text:
import unittest
from conans.model.ref import ConanFileReference, PackageReference
from conans.test.utils.cpp_test_files import cpp_hello_conan_files
from conans.paths import (CONANFILE_TXT, BUILD_INFO_CMAKE, BUILD_INFO_GCC, CONANINFO,
                          BUILD_INFO_VISUAL_STUDIO, BUILD_INFO_XCODE)
from conans.util.files import save, load
import os
from conans.test.utils.tools import TestClient
from conans.test.utils.test_files import temp_folder

class FlatRequirementsTest(unittest.TestCase):

    def setUp(self):
        self.conan_reference = ConanFileReference.loads("Hello0/0.1@lasote/stable")
        self.files = cpp_hello_conan_files("Hello0", "0.1", build=False)
        self.conan = TestClient()
        self.conan.save(self.files)
        self.conan.run("export lasote/stable")

    def consumer_with_flat_requirement_test(self):
        # We want to reuse exported Hello0/0.1@lasote/stable
        tmp_dir = temp_folder()
        req_file = '''[requires]
Hello0/0.1@lasote/stable # My req comment
[generators]
gcc # I need this generator for..
cmake
visual_studio
xcode
'''
        save(os.path.join(tmp_dir, CONANFILE_TXT), req_file)

        self.conan.current_folder = tmp_dir
        # Install requirements
        self.conan.run('install --build missing')
        self.assertEqual(sorted([CONANFILE_TXT, BUILD_INFO_GCC, BUILD_INFO_CMAKE,
                                 BUILD_INFO_VISUAL_STUDIO, BUILD_INFO_XCODE, CONANINFO]),
                         sorted(os.listdir(tmp_dir)))

        cmake = load(os.path.join(tmp_dir, BUILD_INFO_CMAKE))
        gcc = load(os.path.join(tmp_dir, BUILD_INFO_GCC))

        self.assertIn("CONAN_INCLUDE_DIRS", cmake)
        self.assertIn("CONAN_LIB_DIRS", cmake)
        self.assertIn("CONAN_LIBS", cmake)

        self.assertIn("CONAN_INCLUDE_DIRS", cmake)
        self.assertIn("CONAN_LIB_DIRS", cmake)
        self.assertIn(".conan/data/Hello0/0.1/lasote/stable/package", cmake)

        self.assertIn("-L", gcc)
        self.assertIn("-l", gcc)
        self.assertIn("-I", gcc)

        self.assertIn(".conan/data/Hello0/0.1/lasote/stable/package", gcc)

        # CHECK VISUAL STUDIO GENERATOR

        from xml.dom import minidom
        xmldoc = minidom.parse(os.path.join(tmp_dir, BUILD_INFO_VISUAL_STUDIO))
        definition_group = xmldoc.getElementsByTagName('ItemDefinitionGroup')[0]
        compiler = definition_group.getElementsByTagName("ClCompile")[0]

        include_dirs = compiler.getElementsByTagName("AdditionalIncludeDirectories")[0].firstChild.data
        definitions = compiler.getElementsByTagName("PreprocessorDefinitions")[0].firstChild.data

        linker = definition_group.getElementsByTagName("Link")[0]
        lib_dirs = linker.getElementsByTagName("AdditionalLibraryDirectories")[0].firstChild.data
        libs = linker.getElementsByTagName("AdditionalDependencies")[0].firstChild.data

        package_id = os.listdir(self.conan.paths.packages(self.conan_reference))[0]
        package_ref = PackageReference(self.conan_reference, package_id)
        package_paths = self.conan.paths.package(package_ref).replace("\\", "/")

        expected_lib_dirs = os.path.join(package_paths, "lib").replace("\\", "/")
        expected_include_dirs = os.path.join(package_paths, "include").replace("\\", "/")

        self.assertIn(expected_lib_dirs, lib_dirs)
        self.assertEquals("helloHello0.lib;%(AdditionalDependencies)", libs)
        self.assertEquals("%(PreprocessorDefinitions)", definitions)
        self.assertIn(expected_include_dirs, include_dirs)

        # CHECK XCODE GENERATOR
        xcode = load(os.path.join(tmp_dir, BUILD_INFO_XCODE))

        self.assertIn('LIBRARY_SEARCH_PATHS = $(inherited) "%s"' % expected_lib_dirs, xcode)
        self.assertIn('HEADER_SEARCH_PATHS = $(inherited) "%s"' % expected_include_dirs, xcode)
        self.assertIn("GCC_PREPROCESSOR_DEFINITIONS = $(inherited)", xcode)
        self.assertIn("OTHER_CFLAGS = $(inherited)", xcode)
        self.assertIn("OTHER_CPLUSPLUSFLAGS = $(inherited)", xcode)


text:
* Added node 0.10 support, removed coffee-script dependency.

# uglify-js-brunch 1.5.0 (15 January 2013)
* Updated to uglify 2.2.
* Added source maps support.
* Improved installation process.

# uglify-js-brunch 1.3.1 (16 July 2012)
* Switched to better error reporting.

# uglify-js-brunch 1.3.0 (29 June 2012)
* Added node.js 0.8 and 0.9 support.
* Package is now precompiled before every publishing to npm.

# uglify-js-brunch 1.1.1 (15 April 2012)
* Fixed error reporting when installing the package.

# uglify-js-brunch 1.1.0 (9 April 2012)
* Added windows support.

# uglify-js-brunch 1.0.0 (8 March 2012)
* Initial release

redpajama_set_name: RedPajamaGithub


text:
EMAIL=$(git config user.email)
if [[ $EMAIL == *"alibaba-inc"* ]] || [[ $EMAIL == *"taobao"* ]]
then
echo "email with *.alibaba-inc.com or *.taobao.com are not allowed";
exit 1;
else
echo "";
fi;


text:
{% extends 'layout.html' %}

{% block content %}

{% include "_header.html" %}

  {% block breadcrumb %}{% endblock %}

  {% include "_messages.html" %}

  {% block page %}{% endblock page %}

{% include "_footer.html" %}

{% endblock %}


text:
[![Gem Version](https://badge.fury.io/rb/dead_gems.svg)](http://badge.fury.io/rb/dead_gems)
[![Build Status](https://travis-ci.org/jbodah/dead_gems.svg)](https://travis-ci.org/jbodah/dead_gems)

lists your app's unused gems

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'dead_gems'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install dead_gems

## Usage

`DeadGems::find` is the main entry point. It takes the path to your project's root (which should contain your Gemfile) and a shell command to use in that project that should touch as much of your code as possible.

**NOTE** This will take a long time as it uses [TracePoint](http://ruby-doc.org/core-2.0.0/TracePoint.html) to check the source location of every method call to see if the code being leveraged is in a gem directory.

```rb
# First make sure to backup any changes you have (e.g. commit them to git, stash them, etc)
$ irb
$ irb(main)> require 'dead_gems'
$ irb(main)> DeadGems.find('~/my_slow_project', 'bundle exec rake test')

# You can also specify the path to your test helper if you are using RSpec or something
$ irb(main)> DeadGems.find('~/my_slow_project', 'bundle exec rake test', test_helper: 'spec/spec_helper.rb')
```

This will run my project's tests and output all of the gems that aren't used in my tests.

## Contributing

1. Fork it ( https://github.com/jbodah/dead_gems/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
from network import LoRa
import binascii
import pycom
import os

EXPECTED_MAC_ADDRESS = b"{MAC_ADDRESS}"

lora = LoRa(mode=LoRa.LORA)

if binascii.hexlify(lora.mac()) == EXPECTED_MAC_ADDRESS  and os.uname().release == "{FW_VERSION}" and 'LoPy' in os.uname().machine:
    pycom.heartbeat(False)
    pycom.rgbled(0x008000)   # green
    print('Test OK')
    while True:
        pass
else:
    print('Test failed')


text:
iRECEPTION
==========

iRECEPTION: ESS-TOP-L-DIR- EnterpriseComponents and hopefully NetUs Sum Fine Rum and Turbo-Dubstep Via-RdioPython.


text:
<?php

/**
 * Generated command class for `hg grep`
 *
 * @generated
 * @see     http://selenic.com/hg/help/grep
 * @package libhg.Command.Grep
 */
class libhg_Command_Grep_Cmd extends libhg_Command_Grep_Base {
	/**
	 * evaluate server's respond to runcommand
	 *
	 * @param  libhg_Stream_Readable      $reader  readable stream
	 * @param  libhg_Stream_Writable      $writer  writable stream
	 * @param  libhg_Repository_Interface $repo    used repository
	 * @return libhg_Command_Grep_Result
	 */
	public function evaluate(libhg_Stream_Readable $reader, libhg_Stream_Writable $writer, libhg_Repository_Interface $repo) {
		$output = trim($reader->readString(libhg_Stream::CHANNEL_OUTPUT));
		$code   = $reader->readReturnValue();

		return new libhg_Command_Grep_Result($output, $code);
	}
}


text:
 Sign In

    <form class="form-horizontal" ng-submit="signin(user)">

        Error: {{errorMessage}}

        Username

          <input type="text" autofocus ng-model="user.username" id="inputUsername" >

        Password

          <input type="password" ng-model="user.password" id="inputPassword" >

        <button class="btn btn-primary">Sign In</button>

    </form>


text: A message queue for C


text:
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */

import Page = require('../../../../base/Page');
import Response = require('../../../../http/response');
import Sync = require('../../Sync');
import { DocumentPermissionList } from './document/documentPermission';
import { DocumentPermissionListInstance } from './document/documentPermission';
import { SerializableClass } from '../../../../interfaces';

/**
 * Initialize the DocumentList
 *
 * PLEASE NOTE that this class contains preview products that are subject to
 * change. Use them with caution. If you currently do not have developer preview
 * access, please contact help@twilio.com.
 *
 * @param version - Version of the resource
 * @param serviceSid - The service_sid
 */
declare function DocumentList(version: Sync, serviceSid: string): DocumentListInstance;

/**
 * Options to pass to update
 *
 * @property data - The data
 * @property ifMatch - The If-Match HTTP request header
 */
interface DocumentInstanceUpdateOptions {
  data: object;
  ifMatch?: string;
}

interface DocumentListInstance {
  /**
   * @param sid - sid of instance
   */
  (sid: string): DocumentContext;
  /**
   * create a DocumentInstance
   *
   * @param callback - Callback to handle processed record
   */
  create(callback?: (error: Error | null, item: DocumentInstance) => any): Promise<DocumentInstance>;
  /**
   * create a DocumentInstance
   *
   * @param opts - Options for request
   * @param callback - Callback to handle processed record
   */
  create(opts?: DocumentListInstanceCreateOptions, callback?: (error: Error | null, item: DocumentInstance) => any): Promise<DocumentInstance>;
  /**
   * Streams DocumentInstance records from the API.
   *
   * This operation lazily loads records as efficiently as possible until the limit
   * is reached.
   *
   * The results are passed into the callback function, so this operation is memory
   * efficient.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param callback - Function to process each record
   */
  each(callback?: (item: DocumentInstance, done: (err?: Error) => void) => void): void;
  /**
   * Streams DocumentInstance records from the API.
   *
   * This operation lazily loads records as efficiently as possible until the limit
   * is reached.
   *
   * The results are passed into the callback function, so this operation is memory
   * efficient.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param opts - Options for request
   * @param callback - Function to process each record
   */
  each(opts?: DocumentListInstanceEachOptions, callback?: (item: DocumentInstance, done: (err?: Error) => void) => void): void;
  /**
   * Constructs a document
   *
   * @param sid - The sid
   */
  get(sid: string): DocumentContext;
  /**
   * Retrieve a single target page of DocumentInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param callback - Callback to handle list of records
   */
  getPage(callback?: (error: Error | null, items: DocumentPage) => any): Promise<DocumentPage>;
  /**
   * Retrieve a single target page of DocumentInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param targetUrl - API-generated URL for the requested results page
   * @param callback - Callback to handle list of records
   */
  getPage(targetUrl?: string, callback?: (error: Error | null, items: DocumentPage) => any): Promise<DocumentPage>;
  /**
   * Lists DocumentInstance records from the API as a list.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param callback - Callback to handle list of records
   */
  list(callback?: (error: Error | null, items: DocumentInstance[]) => any): Promise<DocumentInstance[]>;
  /**
   * Lists DocumentInstance records from the API as a list.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param opts - Options for request
   * @param callback - Callback to handle list of records
   */
  list(opts?: DocumentListInstanceOptions, callback?: (error: Error | null, items: DocumentInstance[]) => any): Promise<DocumentInstance[]>;
  /**
   * Retrieve a single page of DocumentInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param callback - Callback to handle list of records
   */
  page(callback?: (error: Error | null, items: DocumentPage) => any): Promise<DocumentPage>;
  /**
   * Retrieve a single page of DocumentInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param opts - Options for request
   * @param callback - Callback to handle list of records
   */
  page(opts?: DocumentListInstancePageOptions, callback?: (error: Error | null, items: DocumentPage) => any): Promise<DocumentPage>;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
}

/**
 * Options to pass to create
 *
 * @property data - The data
 * @property uniqueName - The unique_name
 */
interface DocumentListInstanceCreateOptions {
  data?: object;
  uniqueName?: string;
}

/**
 * Options to pass to each
 *
 * @property callback -
 *                         Function to process each record. If this and a positional
 *                         callback are passed, this one will be used
 * @property done - Function to be called upon completion of streaming
 * @property limit -
 *                         Upper limit for the number of records to return.
 *                         each() guarantees never to return more than limit.
 *                         Default is no limit
 * @property pageSize -
 *                         Number of records to fetch per request,
 *                         when not set will use the default value of 50 records.
 *                         If no pageSize is defined but a limit is defined,
 *                         each() will attempt to read the limit with the most efficient
 *                         page size, i.e. min(limit, 1000)
 */
interface DocumentListInstanceEachOptions {
  callback?: (item: DocumentInstance, done: (err?: Error) => void) => void;
  done?: Function;
  limit?: number;
  pageSize?: number;
}

/**
 * Options to pass to list
 *
 * @property limit -
 *                         Upper limit for the number of records to return.
 *                         list() guarantees never to return more than limit.
 *                         Default is no limit
 * @property pageSize -
 *                         Number of records to fetch per request,
 *                         when not set will use the default value of 50 records.
 *                         If no page_size is defined but a limit is defined,
 *                         list() will attempt to read the limit with the most
 *                         efficient page size, i.e. min(limit, 1000)
 */
interface DocumentListInstanceOptions {
  limit?: number;
  pageSize?: number;
}

/**
 * Options to pass to page
 *
 * @property pageNumber - Page Number, this value is simply for client state
 * @property pageSize - Number of records to return, defaults to 50
 * @property pageToken - PageToken provided by the API
 */
interface DocumentListInstancePageOptions {
  pageNumber?: number;
  pageSize?: number;
  pageToken?: string;
}

interface DocumentPayload extends DocumentResource, Page.TwilioResponsePayload {
}

interface DocumentResource {
  account_sid: string;
  created_by: string;
  data: object;
  date_created: Date;
  date_updated: Date;
  links: string;
  revision: string;
  service_sid: string;
  sid: string;
  unique_name: string;
  url: string;
}

interface DocumentSolution {
  serviceSid?: string;
}

declare class DocumentContext {
  /**
   * Initialize the DocumentContext
   *
   * PLEASE NOTE that this class contains preview products that are subject to
   * change. Use them with caution. If you currently do not have developer preview
   * access, please contact help@twilio.com.
   *
   * @param version - Version of the resource
   * @param serviceSid - The service_sid
   * @param sid - The sid
   */
  constructor(version: Sync, serviceSid: string, sid: string);

  documentPermissions: DocumentPermissionListInstance;
  /**
   * fetch a DocumentInstance
   *
   * @param callback - Callback to handle processed record
   */
  fetch(callback?: (error: Error | null, items: DocumentInstance) => any): Promise<DocumentInstance>;
  /**
   * remove a DocumentInstance
   *
   * @param callback - Callback to handle processed record
   */
  remove(callback?: (error: Error | null, items: DocumentInstance) => any): Promise<boolean>;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
  /**
   * update a DocumentInstance
   *
   * @param opts - Options for request
   * @param callback - Callback to handle processed record
   */
  update(opts: DocumentInstanceUpdateOptions, callback?: (error: Error | null, items: DocumentInstance) => any): Promise<DocumentInstance>;
}

declare class DocumentInstance extends SerializableClass {
  /**
   * Initialize the DocumentContext
   *
   * PLEASE NOTE that this class contains preview products that are subject to
   * change. Use them with caution. If you currently do not have developer preview
   * access, please contact help@twilio.com.
   *
   * @param version - Version of the resource
   * @param payload - The instance payload
   * @param serviceSid - The service_sid
   * @param sid - The sid
   */
  constructor(version: Sync, payload: DocumentPayload, serviceSid: string, sid: string);

  private _proxy: DocumentContext;
  accountSid: string;
  createdBy: string;
  data: any;
  dateCreated: Date;
  dateUpdated: Date;
  /**
   * Access the documentPermissions
   */
  documentPermissions(): DocumentPermissionListInstance;
  /**
   * fetch a DocumentInstance
   *
   * @param callback - Callback to handle processed record
   */
  fetch(callback?: (error: Error | null, items: DocumentInstance) => any): Promise<DocumentInstance>;
  links: string;
  /**
   * remove a DocumentInstance
   *
   * @param callback - Callback to handle processed record
   */
  remove(callback?: (error: Error | null, items: DocumentInstance) => any): Promise<boolean>;
  revision: string;
  serviceSid: string;
  sid: string;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
  uniqueName: string;
  /**
   * update a DocumentInstance
   *
   * @param opts - Options for request
   * @param callback - Callback to handle processed record
   */
  update(opts: DocumentInstanceUpdateOptions, callback?: (error: Error | null, items: DocumentInstance) => any): Promise<DocumentInstance>;
  url: string;
}

declare class DocumentPage extends Page<Sync, DocumentPayload, DocumentResource, DocumentInstance> {
  /**
   * Initialize the DocumentPage
   *
   * PLEASE NOTE that this class contains preview products that are subject to
   * change. Use them with caution. If you currently do not have developer preview
   * access, please contact help@twilio.com.
   *
   * @param version - Version of the resource
   * @param response - Response from the API
   * @param solution - Path solution
   */
  constructor(version: Sync, response: Response<string>, solution: DocumentSolution);

  /**
   * Build an instance of DocumentInstance
   *
   * @param payload - Payload response from the API
   */
  getInstance(payload: DocumentPayload): DocumentInstance;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
}

export { DocumentContext, DocumentInstance, DocumentInstanceUpdateOptions, DocumentList, DocumentListInstance, DocumentListInstanceCreateOptions, DocumentListInstanceEachOptions, DocumentListInstanceOptions, DocumentListInstancePageOptions, DocumentPage, DocumentPayload, DocumentResource, DocumentSolution }


text:
---
layout: post
title: Mongoose简单的连表查询
description: "使用populate属性"
tags: [Mongoose]
image:
  background: triangular.png
comments: true
share: true
---

像我这篇文章所说的基于Node.js + jade + Mongoose 模仿gokk.tv,当时停止开发是因为我深深的感觉到当时想错了,应该用两个Schema,而不是一个下面又有数组来存,这样取数据是方便,当时分页相当麻烦,不能使用原生提供的limit方法。

今天看到一本书上有讲,尝试了一把,记录下来

我们实验的场景为一个班级有N多学生,先通过学生ID找到班级名称(是不是被玩腻了?)

先来将Schema定义好

ClazzSchema :

{% highlight JavaScript %}
var mongoose = require('mongoose')

var ClazzSchema = new mongoose.Schema({
	clazzName:String
})
//其他方法省略..
}

module.exports = ClazzSchema

{% endhighlight %}

StudentSchema :

{% highlight JavaScript %}
var mongoose = require('mongoose')

var StudentSchema = new mongoose.Schema({
	name:String,
	clazzID : {
		type : mongoose.Schema.ObjectId,
		ref : 'Clazz'
	}
})

StudentSchema.statics = {
	findClazzNameByStudentId:function(studentId, callback){
			return this
				.findOne({_id : studentId}).populate('clazzID')
				.exec(callback)
		}
	//其他方法省略..
}

module.exports = StudentSchema

{% endhighlight %}

可以看到,主需要将ClazzID设为ref到Clazz,依赖为你建立Model时的名称就可以了,要查询Clzz使用populate

下面是Model

{% highlight JavaScript %}
var mongoose = require('mongoose')
var ClazzSchema = require('../schemas/clazzSchema')
var Clazz = mongoose.model('Clazz',ClazzSchema)

module.exports  = Clazz
{% endhighlight %}

{% highlight JavaScript %}
var mongoose = require('mongoose')
var StudentSchema = require('../schemas/studentSchema')
var Student = mongoose.model('Student',StudentSchema)

module.exports  = Student
{% endhighlight %}

大同小异,着重看test.js

{% highlight JavaScript %}
var mongoose = require('mongoose')
var Clazz = require('./models/clazzModel')
var Student = require('./models/studentModel')
//var db = mongoose.createConnection('localhost', 'gokk')
mongoose.connect('mongodb://localhost/test')

/*var clazz = new Clazz(
	{
		clazzName:'软件2班'
	}
);

clazz.save(function  (argument){
	console.log('true');
});*/

/*var student = new Student({
	name : 'hacke2',
	clazzID : '542b5fcc49df6e741d8d15f5'
})
student.save(function (err){
	console.log('true');
})*/

Student.findClazzNameByStudentId('542b600a683d59a80d4ee632', function (err, student){
	if(err) console.log(err);
	console.log(student.clazzID.clazzName);
})
{% endhighlight %}

之前添加了两班级:软件一班和软件二班

我们在新增hacke2时将classID设为软件2班的,查新hacke2时自动就会把关键的
Class查询到

{% highlight JavaScript %}
{ _id: 542b600a683d59a80d4ee632,
    name: 'hacke2',
    clazzID: { _id: 542b5fcc49df6e741d8d15f5, clazzName: '软件2班', __v: 0 },
    __v: 0 }
{% endhighlight %}
end from  {{ site.url }}


text:
package eu.openanalytics.rsb;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.nio.file.Files;

import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.eclipse.statet.jcommons.lang.Nullable;

import com.icegreen.greenmail.store.FolderException;
import com.icegreen.greenmail.user.GreenMailUser;
import com.icegreen.greenmail.util.GreenMailUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.After;
import org.junit.Test;

/**
 * @author "Open Analytics <rsb.development@openanalytics.eu>"
 */
public class EmailDepositITCase extends AbstractITCase {

	public EmailDepositITCase() {
	}

	@After
	public void purgeReceivedEmails() throws FolderException {
		SuiteITCase.greenMail.getManagers()
				.getImapHostManager()
				.getInbox(SuiteITCase.userAccount)
				.deleteAllMessages();
	}

	@Test
	public void submissionToAccountWithDefaultSettings() throws Exception {
		final String subject= sendZipJobEmail(SuiteITCase.rsbAccountWithDefaultSettings, "r-job-sample.zip");
		final MimeMessage rsbResponseMessage= ponderForRsbResponse(subject);
		verifyValidResultWithDefaultResponse(rsbResponseMessage);
	}

	@Test
	public void submissionToAccountWithDefaultSettingsPop3() throws Exception {
		final String subject= sendZipJobEmail(SuiteITCase.rsbAccountWithDefaultSettingsPop3, "r-job-sample.zip");
		final MimeMessage rsbResponseMessage= ponderForRsbResponse(subject);
		verifyValidResultWithDefaultResponse(rsbResponseMessage);
	}

	@Test
	public void submissionToAccountWithResponseFile() throws Exception {
		final String subject= sendZipJobEmail(SuiteITCase.rsbAccountWithResponseFile, "r-job-sample.zip");
		final MimeMessage rsbResponseMessage= ponderForRsbResponse(subject);
		verifyValidResult(rsbResponseMessage,
				Files.readString(getTestDataFile("test-email-response.txt")) );
	}

	@Test
	public void submissionToAccountWithJobConfiguration() throws Exception {
		final String subject= sendJobEmail(SuiteITCase.rsbAccountWithJobConfiguration,
			"fake data".getBytes(), "application/octet-stream", "data.bin");
		final MimeMessage rsbResponseMessage= ponderForRsbResponse(subject);
		verifyValidResultWithDefaultResponse(rsbResponseMessage);
	}

	@Test
	public void submissionOfUnprocessableJob() throws Exception {
		final String subject= sendZipJobEmail(SuiteITCase.rsbAccountWithResponseFile,
			"r-job-meta-required.zip");
		final MimeMessage rsbResponseMessage= ponderForRsbResponse(subject);
		verifyErrorResult(rsbResponseMessage, null);
	}

	@Test
	public void submissionOfInvalidZip() throws Exception {
		final String subject= sendZipJobEmail(SuiteITCase.rsbAccountWithResponseFile,
				"invalid-job-subdir.zip" );
		final MimeMessage rsbResponseMessage= ponderForRsbResponse(subject);
		verifyErrorResult(rsbResponseMessage, "invalid zip");
	}

	@Test
	public void submissionOfInvalidZipPop3() throws Exception {
		final String subject= sendZipJobEmail(SuiteITCase.rsbAccountWithDefaultSettingsPop3,
				"invalid-job-subdir.zip" );
		final MimeMessage rsbResponseMessage= ponderForRsbResponse(subject);
		verifyErrorResult(rsbResponseMessage, "invalid zip");
	}

	private String sendZipJobEmail(final GreenMailUser rsbAccount, final String zipFile)
			throws MessagingException, IOException {
		return sendJobEmail(rsbAccount,
				Files.readAllBytes(getTestDataFile(zipFile)), "application/zip", zipFile );
	}

	private String sendJobEmail(final GreenMailUser rsbAccount,
			final byte[] data, final String contentType, final String filename)
			throws MessagingException, IOException {
		final String subject= RandomStringUtils.randomAlphanumeric(20);

		GreenMailUtil.sendAttachmentEmail(rsbAccount.getEmail(), SuiteITCase.userAccount.getEmail(),
				subject, "some work for you",
				data, contentType, filename, "test job",
				SuiteITCase.greenMail.getSmtp().getServerSetup() );

		return subject;
	}

	private MimeMessage ponderForRsbResponse(final String subject)
			throws InterruptedException, MessagingException {
		final MimeMessage[] rsbResponseMessages= waitForRsbResponse();
		assertEquals(1, rsbResponseMessages.length);
		final MimeMessage rsbResponseMessage= rsbResponseMessages[0];
		assertEquals("RE: " + subject, rsbResponseMessage.getSubject());
		return rsbResponseMessage;
	}

	private void verifyValidResultWithDefaultResponse(final MimeMessage rsbResponseMessage)
			throws IOException, MessagingException {
		final String exceptedResponseBody= getRawMessages().getProperty("email.result.body");
		verifyValidResult(rsbResponseMessage, exceptedResponseBody);
	}

	private void verifyValidResult(final MimeMessage rsbResponseMessage, final String exceptedResponseBody)
			throws IOException, MessagingException {
		final Multipart parts= (Multipart)rsbResponseMessage.getContent();

		final String responseBody= StringUtils.normalizeSpace(
				((MimeMultipart)getMailBodyPart(parts, "multipart/related").getContent())
						.getBodyPart(0).getContent().toString() );

		assertEquals(StringUtils.normalizeSpace(exceptedResponseBody), responseBody);
		assertEquals("rnorm.pdf", getMailBodyPart(parts, "application/pdf").getFileName());
	}

	private void verifyErrorResult(final MimeMessage rsbResponseMessage,
			final @Nullable String expectedCause)
			throws IOException, MessagingException {
		final Multipart parts= (Multipart)rsbResponseMessage.getContent();

		final String responseBody= StringUtils.normalizeSpace(
				((MimeMultipart)getMailBodyPart(parts, "multipart/related").getContent())
						.getBodyPart(0).getContent().toString() );
		assertTrue(StringUtils.containsIgnoreCase(responseBody, "error"));

		if (expectedCause != null) {
			assertTrue(StringUtils.containsIgnoreCase(responseBody, expectedCause));
		}
	}

	private BodyPart getMailBodyPart(final Multipart parts, final String contentType)
			throws MessagingException {
		for (int i= 0; i < parts.getCount(); i++) {
			final BodyPart part= parts.getBodyPart(i);
			if (StringUtils.startsWith(part.getContentType(), contentType)) {
				return part;
			}
		}
		throw new IllegalStateException("No part of type " + contentType + " found");
	}

	private MimeMessage[] waitForRsbResponse() throws InterruptedException {
		MimeMessage[] receivedMessages= fetchMessagesFromUserMailBox();

		int attemptCount= 0;
		while ((receivedMessages.length == 0) && (attemptCount++ < 120)) {
			Thread.yield();
			Thread.sleep(250);
			receivedMessages= fetchMessagesFromUserMailBox();
		}
		return receivedMessages;
	}

	private MimeMessage[] fetchMessagesFromUserMailBox() {
		return SuiteITCase.greenMail.getReceivedMessagesForDomain(SuiteITCase.TEST_USER_EMAIL_DOMAIN);
	}

}


text:
<!DOCTYPE html>

    <title>Issue #430: Do not validate empty fields that is not required.</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" type="text/css" href="../css/validationEngine.jquery.css" />

Issue #430: Do not validate empty fields that is not required.

      See https://github.com/posabsolute/jQuery-Validation-Engine/issues/430
      for information.

    <form id="form" action="/" method="POST">

        Not required, but validate input if value is present.

        <input type="text" name="test_case_1" class="validate[custom[test_value]]" />

        Required, validate input.

        <input type="text" name="test_case_2" class="validate[required, custom[test_value]]" />

      <input type="submit" value="Submit" />
    </form>


text:
$ModuleName = $MyInvocation.MyCommand -replace '\..*' #-replace 'Pester\.' -replace 'Tests\.' -replace 'ps1$', 'psm1'
$ModulePath = "$PSScriptRoot\..\Private\$ModuleName.psm1"
$RequiresLine = Get-Content $ModulePath | where {$_ -match '#requires'} | select -First 1
$RequiredModuleNames = ($RequiresLine -replace '.*-Modules ' -replace ' -\w.*') -split ',\s*'
$RequiredModuleNames | %{
    Import-Module -Name $ModulePath\..\$_
}
Import-Module $ModulePath -Force

Describe $ModuleName {

    #Integration test. Run on domain-joined machine
    Context 'Integration tests' {

        if ((Get-WmiObject Win32_ComputerSystem).DomainRole -in (0,2)) {
            Write-Host "Skipping tests; current host is not joined to a domain"
            $DomainJoined = $false
        } else {
            $DomainJoined = $true
            $Domain = (Get-WmiObject Win32_ComputerSystem).Domain
            $Response = Invoke-Portqry -Server $Domain -Port 88 -Protocol TCP
        }

        It 'Tests TCP 88 to domain FQDN' -Pending:(-not $DomainJoined) {
            $Response.Success | Should Be $true
            $Response.Summary | Should BeExactly 'Listening on TCP-88'
            $Response.PortQryText | Should BeOfType string
        }

    }
}

Remove-Module $ModuleName
$RequiredModuleNames | Remove-Module


text:
import { connect } from 'react-redux';
import React, { Component, PropTypes } from 'react';

// Import Actions
import { selectWinner } from '~/actions/a_picks.js';

export class WinningTeamSelector extends Component {

    handleTeamSelectionChange(gameId) {
        const r = `teamSelector_${gameId}`;
        const winningTeamId = this.refs[r].value || 0;
        this.props.selectWinner(gameId, winningTeamId);
    }

    render() {
        const { game } = this.props;
        const { id, awayTeam, homeTeam } = game;

        return (
            <select ref={`teamSelector_${id}`} onChange={() => { this.handleTeamSelectionChange(id); }}>
                <option>(Select Winner)</option>
                <option value={awayTeam.id}>{awayTeam.mascot}</option>
                <option value={homeTeam.id}>{homeTeam.mascot}</option>
            </select>
        );
    }
}

WinningTeamSelector.propTypes = {
    game: PropTypes.object.isRequired
};

const mapStateToProps = () => ({});

export default connect(mapStateToProps, { selectWinner })(WinningTeamSelector);


text:
package org.apache.pig.test;

import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map.Entry;

import org.apache.commons.io.filefilter.RegexFileFilter;
import org.apache.commons.lang.ArrayUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.mapreduce.v2.MiniMRYarnCluster;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.pig.ExecType;
import org.apache.pig.PigConfiguration;
import org.apache.pig.backend.hadoop.executionengine.Launcher;
import org.apache.pig.backend.hadoop.executionengine.tez.TezExecType;
import org.apache.pig.backend.hadoop.executionengine.tez.TezLauncher;
import org.apache.pig.backend.hadoop.executionengine.tez.TezSessionManager;
import org.apache.tez.dag.api.TezConfiguration;
import org.apache.tez.mapreduce.hadoop.MRJobConfig;
import org.apache.tez.runtime.library.api.TezRuntimeConfiguration;

public class TezMiniCluster extends YarnMiniCluster {

    private static final File TEZ_LIB_DIR = new File("build/ivy/lib/Pig");
    private static final File TEZ_CONF_FILE = new File(CONF_DIR, "tez-site.xml");

    private static final ExecType TEZ = new TezExecType();

    @Override
    public ExecType getExecType() {
        return TEZ;
    }

    @Override
    protected void setupMiniDfsAndMrClusters() {
        super.setupMiniDfsAndMrClusters();
        try {
            // Write tez-site.xml
            Configuration tez_conf = new Configuration(false);
            // TODO PIG-3659 - Remove this once memory management is fixed
            tez_conf.set(TezRuntimeConfiguration.TEZ_RUNTIME_IO_SORT_MB, "20");
            tez_conf.set(TezRuntimeConfiguration.TEZ_RUNTIME_OPTIMIZE_LOCAL_FETCH, "false");
            tez_conf.set("tez.lib.uris", "hdfs:///tez,hdfs:///tez/lib");
            // Set to a lower value so that tests don't get stuck for long because of 1 AM running at a time
            tez_conf.set(TezConfiguration.TEZ_SESSION_AM_DAG_SUBMIT_TIMEOUT_SECS, "20");
            // Lower the max task attempts to 2 so that negative tests fail
            // faster. By default, tasks retry 4 times
            tez_conf.set(TezConfiguration.TEZ_AM_TASK_MAX_FAILED_ATTEMPTS, "2");
            tez_conf.writeXml(new FileOutputStream(TEZ_CONF_FILE));

            // Copy tez jars to hdfs
            m_fileSys.mkdirs(new Path("/tez/lib"));
            FileFilter fileFilter = new RegexFileFilter("tez-.+\\.jar$");
            File[] tezJars = TEZ_LIB_DIR.listFiles(fileFilter);
            for (int i = 0; i < tezJars.length; i++) {
                if (tezJars[i].getName().startsWith("tez-api")) {
                    m_fileSys.copyFromLocalFile(
                            new Path(tezJars[i].getAbsoluteFile().toString()),
                            new Path("/tez"));
                } else {
                    m_fileSys.copyFromLocalFile(
                            new Path(tezJars[i].getAbsoluteFile().toString()),
                            new Path("/tez/lib"));
                }
            }

            // Turn FetchOptimizer off so that we can actually test Tez
            m_conf.set(PigConfiguration.PIG_OPT_FETCH, System.getProperty("test.opt.fetch", "false"));

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void shutdownMiniDfsAndMrClusters() {
        TezSessionManager.shutdown();
        super.shutdownMiniDfsAndMrClusters();
    }

    @Override
    protected void shutdownMiniMrClusters() {
        super.shutdownMiniMrClusters();
    }

    @Override
    protected void deleteConfFiles() {
        super.deleteConfFiles();
        if(TEZ_CONF_FILE.exists()) {
            TEZ_CONF_FILE.delete();
        }
    }

    static public Launcher getLauncher() {
        return new TezLauncher();
    }
}


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using SimpleJSON;

[ExecuteInEditMode]
public class Grid : Singleton<Grid>
{
    [SerializeField]
    private Cell _cellPrefab;

    private static Cell[,] _cells;
    private static Vector2 _gridPosition;

    protected override void OnAwake()
    {
        Build();
    }

    [ContextMenu("Build")]
    public void Build()
    {
        var path = string.Format("Stages/{0}", GameController.Stage);
        var data = JSON.ParseFile(path);

        RowCount = data["rowCount"].AsInt;
        ColumnCount = data["columnCount"].AsInt;
        var cells = data["cells"];

        for (int i = _transform.childCount - 1; i >= 0; i--) {
            DestroyImmediate(_transform.GetChild(i).gameObject);
        }

        var padding = Cell.Size / 6.0f;
        var offset = (-new Vector3(ColumnCount - 1, RowCount - 1) / 2.0f) * (Cell.Size + padding);

        _cells = new Cell[RowCount, ColumnCount];

        for (int row = 0; row < RowCount; row++) {
            for (int column = 0; column < ColumnCount; column++) {
                if (cells[row][column].AsInt == 0) {
                    var cell = Instantiate(_cellPrefab);

                    cell.Transform.SetParent(_transform);
                    cell.Transform.localPosition = new Vector3(column, row) * (Cell.Size + padding) + offset;

                    var loc = new Location(row, column);

                    cell.Location = loc;

                    _cells[row, column] = cell;
                } else {
                    _cells[row, column] = null;
                }
            }
        }

        _gridPosition = Vector2.zero * Cell.Size + new Vector2(offset.x, offset.y);
    }

    public static IEnumerable<Cell> Cells
    {
        get
        {
            for (int row = 0; row < RowCount; row++) {
                for (int column = 0; column < ColumnCount; column++) {
                    yield return _cells[row, column];
                }
            }
        }
    }

    public static Cell GetCell(Location location)
    {
        return GetCell(location.Row, location.Column);
    }
    public static Cell GetCell(Vector3 worldPosition)
    {
        return GetCell(WorldToLocation(worldPosition));
    }

    public static Cell GetCell(int row, int column)
    {
        if (row < 0 || row >= RowCount || column < 0 || column >= ColumnCount) {
            return null;
        }

        return _cells[row, column];
    }

    public static bool IsType(int row, int column, AnimalType type)
    {
        if (row < 0 || row >= RowCount || column < 0 || column >= ColumnCount) {
            return false;
        }

        var cell = _cells[row, column];

        return cell && cell.Animal && cell.Animal.Type == type;
    }

    public static bool IsStill(int row, int column)
    {
        if (row < 0 || row >= RowCount || column < 0 || column >= ColumnCount) {
            return true;
        }

        var cell = _cells[row, column];

        return cell && cell.Animal && !cell.Animal.IsFalling;
    }

    public static Vector3 LocationToWorld(Location location)
    {
        var x = _gridPosition.x + location.Column * (Cell.Size + Cell.Size / 6.0f);
        var y = _gridPosition.y + location.Row * (Cell.Size + Cell.Size / 6.0f);

        return new Vector3(x, y);
    }

    public static Location WorldToLocation(Vector3 worldPosition)
    {
        int column = Mathf.RoundToInt((worldPosition.x - _gridPosition.x) / (Cell.Size + Cell.Size / 6.0f));
        int row = Mathf.RoundToInt((worldPosition.y - _gridPosition.y) / (Cell.Size + Cell.Size / 6.0f));

        return new Location(row, column);
    }

    public static int RowCount { get; private set; }
    public static int ColumnCount { get; private set; }
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>ACE Editor Example</title>
    <link rel="stylesheet" type="text/css" href="http://extjs.cachefly.net/extjs-4.1.1-gpl/resources/css/ext-all.css" />
    <link rel="stylesheet" type="text/css" href="http://extjs.cachefly.net/extjs-4.1.1-gpl/examples/shared/example.css" />

ACE Editor Example

The js is not minified so it is readable. See aceeditor.js.

Note: Works with 4.1.1

function foo(items) {
    var i;
    for (i = 0; i < items.length; i++) {
        alert("Ace Rocks " + items[i]);
    }
}


text:
<?php

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model backend\models\AuthAssignment */

$this->title = 'User Permissions';
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Auth Assignments'), 'url' => ['index']];
$this->params['breadcrumbs'][] = Yii::t('app', 'Update');
?>
<div class="auth-assignment-update">

    <?= $this->render('_form', [
        'userPermissionmodel'=>$userPermissionmodel,
        'userPermissionGroupsmodel'=>$userPermissionGroupsmodel,
        'model1'=>$userPermissionAuthItemModel,
        'model2'=>$userPermissionAuthItemGroupModel,
    ]) ?>

</div>


text:
from Tkinter import *

class Application(Frame):
    def Build_CSV(self):
        dt_selected = self.var1.get()
        print(dt_selected)
        try:
            indx_date = self.lst1.index(dt_selected)+1
            print(indx_date)
        except:
            print"Please Select a date"

    def createWidgets(self):
        self.QUIT = Button(self)
        self.QUIT["text"] = "QUIT"
        self.QUIT["fg"]   = "red"
        self.QUIT["command"] =  self.quit

        self.QUIT.pack({"side": "left"})

        self.CSV_build = Button(self)
        self.CSV_build ["text"] = "Create CSV",
        self.CSV_build ["command"] = self.Build_CSV
        self.CSV_build .pack({"side": "left"})

        self.lst1 = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug',
                    'Sep','Oct','Nov','Dec']
        self.var1 = StringVar()
        self.drop = OptionMenu(root,self.var1,*self.lst1)
        self.drop.grid()
        self.drop.pack({"side": "left"})

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

root = Tk()
app = Application(master=root)
root.geometry('{}x{}'.format(500, 500))
app.mainloop()
root.destroy()


text:
//TODO: instead of using helper methods this should be an API that does things.
export const STATES = {
  OUTER_SPACE: 'OUTER_SPACE',
  HTML_TAG: 'HTML_TAG',
  HTML_BODY: 'HTML_BODY',
  HTML_ELEMENT: 'HTML_BODY',
  HTML_ATTRIBUTE: 'HTML_ATTRIBUTE',
  ESCAPABLE_RAW: 'ESCAPABLE_RAW',
  TORNADO_TAG: 'TORNADO_TAG',
  TORNADO_BODY: 'TORNADO_BODY'
};
const methodNameMap = {
  register: 'r',
  get: 'g',
  createDocumentFragment: 'f',
  createTextNode: 't',
  createHTMLComment: 'c',
  createElement: 'm',
  setAttribute: 'a',
  getPartial: 'p',
  replaceNode: 'n',
  exists: 'e',
  helper: 'h',
  block: 'b',
  getNodeAtIdxPath: 'i',
  nodeToString: 's'
};
const PRODUCTION = 'production';
let mode = 'dev'; //TODO: this should be an option in the compiler

export default {
  /**
   * Return a method name based on whether we are compiling for production or dev
   * @param {String} fullName The full name of the method
   * @return {String} Return the shortened alias name or the fullName
   */
  getTdMethodName(fullName) {
    if (mode === PRODUCTION) {
      return methodNameMap[fullName];
    } else {
      return fullName;
    }
  },

  /**
   * Adjust an attribute's name as necessary (e.g. SVG cares about case)
   * @param {String} elType The element's tag name
   * @param {String} attrName The attribute's name before adjustment
   * @return {String} The adjusted attribute name (or the given attribute name if no adjustment
   * is needed)
   */
  adjustAttrName(elType, attrName, ctx) {
    if (ctx.namespace) {
      attrName = this.svgAdjustAttrs[attrName] || attrName;
    }
    return attrName;
  },

  elTypes: {
    escapableRaw: ['textarea', 'title']
  },

  /**
   * whether we are in an html_attribute given the current state
   * NOTE: when we see a tornado body previous states are reset.
   * @param {Array} state  the current stateStack
   * @return {Boolean}
   */
  inHtmlAttribute: function(state) {
    let lastTornadoBodyIdx = state.lastIndexOf(STATES.TORNADO_BODY),
        lastHtmlAttributeIdx = state.lastIndexOf(STATES.HTML_ATTRIBUTE);
    return lastHtmlAttributeIdx > lastTornadoBodyIdx;
  },

  /**
   * whether we are in an escapable_raw given the current state
   * NOTE: when we see a tornado body previous states are reset.
   * @param {Array} state  the current stateStack
   * @return {Boolean}
   */
  inEscapableRaw: function(state) {
    let lastTornadoBodyIdx = state.lastIndexOf(STATES.TORNADO_BODY),
        lastEscapableRawIdx = state.lastIndexOf(STATES.ESCAPABLE_RAW);
    return lastEscapableRawIdx > lastTornadoBodyIdx;
  }

};


text:
package com.comcast.cdn.traffic_control.traffic_monitor.wicket.components;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.json.JSONArray;
import org.apache.wicket.ajax.json.JSONException;
import org.apache.wicket.ajax.json.JSONObject;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.extensions.ajax.markup.html.AjaxEditableChoiceLabel;
import org.apache.wicket.extensions.ajax.markup.html.AjaxEditableLabel;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.util.WildcardListModel;

import com.comcast.cdn.traffic_control.traffic_monitor.config.ConfigHandler;
import com.comcast.cdn.traffic_control.traffic_monitor.config.MonitorConfig;
import com.comcast.cdn.traffic_control.traffic_monitor.health.TmWatcher;
import com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher;

public class EditConfigPanel extends Panel {
	private static final Logger LOGGER = Logger.getLogger(EditConfigPanel.class);
	private static final long serialVersionUID = 1L;

	private static final String TM_HOSTNAME_KEY = "tm.hostname";
	private static final String CDN_NAME_KEY = "cdnName";
	AjaxEditableChoiceLabel<String> cdnName;

	public EditConfigPanel(final String id) {
		super(id);

		final MonitorConfig config = ConfigHandler.getConfig();

		if (config == null || !config.allowConfigEdit()) {
			return;
		}

		final WebMarkupContainer c = new WebMarkupContainer("configeditpanel");
		add(c);

		this.setOutputMarkupId(true);
		final Form<MonitorConfig>myeditform = new Form<MonitorConfig>("configform");
		setForm(myeditform, ConfigHandler.getConfig().getBaseProps());
		c.add(myeditform);
	}

	private final void setForm(final Form<MonitorConfig> editform, final Map<String, String> baseconfig) {
		final MonitorConfig config = ConfigHandler.getConfig();

		if (config == null || !config.allowConfigEdit()) {
			return;
		}

		final List<String> keys = sort(baseconfig.keySet());
		keys.remove(TM_HOSTNAME_KEY);
		keys.remove(CDN_NAME_KEY);

		final List<String> TM_HOSTS = Arrays.asList(new String[] {
				"tm.company.net"
			});
		final ArrayList<String> cdnList = new ArrayList<String>();
		final String hostName = baseconfig.get(TM_HOSTNAME_KEY);
		setCdnList(cdnList, hostName);
		final AjaxEditableChoiceLabel<String> tmHost = new AjaxEditableChoiceLabel<String>(
				"tmHost", new BaseConfigModel(TM_HOSTNAME_KEY, baseconfig), TM_HOSTS) {
			private static final long serialVersionUID = 1L;
			@Override
			protected void onSubmit(final AjaxRequestTarget target) {
				super.onSubmit(target);
				final String hostName = baseconfig.get(TM_HOSTNAME_KEY);
				setCdnList(cdnList, hostName);
				target.add(cdnName);
			}
		};
//		listSites
		editform.add(tmHost);

		cdnName = new AjaxEditableChoiceLabel<String>(
				CDN_NAME_KEY, new BaseConfigModel(CDN_NAME_KEY, baseconfig),  new WildcardListModel<String>(cdnList));
//		listSites
		editform.add(cdnName);

		final ListView<String> propView = new ListView<String>("propList", keys) {
			private static final long serialVersionUID = 1L;

			@Override
			protected void populateItem(final ListItem<String> item) {
				final String key = item.getModelObject();

				final Label label = new Label("key", key);
				item.add(label);

				//				editform.add(new TextField("value", new Model<String>(baseconfig.get(key)))) ;
				item.add(new AjaxEditableLabel<String>("value", new BaseConfigModel(key, baseconfig)));

				item.add(label);
			}
		};
		editform.add(propView);

		editform.add(new AjaxLink<Object>("cancel") {
			private static final long serialVersionUID = 1L;
			@Override
			public void onClick(final AjaxRequestTarget target) {
				final Map<String, String> oldProps = ConfigHandler.getConfig().getBaseProps();
				baseconfig.putAll(oldProps);
				final String hostName = baseconfig.get(TM_HOSTNAME_KEY);
				setCdnList(cdnList, hostName);
				if(target != null) {
					target.add(EditConfigPanel.this);
				}
			}
		});
		editform.add(new AjaxButton("submit", editform) {
			private static final long serialVersionUID = 1L;
			@Override
			public void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
				try {
					ConfigHandler.saveBaseConfig(baseconfig);
					TmWatcher.getInstance().refresh();
				} catch (JSONException e) {
					LOGGER.warn(e,e);
				} catch (IOException e) {
					LOGGER.warn(e,e);
				}
//				EditConfigPanel.this.showForm(false);
				if(target != null) {
					target.add(EditConfigPanel.this);
				}
			}
		});
	}

	protected final void setCdnList(final List<String> cdnList, final String hostName) {
		final MonitorConfig config = ConfigHandler.getConfig();

		if (config == null || !config.allowConfigEdit()) {
			return;
		}

		cdnList.clear();
		try {
			final File file = Fetcher.downloadTM("https://"+hostName+"/dataparameter", config.getAuthUrl(), config.getAuthUsername(), config.getAuthPassword(), 500);
			final String str = IOUtils.toString(new FileReader(file));
			file.delete();
			final JSONArray ja = new JSONArray(str);
//			LOGGER.warn(ja.toString(2));
			for(int i = 0; i < ja.length(); i++) {
				// "name": "CDN_name",
				final JSONObject jo = ja.getJSONObject(i);
				if("CDN_name".equals(jo.optString("name"))) {
					cdnList.add(jo.optString("value"));
				}
			}
		} catch (java.net.SocketTimeoutException e) {
			cdnList.add(ConfigHandler.getConfig().getBaseProps().get(CDN_NAME_KEY));
			LOGGER.warn("TM timeout");
		} catch (Exception e) {
			cdnList.add(ConfigHandler.getConfig().getBaseProps().get(CDN_NAME_KEY));
			LOGGER.warn(e,e);
		}
	}

	private List<String> sort(final Set<String> props) {
		final TreeSet<String> set = new TreeSet<String>(props);
 		return new ArrayList<String>(set);
	}

	static class BaseConfigModel extends Model<String> {
		private static final long serialVersionUID = 1L;
		final private Map<String, String> config;
		final String key;
		public BaseConfigModel(final String key, final Map<String, String> config) {
			this.key = key;
			this.config = config;
		}
		@Override
		public String getObject( ) {
			if(config == null) { return "[no config]"; }
			final String r = config.get(key);
			if(r == null) { return "[null]"; }
			return r;
		}
		@Override
		public void setObject(final String val ) {
			config.put(key,val);
		}
	}
}


text:
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">

   <meta charset="UTF-8">
   <meta name="robots" content="all">
   <meta name="description" content="An interactive math lesson converting celsius temperature to fahrenheit">
   <meta name="keywords" content="temperature conversion, degrees celsius, fahrenheit">
   <title>Temperature Conversion from Celsius to Fahrenheit</title>

<link rel="stylesheet" type="text/css" href="aaa_style.css">

&nbsp

Temperature Conversion - Celsius to Fahrenheit

The metric system uses the Celsius scale to measure temperature.  However, temperatures
are still measured on the Fahrenheit scale in the U.S.

Water freezes at 0o Celsius and boils at 100o Celsius which is a difference
of 100o.  Water freezes at 32o Fahrenheit and boils at 212o
Fahrenheit which is a difference of 180o.  Therefore each degree on the
Celsius scale is equal to 180/100 or 9/5 degrees on the Fahrenheit scale.

How to convert Celsius temperatures to Fahrenheit

Multiply the Celsius temperature by 9/5.

Add 32o to adjust for the offset in the Fahrenheit scale.

Example: convert 37o C to Fahrenheit.

37 * 9/5 = 333/5 = 66.6

66.6 + 32 = 98.6o F

There is a mental math method to convert from Celsius to Fahrenheit.  The
ratio of 9/5 is equal to 1.8 and 1.8 is equivalent to 2 - 0.2

How to convert Celsius temperatures to Fahrenheit with mental math.

Double the Celsius temperature (multiply by 2).

Take 1/10 of this number (2 * 1/10 = 0.2) and subtract it from the number above.

Add 32o to adjust for the offset in the Fahrenheit scale.

Example: convert 37o C to Fahrenheit.

37 * 2 = 74

74 * 1/10 = 7.4

74 - 7.4 = 66.6

66.6 + 32 = 98.6o F

Return to Top

Convert the Celsius Temperature to Fahrenheit

Round to the nearest degree.

<Form Name="math1">
<input type="button" value="Start" onClick="strt()" class="bgbutton">
</form>

<form name="form1">

<input type="text" value="" name="resulta" size=5 class="largebold">oC
<big> = </big>
<input type="text" value="" name="Answer" size=5 class="largebold">oF
  <input type="button" value="check" onclick="chck();" class="bgbutton">

<input type="text" value="Press the Start Button" name="result1" size=65 class="largebold">


text:
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>{% if page.title %}{{ page.title | escape }}{% else %}{{ site.title | escape }}{% endif %}</title>
  <meta property="og:type" content="website" />
  <meta property="og:description" content="{% if page.excerpt %}{{ page.excerpt | strip_html | strip_newlines | truncate: 160 }}{% else %}{{ site.description }}{% endif %}">
  <meta property="og:image" content="{{ site.baseurl }}/images/icon256.png" />
  <meta property="og:image:type" content="image/png" />
  <meta property="og:image:width" content="256" />
  <meta property="og:image:height" content="256" />

  <link rel="stylesheet" href="{{ "/css/main.css" | prepend: site.baseurl }}">
  <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
  <link rel="alternate" type="application/rss+xml" title="{{ site.title }}" href="{{ "/feed.xml" | prepend: site.baseurl | prepend: site.url }}">
  <link rel="shortcut icon" type="image/png" href="{{ site.baseurl }}/images/icon48.png">
</head>


text:
"""
Tests for the ZCA_Dataset class.
"""

import numpy as np

from theano.tests.unittest_tools import assert_allclose

from pylearn2.datasets.preprocessing import ZCA
from pylearn2.datasets.zca_dataset import ZCA_Dataset
from pylearn2.testing.datasets import random_dense_design_matrix

def test_zca_dataset():
    """
    Tests the ZCA_Dataset class.
    """
    # Preparation
    rng = np.random.RandomState([2014, 11, 4])
    start = 0
    stop = 990
    num_examples = 1000
    num_feat = 5
    num_classes = 2

    # random_dense_design_matrix has values that are centered and of
    # unit stdev, which is not useful to test the ZCA.
    # So, we replace its value by an uncentered uniform one.
    raw = random_dense_design_matrix(rng, num_examples, num_feat, num_classes)
    x = rng.uniform(low=-0.5, high=2.0, size=(num_examples, num_feat))
    x = x.astype(np.float32)
    raw.X = x

    zca = ZCA(filter_bias=0.0)
    zca.apply(raw, can_fit=True)
    zca_dataset = ZCA_Dataset(raw, zca, start, stop)

    # Testing general behaviour
    mean = zca_dataset.X.mean(axis=0)
    var = zca_dataset.X.std(axis=0)
    assert_allclose(mean, np.zeros(num_feat), atol=1e-2)
    assert_allclose(var, np.ones(num_feat), atol=1e-2)

    # Testing mapback()
    y = zca_dataset.mapback(zca_dataset.X)
    assert_allclose(x[start:stop], y)

    # Testing mapback_for_viewer()
    y = zca_dataset.mapback_for_viewer(zca_dataset.X)
    z = x/np.abs(x).max(axis=0)
    assert_allclose(z[start:stop], y, rtol=1e-2)

    # Testing adjust_for_viewer()
    y = zca_dataset.adjust_for_viewer(x.T).T
    z = x/np.abs(x).max(axis=0)
    assert_allclose(z, y)

    # Testing adjust_to_be_viewed_with()
    y = zca_dataset.adjust_to_be_viewed_with(x, 2*x, True)
    z = zca_dataset.adjust_for_viewer(x)
    assert_allclose(z/2, y)
    y = zca_dataset.adjust_to_be_viewed_with(x, 2*x, False)
    z = x/np.abs(x).max()
    assert_allclose(z/2, y)

    # Testing has_targets()
    assert zca_dataset.has_targets()


text:
package hk.samwong.roomservice.servlet.dao;

import hk.samwong.roomservice.commons.dataFormat.Response;
import hk.samwong.roomservice.commons.parameterEnums.ReturnCode;
import hk.samwong.roomservice.forgdrive.commons.dataFormat.GDriveFolder;
import hk.samwong.roomservice.forgdrive.commons.dataFormat.ResponseWithGDriveFolders;
import hk.samwong.roomservice.forgdrive.commons.enums.GDriveOperation;
import hk.samwong.roomservice.forgdrive.commons.enums.GDriveParameterKey;
import hk.samwong.roomservice.servlet.helper.MapUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * Servlet implementation class Collabofolder
 */
@WebServlet("/Collabofolder")
public class Collabofolder extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger log = Logger.getLogger(Collabofolder.class);
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Collabofolder() {
		super();
		String dbUrl = "jdbc:sqlite:" + System.getProperty("catalina.base")
				+ "/collabofolder.sqlite";
		log.info(dbUrl);
		try {
			namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(
					new SingleConnectionDataSource(
							org.sqlite.JDBC.createConnection(dbUrl,
									new Properties()), true));
			namedParameterJdbcTemplate
					.getJdbcOperations()
					.execute(
							"CREATE TABLE IF NOT EXISTS rooms (folder TEXT, room TEXT, link TEXT, owner TEXT);");

		} catch (SQLException e) {
			log.fatal("Failed to create connection to " + dbUrl, e);
			throw new MissingResourceException("JDBC createConnection failed.",
					"sqlite", dbUrl);
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Map<String, String[]> parameters = request.getParameterMap();
		log.info("Received GET request with params:"
				+ MapUtils.printParameterMap(parameters));

		PrintWriter out = response.getWriter();
		try {
			String[] ops = parameters.get(GDriveParameterKey.OPERATION
			.toString());

			String operation;
			if (ops.length > 0) {
				operation = ops[0];
			} else {
				ResponseWithGDriveFolders badOps = (ResponseWithGDriveFolders) new ResponseWithGDriveFolders()
						.setReturnCode(ReturnCode.ILLEGAL_ARGUMENT)
						.setExplanation("please specify OPERATION");
				out.print(new Gson().toJson(badOps));
				return;
			}

			if (operation.equals(GDriveOperation.GetSurroundingFolders
					.toString())) {

				String[] roomLists = parameters.get(GDriveParameterKey.ROOMS
						.toString());
				String roomListJson;
				if (roomLists.length > 0) {
					roomListJson = roomLists[0];
				} else {
					ResponseWithGDriveFolders badOps = (ResponseWithGDriveFolders) new ResponseWithGDriveFolders()
							.setReturnCode(ReturnCode.ILLEGAL_ARGUMENT)
							.setExplanation("please specify ROOMS");
					out.print(new Gson().toJson(badOps));
					return;
				}

				List<String> roomList = new Gson().fromJson(roomListJson,
						new TypeToken<List<String>>() {
						}.getType());

				RowMapper<GDriveFolder> rowMapper = new RowMapper<GDriveFolder>() {
					public GDriveFolder mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						return new GDriveFolder()
								.withName(rs.getString("folder"))
								.withRoom(rs.getString("room"))
								.withUrl(rs.getString("link"))
								.withOwner(rs.getString("owner"));
					}
				};

				List<GDriveFolder> gDriveFolders = this.namedParameterJdbcTemplate
						.getJdbcOperations()
						.query("SELECT folder , room , link , owner FROM rooms;",
								rowMapper);
				// Filter out the irrelevant room. TODO do this in db
				List<GDriveFolder> gDriveFoldersFiltered = new LinkedList<GDriveFolder>();
				for (GDriveFolder drive : gDriveFolders) {
					if (roomList.contains(drive.getRoom())) {
						gDriveFoldersFiltered.add(drive);
					}
				}

				ResponseWithGDriveFolders responseWithGDriveFolders = new ResponseWithGDriveFolders()
						.withGDriveFolders(gDriveFoldersFiltered);
				out.print(new Gson().toJson(responseWithGDriveFolders));
			}
		} catch (Throwable e) {
			Response errorResponse = new Response().setReturnCode(
					ReturnCode.ILLEGAL_ARGUMENT).setExplanation(e.toString());
			out.print(new Gson().toJson(errorResponse));
			return;
		} finally {
			out.close();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String[]> parameters = request.getParameterMap();
		log.info("Received PUT request with params:" + MapUtils.printParameterMap(parameters));

		PrintWriter out = response.getWriter();
		try {
			String[] ops = parameters.get(GDriveParameterKey.OPERATION.toString());
			String operation;
			if(ops.length > 0){
				operation = ops[0];
			}else{
				ResponseWithGDriveFolders badOps = (ResponseWithGDriveFolders) new ResponseWithGDriveFolders().setReturnCode(ReturnCode.ILLEGAL_ARGUMENT).setExplanation("please specify OPERATION");
				out.print(new Gson().toJson(badOps));
				return;
			}

			if (operation.equals(GDriveOperation.PutFolder.toString())) {
				String insertSql = "INSERT INTO rooms (folder, room, link, owner) VALUES (:folder, :room, :link, :owner);";
				SqlParameterSource namedParameters = new MapSqlParameterSource()
								.addValue("folder",
								parameters.get(GDriveParameterKey.FOLDER_NAME.toString())[0])
								.addValue("room",
								parameters.get(GDriveParameterKey.ROOM_NAME.toString())[0])
								.addValue("link",
								parameters.get(GDriveParameterKey.ALTERNATE_LINK.toString())[0])
								.addValue("owner",
								parameters.get(GDriveParameterKey.ACCOUNT_NAME.toString())[0]);
				this.namedParameterJdbcTemplate.update(insertSql, namedParameters);
				out.print(new Gson().toJson(new Response().setReturnCode(ReturnCode.OK)));
			}
		} catch (IllegalArgumentException e) {
			Response errorResponse = new Response().setReturnCode(
					ReturnCode.ILLEGAL_ARGUMENT).setExplanation(e.toString());
			out.print(new Gson().toJson(errorResponse));
			return;
		} catch (ArrayIndexOutOfBoundsException e){
			Response errorResponse = new Response().setReturnCode(
					ReturnCode.ILLEGAL_ARGUMENT).setExplanation(e.toString());
			out.print(new Gson().toJson(errorResponse));
			return;
		} finally {
			out.close();
			log.info("put done, connection closed, results returned");
		}

	}
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Immutable;
using System.Diagnostics;

namespace Microsoft.CodeAnalysis
{
    internal sealed class MergedAliases
    {
        public ArrayBuilder<string> AliasesOpt;
        public ArrayBuilder<string> RecursiveAliasesOpt;

        /// <summary>
        /// Adds aliases of a specified reference to the merged set of aliases.
        /// Consider the following special cases:
        ///
        /// o {} + {} = {}
        ///   If neither reference has any aliases then the result has no aliases.
        ///
        /// o {A} + {} = {A, global}
        ///   {} + {A} = {A, global}
        ///
        ///   If one and only one of the references has aliases we add the global alias since the
        ///   referenced declarations should now be accessible both via existing aliases
        ///   as well as unqualified.
        ///
        /// o {A, A} + {A, B, B} = {A, A, B, B}
        ///   We preserve dups in each alias array, but avoid making more dups when merging.
        /// </summary>
        internal void Merge(MetadataReference reference)
        {
            if (reference.Properties.HasRecursiveAliases)
            {
                if (RecursiveAliasesOpt == null)
                {
                    RecursiveAliasesOpt = ArrayBuilder<string>.GetInstance();
                    RecursiveAliasesOpt.AddRange(reference.Properties.Aliases);
                    return;
                }
            }
            else
            {
                if (AliasesOpt == null)
                {
                    AliasesOpt = ArrayBuilder<string>.GetInstance();
                    AliasesOpt.AddRange(reference.Properties.Aliases);
                    return;
                }
            }

            Merge(
                aliases: reference.Properties.HasRecursiveAliases ? RecursiveAliasesOpt : AliasesOpt,
                newAliases: reference.Properties.Aliases);
        }

        internal static void Merge(ArrayBuilder<string> aliases, ImmutableArray<string> newAliases)
        {
            if (aliases.Count == 0 ^ newAliases.IsEmpty)
            {
                AddNonIncluded(aliases, MetadataReferenceProperties.GlobalAlias);
            }

            AddNonIncluded(aliases, newAliases);
        }

        internal static ImmutableArray<string> Merge(ImmutableArray<string> aliasesOpt, ImmutableArray<string> newAliases)
        {
            if (aliasesOpt.IsDefault)
            {
                return newAliases;
            }

            var result = ArrayBuilder<string>.GetInstance(aliasesOpt.Length);
            result.AddRange(aliasesOpt);
            Merge(result, newAliases);
            return result.ToImmutableAndFree();
        }

        private static void AddNonIncluded(ArrayBuilder<string> builder, string item)
        {
            if (!builder.Contains(item))
            {
                builder.Add(item);
            }
        }

        private static void AddNonIncluded(ArrayBuilder<string> builder, ImmutableArray<string> items)
        {
            int originalCount = builder.Count;

            foreach (var item in items)
            {
                if (builder.IndexOf(item, 0, originalCount) < 0)
                {
                    builder.Add(item);
                }
            }
        }
    }
}


text:
package com.opendesk.openhttp;

import java.util.Map;

/**
 * Created by Mubarak Mohideen on 6/20/2016.
 */
 interface APIBuilder<T,C> {
    public T setEndPoint(String url);
    public T setEnableSession(boolean isSessionEnabled);
    public T setRequestProperty(Map<String,String> requestProperties);
    public C build();
}


text:
<template name="login">

{{#if isDevelopment}}

 ATTENTION!  This is a testing version of the site.

Please go to http://kaizenchallenge.dynalias.net and update your bookmarks.

{{/if}}

	  ×
	  Login failed!

	{{#if invalidToken}}

	  ×
	  Reset token is invalid or expired.

	{{/if}}

Log in

    <form id="form-login" role="form">

            <input type="text" class="form-control" id="inputUsername"
                placeholder="Username" required>

            <input type="password" class="form-control" id="inputPassword"
                placeholder="Password" required>

             <button type="submit" class="btn btn-success">Log in</button>

    </form>

Or pick one:

Log in with Twitter

Log in with Facebook

Log in with Google

Log in with GitHub

Have no account? Sign up
Forgot your password?

{{> footer footerclass="navbar-fixed-bottom"}}
</template>


text:
Useful information that doesn't nicely fit anywhere else.

## Is anything wrong, unclear, missing?
[Leave a comment.](https://github.com/feathersjs/feathers-guide/issues/new?title=Comment:Step-Appendix-Readme&body=Comment:Step-Appendix-Readme)


text:
package org.apache.tez.dag.history;

import org.apache.tez.dag.records.TezTaskAttemptID;
import org.apache.tez.dag.recovery.records.RecoveryProtos;
import org.apache.tez.runtime.api.impl.EventMetaData;

public class RecoveryConverters {

}


text: from grafcli.resources.resources import Resources


text:
CC=gcc
CFLAGS?=-O -g -fstack-protector-all -DENABLE_SERVER -DENABLE_SSL_TLS -I/usr/local/include -I/usr/local/include/openssl
#SUNLIBS=`[ \`uname\` = "SunOS" ] && echo -lsocket -lnsl`
LIBS=${SUNLIBS} -Wl,-rpath=/usr/local/lib:/usr/lib -lcrypt -lpthread -lresolv -ltls -ldl

all: dawnhttpd

dawnhttpd: dawnhttpd.c cdecode.c
	$(CC) $(CFLAGS) $(LIBS) dawnhttpd.c cdecode.c -o $@

clean:
	rm -f dawnhttpd core dawnhttpd.core

install:
	-cp dawnhttpd /usr/sbin

.PHONY: all clean


text:
<element name="g-toolbar" attributes="responsive">
  <template>

      <content></content>

  </template>

</element>


text:
Register here!

{{ registerError }}

<form ng-submit="register()">
  <input type="text" class="form-control" ng-model="registerUsername" placeholder="Username">
  <input type="password" class="form-control" ng-model="registerPassword" placeholder="Password">
  <input type="submit" class="btn btn-default" value="Submit">
</form>

Login here!

{{ loginError }}

<form ng-submit="login()">
  <input type="text" class="form-control" ng-model="loginUsername" placeholder="Username">
  <input type="password" class="form-control" ng-model="loginPassword" placeholder="Password">
  <input type="submit" class="btn btn-default" value="Submit">
</form>


text:
namespace CLDEParser {
    namespace Common {

        struct IPrintable;

        struct IPrintFormatter {
            virtual std::string Print(const IPrintable &printable) const = 0;
        };
    }
}

#endif //CLDEPARSER_COMMON_IPRINTFORMATTER_H


text:
<?php

namespace Inanimatt\SiteBuilder\Transformer;

use Inanimatt\SiteBuilder\Event\FileCopyEvent;
use Inanimatt\SiteBuilder\Transformer\TransformerInterface;
use dflydev\markdown\MarkdownParser;
use \Twig_Environment;

class TwigMarkdownTransformer implements TransformerInterface
{
    protected $markdown;
    protected $twig;
    protected $template;

    public function __construct(MarkdownParser $markdown, Twig_Environment $twig, $template)
    {
        $this->markdown = $markdown;
        $this->twig = $twig;
        $this->template = $template;
    }

    /**
     * {@inheritdoc}
     */
    public function transform(FileCopyEvent $event)
    {
        if (!in_array($event->getExtension(), array('md', 'markdown'))) {
            return;
        }

        $fileContent = $event->getContent();

        // Override template?
        $template = $event->data->get('template')->getOrElse($this->template);

        /* Parse remaining file as markdown */
        $data = iterator_to_array($event->data);
        $data['content'] = $this->markdown->transformMarkdown($fileContent);

        // Render and save
        $output = $this->twig->render($template, $data);

        $targetFile = $event->getTarget();
        $targetFile = substr($targetFile, 0, 0 - strlen(pathinfo($targetFile, PATHINFO_EXTENSION))) . 'html';

        $event->setTarget($targetFile);
        $event->setContent($output);
    }
}


text:
<?php

namespace alkemann\h2l\tests\unit;

use alkemann\h2l\{Connections, exceptions\ConfigMissing};
use InvalidArgumentException;
use Exception;

class ConnectionsTest extends \PHPUnit\Framework\TestCase
{

    private static $ref_class;
    private static $ref_connections;
    private static $ref_open;
    private static $ref_close;

    public static function setUpBeforeClass(): void
    {
        static::$ref_class = new \ReflectionClass('alkemann\h2l\Connections');
        static::$ref_connections = static::$ref_class->getProperty('connections');
        static::$ref_connections->setAccessible(true);
        static::$ref_open = static::$ref_class->getProperty('open');
        static::$ref_open->setAccessible(true);
        static::$ref_close = static::$ref_class->getProperty('close');
        static::$ref_close->setAccessible(true);
    }

    public function setUp(): void
    {
        static::$ref_connections->setValue([]);
        static::$ref_open->setValue([]);
        static::$ref_close->setValue([]);
    }

    public function testAdd(): void
    {
        Connections::add('test1', function() {});

        $this->assertEquals(false, static::$ref_connections->getValue()['test1']);
    }

    public function testExceptionOnDuplicate(): void
    {
        $this->expectException(InvalidArgumentException::class);
        Connections::add('test1', function() {});
        Connections::add('test1', function() {});
    }

    public function testGetOnMissing(): void
    {
        $this->expectException(ConfigMissing::class);
        $this->expectExceptionCode(ConfigMissing::MISSING_CONNECTION);
        $result = Connections::get('i did not make this');
    }

    public function testGetWithConnect(): void
    {
        $status = false; // not connected at start
        $open = function() use (&$status) {
            if ($status) {
                throw new \Exception("Already connected");
            }
            $status = true;
            return "FAKE DB CONNECTION";
        };
        $close = function($db) use (&$status) {
            if (!$status) {
                throw new \Exception("Already closed");
            }
            $status = false;
        };
        Connections::add('tested', $open, $close);

        $this->assertEquals(false, static::$ref_connections->getValue()['tested']);
        $this->assertSame($open, static::$ref_open->getValue()['tested']);
        $this->assertSame($close, static::$ref_close->getValue()['tested']);

        $expected = "FAKE DB CONNECTION";
        $result = Connections::get('tested');
        $this->assertTrue($status);
        $this->assertEquals($expected, $result);
        $this->assertEquals($expected, static::$ref_connections->getValue()['tested']);

        // This should NOT throw MissingConfig
        $result = Connections::get('tested');
        $this->assertEquals($expected, $result);

        Connections::close('tested');
        $this->assertFalse($status);
        $this->assertEquals(false, static::$ref_connections->getValue()['tested']);
    }

    public function testExceptionOnCloseForNotExist(): void
    {
        $this->expectException(InvalidArgumentException::class);
        Connections::close('tested');
    }

    public function testExceptionOnCloseForAlreadyClosed(): void
    {
        $this->expectException(Exception::class);
        static::$ref_connections->setValue(['tested' => false]);
        static::$ref_open->setValue(['tested' => function() {}]);
        static::$ref_close->setValue(['tested' => function() {}]);
        Connections::close('tested');
    }

    public function testOkToCallCloseWithoutCloseConfigured(): void
    {
        static::$ref_connections->setValue(['tested' => true]);
        static::$ref_open->setValue(['tested' => function() {}]);
        Connections::close('tested');
        $this->assertTrue(true);
    }
}


text:
class Item < ActiveRecord::Base
  validates :name, :price, { :presence => true }

  has_many :bids
  has_many :contestants, through: :bids
end


text:
title: Network Engineering
localeTitle: Сетевая инженерия
---
## Сетевая инженерия

**Пакет** представляет собой абстракцию передаваемых данных на _сетевом уровне_ модели OSI. Он состоит из фактических данных и других полей, необходимых для его посредничества от одного узла к другому узлу в сети. Поскольку передача всех данных по сети за один раз неэффективна, она разбивается на небольшие пакеты и затем передается.

Пакет выглядит следующим образом:

![пакет](https://www.computerhope.com/jargon/p/packet.jpg)

Сетевой слой разбивает данные на небольшие пакеты, каждый с уникальным идентификатором. Затем они передаются на транспортный уровень, который переносит их в пункт назначения через несколько промежуточных узлов, таких как маршрутизаторы и коммутаторы, с использованием _протокола управления передачей_ (TCP) и _протокола Интернета_ (IP). TCP имеет дело с фактической маршрутизацией, в то время как IP помогает в логической адресации устройств (IP-адрес), чтобы отслеживать, какой узел отправляет пакет рядом.

Как только пакеты достигают пункта назначения, подтверждение отправляется обратно. Если по какой-либо причине пакет удаляется, его можно повторно запросить с исходного узла.

Сетевые инженеры отвечают за внедрение, поддержку, поддержку, разработку и, в некоторых случаях, разработку сетей связи в организации или между организациями.

Их цель - обеспечить целостность сетевой инфраструктуры высокой доступности, чтобы обеспечить максимальную производительность для своих пользователей. Пользователи могут быть сотрудниками, клиентами, клиентами и поставщиками. Сети могут включать:

компьютер; голос; брандмауэр. Сетевые инженеры могут работать внутри организации в составе группы поддержки ИТ-подразделения организации или извне в составе аутсорсинговой консалтинговой фирмы по ИТ-сетям, работающей с несколькими клиентами.


text:
<?php

namespace Drupal\field_example\Tests;

use \Drupal\field_example\FieldExampleWebTestBase;

/**
 * Test the basic functionality of Color background  formatter.
 *
 * Create a content type with a field_example_rgb field, configure it with the
 * color_background_formatter, create a node and check for correct values.
 *
 * @group field_example
 * @group examples
 *
 * @ingroup field_example
 */
class ColorBackgroundFormatterTest extends FieldExampleWebTestBase {

  /**
   * Test scenarios in Field example.
   *
   * - Creates a content type.
   * - Adds a multivalued field_example_rgb to it.
   * - Creates a node of the new type.
   * - Populates the multivalued field with two items.
   * - Tests the result.
   */
  public function testSingleValueField() {
    // Login with Admin and create a field.
    $this->drupalLogin($this->administratorAccount);
    $this->fieldName = $this->createField('field_example_rgb', 'field_example_colorpicker', '1', 'field_example_color_background');

    // Login with Author user for content creation.
    $this->drupalLogin($this->authorAccount);
    $this->drupalGet('node/add/' . $this->contentTypeName);

    // Details to be submitted for content creation.
    $title = $this->randomMachineName(20);
    $edit = array(
      'title[0][value]' => $title,
      'field_' . $this->fieldName . '[0][value]' => '#00ff00',
    );

    // Submit the content creation form.
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText(t('@type @title has been created', array('@type' => $this->contentTypeName, '@title' => $title)));

    // Verify color.
    $this->assertText(t('The content area color has been changed to #00ff00'), 'Verify the color');
  }

  /**
   * Test scenarios in Field example.
   *
   * - Creates a content type.
   * - Adds a multivalued field_example_rgb to it.
   * - Creates a node of the new type.
   * - Populates the multivalued field with two items.
   * - Tests the result.
   */
  public function testMultiValueField() {

    // Login with Admin and create a field.
    $this->drupalLogin($this->administratorAccount);
    $this->fieldName = $this->createField('field_example_rgb', 'field_example_colorpicker', '-1', 'field_example_color_background');

    // Login with Author user for content creation.
    $this->drupalLogin($this->authorAccount);
    $this->drupalGet('node/add/' . $this->contentTypeName);

    // Details to be submitted for content creation.
    $title = $this->randomMachineName(20);
    $edit = array(
      'title[0][value]' => $title,
      'field_' . $this->fieldName . '[0][value]' => '#00ff00',
    );

    // Add another field value.
    $this->drupalPostForm(NULL, $edit, t('Add another item'));

    // Set value for newly added item.
    $edit = array(
      'field_' . $this->fieldName . '[1][value]' => '#ffff4f',
    );

    // Submit the content creation form.
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText(t('@type @title has been created', array('@type' => $this->contentTypeName, '@title' => $title)));

    // Verify color.
    $this->assertText(t('The content area color has been changed to #00ff00'), 'Verify the color of field 1');
    $this->assertText(t('The content area color has been changed to #ffff4f'), 'Verify the color of field 2');
  }

}


text:
package io.femo.http;

import io.femo.support.jdk7.Supplier;

/**
 * Created by Felix Resch on 29-Apr-16.
 */
public abstract class HttpRoutable<T extends HttpRoutable> {

    public abstract T use(HttpMiddleware handler);

    public abstract T use(String path, HttpMiddleware handler);

    public abstract T use(HttpHandler handler);

    public abstract T use(String path, HttpHandler httpHandler);

    public abstract T use(String method, String path, HttpHandler httpHandler);

    public abstract T after(HttpMiddleware middleware);

    public T get(String path, HttpHandler httpHandler) {
        return use(Http.GET, path, httpHandler);
    }

    public T get(String path, Supplier<HttpHandler> httpHandler) {
        return use(Http.GET, path, httpHandler.get());
    }

    public T post(String path, HttpHandler httpHandler) {
        return use(Http.POST, path, httpHandler);
    }
    public T post(String path, Supplier<HttpHandler> httpHandler) {
        return use(Http.POST, path, httpHandler.get());
    }

    public T put(String path, HttpHandler httpHandler) {
        return use(Http.PUT, path, httpHandler);
    }
    public T put(String path, Supplier<HttpHandler> httpHandler) {
        return use(Http.PUT, path, httpHandler.get());
    }

    public T delete(String path, HttpHandler httpHandler) {
        return use(Http.DELETE, path, httpHandler);
    }
    public T delete(String path, Supplier<HttpHandler> httpHandler) {
        return use(Http.DELETE, path, httpHandler.get());
    }

    public T update(String path, HttpHandler httpHandler) {
        return use(Http.UPDATE, path, httpHandler);
    }
    public T update(String path, Supplier<HttpHandler> httpHandler) {
        return use(Http.UPDATE, path, httpHandler.get());
    }

    public T patch(String path, HttpHandler httpHandler) {
        return use(Http.PATCH, path, httpHandler);
    }
    public T patch(String path, Supplier<HttpHandler> httpHandler) {
        return use(Http.PATCH, path, httpHandler.get());
    }

    public abstract boolean matches(HttpRequest httpRequest);

    public abstract HttpRoutable<T> prependPath(String path);

}


text:
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->

## booleanDisjoint

Boolean-disjoint returns (TRUE) if the intersection of the two geometries is an empty set.

**Parameters**

-   `feature1` **([Geometry][1] \| [Feature][2]<any>)** GeoJSON Feature or Geometry
-   `feature2` **([Geometry][1] \| [Feature][2]<any>)** GeoJSON Feature or Geometry

**Examples**

```javascript
var point = turf.point([2, 2]);
var line = turf.lineString([[1, 1], [1, 2], [1, 3], [1, 4]]);

turf.booleanDisjoint(line, point);
//=true
```

Returns **[boolean][3]** true/false

[1]: https://tools.ietf.org/html/rfc7946#section-3.1

[2]: https://tools.ietf.org/html/rfc7946#section-3.2

[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean

<!-- This file is automatically generated. Please don't edit it directly:
if you find an error, edit the source file (likely index.js), and re-run
./scripts/generate-readmes in the turf project. -->

---

This module is part of the [Turfjs project](http://turfjs.org/), an open source
module collection dedicated to geographic algorithms. It is maintained in the
[Turfjs/turf](https://github.com/Turfjs/turf) repository, where you can create
PRs and issues.

### Installation

Install this module individually:

```sh
$ npm install @turf/boolean-disjoint
```

Or install the Turf module that includes it as a function:

```sh
$ npm install @turf/turf
```

### Diagrams

![esri-disjoint](diagrams/esri-disjoint.gif)


text:
/**
* Theme: Velonic Admin Template
* Author: Coderthemes
* Form wizard page
*/

!function($) {
    "use strict";

    var FormWizard = function() {};

    FormWizard.prototype.createBasic = function($form_container) {
        $form_container.children("div").steps({
            headerTag: "h3",
            bodyTag: "section",
            transitionEffect: "slideLeft"
        });
        return $form_container;
    },
    //creates form with validation
    FormWizard.prototype.createValidatorForm = function($form_container) {
        $form_container.validate({
            errorPlacement: function errorPlacement(error, element) {
                element.after(error);
            }
        });
        $form_container.children("div").steps({
            headerTag: "h3",
            bodyTag: "section",
            transitionEffect: "slideLeft",
            onStepChanging: function (event, currentIndex, newIndex) {
                $form_container.validate().settings.ignore = ":disabled,:hidden";
                return $form_container.valid();
            },
            onFinishing: function (event, currentIndex) {
                $('#failed-div').text('');
                $('#success-div').text('');
                var bodyText=$('#postbody').text();
                var urlText=$('#posturl').text();
                var postData=JSON.parse(bodyText);
                postData.name=$('#policyname').val();
                $.each(postData['policy-virtual-servers'], function (index, item) {
                    item.priority=parseInt($('#priority').val());
                });

                $form_container.validate().settings.ignore = ":disabled";
                if($form_container.valid()){
                    $.ajax({
                        xhrFields: {
                            withCredentials: true
                        },
                        url: urlText.trim(),
                        data: JSON.stringify(postData),
                        type: "POST",
                        dataType: "json",
                        timeout: 99000,
                        beforeSend: function () {
                        },
                        error: function (xhr, status, error) {
                            $('#confirmAddTrafficPolicyResult').modal('show').find('#failed-div').text('创建traffic policy 失败, 失败原因'+xhr.responseText);
                            return false;
                        },
                        success: function (result) {
                            $('#confirmAddTrafficPolicyResult').modal('show').find('#success-div').text('创建traffic policy 成功, 2s 后跳转到Traffic Policy 页面');

                            var env = $('#env').text();
                            setTimeout(function () {
                                window.location.href='/portal/policy#?env='+env;
                            },2000);

                            return true;
                        },
                        complete: function () {
                        }
                    });
                }else{
                    return false;
                }
            },
            onFinished: function (event, currentIndex) {
                alert("Submitted!");
            }
        });

        return $form_container;
    },
    //creates vertical form
    FormWizard.prototype.createVertical = function($form_container) {
        $form_container.steps({
            headerTag: "h3",
            bodyTag: "section",
            transitionEffect: "fade",
            stepsOrientation: "vertical"
        });
        return $form_container;
    },
    FormWizard.prototype.init = function() {
        //initialzing various forms

        //basic form
        this.createBasic($("#basic-form"));

        //form with validation
        this.createValidatorForm($("#wizard-validation-form"));

        //vertical form
        this.createVertical($("#wizard-vertical"));
    },
    //init
    $.FormWizard = new FormWizard, $.FormWizard.Constructor = FormWizard
}(window.jQuery),

//initializing
function($) {
    "use strict";
    $.FormWizard.init()
}(window.jQuery);


text:
namespace Microsoft.AspNetCore.Components.Analyzers;

// Constants for type and method names used in code-generation
// Keep these in sync with the actual definitions
internal static class ComponentsApi
{
    public const string AssemblyName = "Microsoft.AspNetCore.Components";

    public static class ParameterAttribute
    {
        public const string FullTypeName = "Microsoft.AspNetCore.Components.ParameterAttribute";
        public const string MetadataName = FullTypeName;

        public const string CaptureUnmatchedValues = "CaptureUnmatchedValues";
    }

    public static class CascadingParameterAttribute
    {
        public const string FullTypeName = "Microsoft.AspNetCore.Components.CascadingParameterAttribute";
        public const string MetadataName = FullTypeName;
    }

    public static class IComponent
    {
        public const string FullTypeName = "Microsoft.AspNetCore.Components.IComponent";
        public const string MetadataName = FullTypeName;
    }
}