text:
package org.auraframework.impl.javascript.parser.handler.mock;

import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Map;

import org.auraframework.def.BaseComponentDef;
import org.auraframework.def.ComponentConfigProvider;
import org.auraframework.def.ComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.ProviderDef;
import org.auraframework.def.TestSuiteDef;
import org.auraframework.impl.javascript.provider.JavascriptProviderDef.Builder;
import org.auraframework.instance.ComponentConfig;
import org.auraframework.system.Source;
import org.auraframework.test.Resettable;
import org.auraframework.test.mock.Answer;
import org.auraframework.test.mock.DelegatingStubHandler;
import org.auraframework.test.mock.Invocation;
import org.auraframework.test.mock.Stub;
import org.auraframework.throwable.quickfix.InvalidDefinitionException;
import org.auraframework.throwable.quickfix.QuickFixException;

/**
 * Parse JSTEST mock Providers.
 */
public class JavascriptMockProviderHandler extends JavascriptMockHandler<ProviderDef> {
    public JavascriptMockProviderHandler(DefDescriptor<TestSuiteDef> descriptor, Source<?> source,
            DefDescriptor<? extends BaseComponentDef> targetDescriptor, Map<String, Object> map) {
        super(descriptor, source, targetDescriptor, map);
    }

    @Override
    protected ProviderDef createDefinition(Map<String, Object> map) throws QuickFixException {
        ProviderDef baseDef = getBaseDefinition((String) map.get("descriptor"), ProviderDef.class);
        List<Stub<?>> stubs = getStubs(map.get("stubs"));
        return (ProviderDef) Proxy.newProxyInstance(this.getClass()
                .getClassLoader(), new Class<?>[] { ProviderDef.class, Resettable.class },
                new DelegatingStubHandler(baseDef, stubs));
    }

    @SuppressWarnings("unchecked")
    @Override
    protected <T> T getValue(Object object, Class<T> retClass) throws QuickFixException {
        if (object != null && ComponentConfig.class.equals(retClass)) {
            if (!(object instanceof Map)) {
                throw new InvalidDefinitionException("Mock Provider expects (descriptor and/or attributes) or (configProvider)", getLocation());
            }
            ComponentConfig config;

            String configProvider = (String)((Map<?, ?>) object).get("configProvider");
            //If a config provider is specified, defer provide until later
            if(configProvider!=null && !configProvider.isEmpty()){
                config = null;
            }else{//Else determine the mock component to provide
                config = new ComponentConfig();
                DefDescriptor<ComponentDef> cdd = getDescriptor((String) ((Map<?, ?>) object).get("descriptor"),
                        ComponentDef.class);
                if (cdd != null) {
                    config.setDescriptor(cdd);
                }
                Map<String, Object> attributes = (Map<String, Object>) ((Map<?, ?>) object).get("attributes");
                if (attributes != null) {
                    config.setAttributes(attributes);
                }
            }
            return (T) config;
        } else {
            return super.getValue(object, retClass);
        }
    }

    @Override
    protected <T> Answer<T> getAnswer(Object object, Class<T> retClass) throws QuickFixException {
        if (object instanceof Map) {
            Map<?, ?> map = (Map<?, ?>) object;
            final String configProvider = (String)((Map<?, ?>)map.get("value")).get("configProvider");
            if(configProvider!=null){
                return new Returns<T>(null){
                    @SuppressWarnings("unchecked")
                    @Override
                    public T answer() throws Throwable {
                        String mockProvider = configProvider;
                        ComponentConfig config;
                        if(configProvider.startsWith("java://")){
                            mockProvider = configProvider.substring("java://".length());
                        }
                        try{
                            Class<?> providerClass = Class.forName(mockProvider);
                            if(!ComponentConfigProvider.class.isAssignableFrom(providerClass)){
                                throw new InvalidDefinitionException("Class specified as configProvider should implement ComponentConfigProvider", getLocation());
                            }
                            ComponentConfigProvider provider = (ComponentConfigProvider)providerClass.newInstance();
                            config = provider.provide();
                        }catch(ClassNotFoundException e){
                            throw new InvalidDefinitionException("Could not locate class specified as configProvider:"+configProvider, getLocation());
                        }catch(IllegalAccessException e){
                            throw new InvalidDefinitionException("Constructor is inaccessible for "+ configProvider, getLocation());
                        }catch (InstantiationException ie) {
                            throw new InvalidDefinitionException("Cannot instantiate " + configProvider, getLocation());
                        }
                      return (T)config;
                    }
                };
            }else{
                return super.getAnswer(object, retClass);
            }
        }
        throw new InvalidDefinitionException("Mock answer must specify either 'value' or 'error'", getLocation());
    }

    @Override
    protected ProviderDef getDefaultBaseDefinition() throws QuickFixException {
        return getTargetDescriptor().getDef().getLocalProviderDef();
    }

    @Override
    protected Invocation getDefaultInvocation() throws QuickFixException {
        return new Invocation("provide", null, ComponentConfig.class);
    }

    @Override
    protected ProviderDef createDefinition(Throwable error) {
        Builder builder = new Builder();
        builder.setParseError(error);
        return builder.build();
    }

}


text:
using UnityEngine;
using UnityEditor;
using System.Collections;

namespace UniOSC{

	[CustomEditor (typeof(UniOSCMappingItem))]
	public class UniOSCMappingItemEditor : Editor {

		public void OnEnable(){

		}

		public static void OnGUI_Editor(UniOSCMappingItem obj){

			EditorGUI.BeginChangeCheck();

			EditorGUILayout.BeginHorizontal ();

			#region Values
			obj.address = 		EditorGUILayout.TextField(new GUIContent("","Tooltip for Address"),obj.address,GUILayout.Width(UniOSCUtils.MAPPINGLISTLABELRECTS[0].width) );
			obj.min =  			EditorGUILayout.FloatField(new GUIContent("","Minimal value"),obj.min,GUILayout.Width(UniOSCUtils.MAPPINGLISTLABELRECTS[1].width));
			obj.max =  			EditorGUILayout.FloatField(new GUIContent("","Maximal value"),obj.max,GUILayout.Width(UniOSCUtils.MAPPINGLISTLABELRECTS[2].width));
			obj.mappingMIN =  	EditorGUILayout.FloatField(new GUIContent("","Minimal Mapping value"),obj.mappingMIN,GUILayout.Width(UniOSCUtils.MAPPINGLISTLABELRECTS[3].width));
			obj.mappingMAX =  	EditorGUILayout.FloatField(new GUIContent("","Maximal Mapping value"),obj.mappingMAX,GUILayout.Width(UniOSCUtils.MAPPINGLISTLABELRECTS[4].width));
			#endregion Values

			#region Learn
			Rect r = GUILayoutUtility.GetRect(UniOSCUtils.MAPPINGLISTLABELRECTS[5].width, UniOSCUtils.MAPPINGLISTLABELRECTS[5].height,GUI.skin.button, GUILayout.ExpandWidth(false));
			r.width *= 0.9f;
			if(obj.hostObj.IsLearning){
				GUIStyle gs = new GUIStyle(GUI.skin.button);
				gs.active.textColor =UniOSCUtils.LEARN_COLOR_ON  ;
				gs.normal.textColor = UniOSCUtils.LEARN_COLOR_OFF;

				if(GUI.RepeatButton(r,new GUIContent("Learn","Press to Learn OSC"),gs)){
					obj.isLearning = true;
				}else{
					obj.isLearning = false;
				}

			}
			#endregion Learn

			#region Delete
			if ( GUILayout.Button ("Delete",GUILayout.Width(UniOSCUtils.MAPPINGLISTLABELRECTS[6].width),GUILayout.Height(UniOSCUtils.MAPPINGLISTLABELRECTS[6].height) ) ){
				bool deleteItem = EditorUtility.DisplayDialog("Delete", "Do you want to delete this OSCMappingItem with the Address:\n"+obj.address+" ?", "OK", "Cancel");
				if(deleteItem)obj.OnOSCMappingItemDelete();
			}
			#endregion Delete

			EditorGUILayout.EndHorizontal ();

			if(EditorGUI.EndChangeCheck()){
				EditorUtility.SetDirty(obj.hostObj);
			}
		}

		public static void OnGUI_Inspector(UniOSCMappingItem obj){

			EditorGUI.BeginChangeCheck();

			EditorGUILayout.BeginVertical(GUI.skin.box,  GUILayout.Width(UniOSCMappingItem.MAXWIDTH),GUILayout.Height(obj.collapsed ? UniOSCMappingItem.MAXHEIGTH : 10f) );
			//EditorGUIUtility.LookLikeControls(UniOSCMappingItem.MAXWIDTH *0.35f,UniOSCMappingItem.MAXWIDTH *0.55f);
			EditorGUIUtility.labelWidth = UniOSCMappingItem.MAXWIDTH *0.35f;
			EditorGUIUtility.fieldWidth = UniOSCMappingItem.MAXWIDTH *0.55f;

			#region IN
			if(obj.hostObj.IsLearning)obj.collapsed = true;

			EditorGUILayout.BeginHorizontal ();

			obj.collapsed = EditorGUILayout.Foldout(obj.collapsed, "OSC Mapping Item "+ (obj.collapsed ? "" : obj.address) );
			EditorGUILayout.EndHorizontal ();
			#endregion IN

			if (obj.collapsed)
			{
				obj.address = EditorGUILayout.TextField(new GUIContent("OSC Address:","Tooltip for Address"),obj.address);

				#region DataMinMax
				GUILayout.Label(new GUIContent("Data Range:","The range where the incomming date is in. Most of the times this is in normalized range of 0-1."));

				EditorGUILayout.BeginHorizontal();
				//EditorGUIUtility.LookLikeControls(40f,50f);
				EditorGUIUtility.labelWidth =40f;
				EditorGUIUtility.fieldWidth = 50f;

				obj.min =  EditorGUILayout.FloatField(new GUIContent("Min:","Minimal value"),obj.min);
				GUILayout.FlexibleSpace();
				obj.max =  EditorGUILayout.FloatField(new GUIContent("Max:","Maximal value"),obj.max);
				EditorGUILayout.EndHorizontal();
				#endregion DataMinMax

				#region DataMapping
				GUILayout.Label(new GUIContent("Data Mapping:","The incomming data from the OSC Message is changed and mapped from the min-max data range to the min-max mapping range.If you don't want any mapping these values should match with the 'Data Range' above."));

				EditorGUILayout.BeginHorizontal();
				//EditorGUIUtility.LookLikeControls(40f,50f);
				EditorGUIUtility.labelWidth = 40f;
				EditorGUIUtility.fieldWidth = 50f;

				obj.mappingMIN =  EditorGUILayout.FloatField(new GUIContent("Min:","Minimal Mapping value"),obj.mappingMIN);
				GUILayout.FlexibleSpace();
				obj.mappingMAX =  EditorGUILayout.FloatField(new GUIContent("Max:","Maximal Mapping value"),obj.mappingMAX);
				EditorGUILayout.EndHorizontal();
				#endregion DataMapping

				GUILayout.Space(10f);

				#region Bottom
				EditorGUILayout.BeginHorizontal();

				EditorGUILayout.BeginVertical(GUILayout.Height(40f));

				#region Delete
				EditorGUILayout.BeginHorizontal();
				if ( GUILayout.Button ("Delete" ,GUILayout.Width(100)) ){
					bool deleteDispatcher = EditorUtility.DisplayDialog("Delete", "Do you want to delete this OSCMappingItem with the Address:\n"+obj.address+" ?", "OK", "Cancel");
					if(deleteDispatcher)obj.OnOSCMappingItemDelete();
				}
				GUILayout.FlexibleSpace();
				EditorGUILayout.EndHorizontal();
				#endregion Delete

				EditorGUILayout.EndVertical();

				#region Learn

				if(obj.hostObj.IsLearning){
					EditorGUILayout.BeginHorizontal ();
					GUILayout.FlexibleSpace();

					if(obj.hostObj.IsLearning){
						if(GUILayout.RepeatButton(new GUIContent("Learn","Press to Learn OSC"),GUILayout.Width(80f),GUILayout.Height(40f) )  ){
							obj.isLearning = true;
						}else{
							obj.isLearning = false;
						}

					}
					GUILayout.FlexibleSpace();
					EditorGUILayout.EndHorizontal();
				}

				#endregion Learn

				EditorGUILayout.EndHorizontal ();
				#endregion Bottom

			}//collapsed

			EditorGUILayout.EndVertical();

			if(EditorGUI.EndChangeCheck()){
				EditorUtility.SetDirty(obj.hostObj);
			}

		}

	}
}

redpajama_set_name: RedPajamaGithub


text:
The following document explains the format of a Freki file. In addition, it notes a requirement for the installation of the Freki package.

## pdfminer.six

`pdfminer.six` is required in order to successfully run Freki using the `pdfminer` option.

### Installation

The following installation is recommended, as using the Python Package Index (PyPI) installs a broken version.

```
pip install https://github.com/goulu/pdfminer/zipball/e6ad15af79a26c31f4e384d8427b375c93b03533#egg=pdfminer.six
```

### Usage

To use `pdfminer.six`, run the following line in the Terminal:

```
    pdf2txt.py -t xml input_pdf_file > output_xml_file
```

## Freki Format

The format of a Freki file is as follows:

A Freki file is divided into *blocks*. Blocks consist of a preamble (or
header) as well as a following list of *lines*.

### Blocks

Each block begins with a preamble. The format of the preamble is the following:

```
doc_id=val1 block_id=val2 (attr3:val3) ... [<start_line>] [<end_line>]
```

(Note that `doc_id` and `block_id` should appear at the beginning of each block.)

Within the preamble are the following attributes:

(Note that the type of each attribute is listed as well: required, pre-defined but optional, and user-defined.)

* `doc_id`: Refers to the original document that was used to create the block [required]
* `page`: Page number of the original pdf document [pre-defined]
  * Must be an integer
* `block_id`: Unique ID for the block [required]
  * Format is `page-block_id`
    - e.g., `block_id=2-1` refers to the 1st block on page 2
* `bbox`: Bounding box for the coordinates of the block [pre-defined]
  * Format is `llx,lly,urx,ury`
    - `llx`, `lly`, `urx`, and `ury` are point coordinates
      - `ll` stands for "lower left"
      - `ur` stands for "upper right"
      - The x-coordinates (`llx` and `urx`) are indexed from the left of the page
      - The y-coordinates (`lly` and `ury`) are indexed from the bottom of the page
* `label`: Specifies the cuts that were made [pre-defined]
  * Format is [rltb]+
    - e.g., `rtll`
      - vertical; take the right one
      - horizontal; take the top one
      - vertical; take the left one
      - vertical; take the left one

The last two values, `start_line` and `end_line`, are optional. Although the following lines contain the start and end line information, they are redundantly listed for grepability.

### Lines

The format of a line is the following:

```
line=val1 (attr2:val2) ...
```

(Note that `line` should appear at the beginning of each block.)

Each line has the following attributes:

(Note that the type of each attribute is listed as well: required, pre-defined but optional, and user-defined.)

* `line`: Line number [required]
  * Must be an integer value
* `tag`: Specifies the content of the line [pre-defined]
  * There are three main tags:
    - `O`: This line is not IGT
    - `B-`: This line is starting a new span of IGT
    - `I-`: This line is continuing a previous span of IGT
  * There are also four types of `B` & `I` tags:
    - `M`: Metadata
    - `L`: Language line
    - `G`: Gloss line
    - `T`: Translation line
  * There are attributes that we are not using for now, too, that are
    signified with `+`; these are things such as:
    - `DB`: Double column
    - `AC`: Author citation
    - `LN`: Language name
* `lang`: ISO-639-3 code of the language (if the line contains IGT data)
* `span_id`: Unique ID for the IGT span
  * Starts at 1 and increments by 1 for each span
* `fonts`: List of fonts
  * Format is `font_id1-size1[,font2-size2]*`
  * e.g., `F0-12.0,F1-9.8`
    - Line has two fonts
    - First font: ID F0, size 12.0pt
    - Second font: ID F1, size 9.8pt
* `bbox`: (see description of `bbox` for blocks) [pre-defined]
* `tabscore`: [pre-defined]
  * Real value between 0 and 1, inclusive

### Creating other attributes

Users can create other attributes, as needed.

For creating one's own attributes and values, there are a couple of requirements:
* Attribute names can be any string that does not contain whitespace, colons, or equal signs
* Values for other attributes can be any string that do not contain whitespace, colons, or equal signs

### Example

```
doc_id=3009.tetml page=11 block_id=11-6 bbox=42.5,660.3,500.4,672.3 365 365
line=365 tag=O fonts=F49-12.0:is a brick-town at speech time. As convincing as this may be, counterexamples are easy to find:

doc_id=3009.tetml page=11 block_id=11-7 bbox=42.5,615.7,506.2,641.6 366 367
line=366 tag=B-L lang=deu span_id=s13 fonts=F49-12.0:(xix) In der   Nachkriegszeit   ist Kleve   zu einer Klinkerstadt  geworden, aber  schon   in
line=367 tag=I-G lang=deu span_id=s13 fonts=F49-12.0:  	in the   after-war-time   is Kleve   to a	brick-town	become	but   already in

doc_id=3009.tetml page=11 block_id=11-8 bbox=70.8,574.2,453.4,600.1 368 369
line=368 tag=I-L lang=deu span_id=s13 fonts=F49-12.0:den  80ern   hat   man neue Impulse   gesetzt  in Richtung  Hochhaus
line=369 tag=I-G lang=deu span_id=s13 fonts=F49-12.0:the   80ies   has  one  new  impulses   set 	in direction   skyscrapers

doc_id=3009.tetml page=11 block_id=11-9 bbox=70.8,532.6,524.5,558.3 370 371
line=370 tag=I-T lang=deu span_id=s13 fonts=F49-12.0:'Kleve has become a brick-town after the War, but already in the 80ies, people tried new
line=371 tag=I-T lang=deu span_id=s13 fonts=F49-12.0:things with skyscrapers'

doc_id=3009.tetml page=11 block_id=11-10 bbox=56.6,501.9,503.7,513.9 372 372
line=372  tag=O fonts=F49-12.0:In the section about Comrie (1995) below, I will address other facets of the relevance-notion.
```


text:
import sys
import math

def readline():
	return sys.stdin.readline().strip()

def main():
	dictionary = dict()
	for line in sys.stdin:
		line = line.strip()
		if line == "":
			break
		line = line.split()
		dictionary[line[1]] = line[0]
	for line in sys.stdin:
		word = line.strip()
		if word not in dictionary:
			print("eh")
		else:
			print(dictionary[word])

if __name__=="__main__":
    main()


text:
package com.microsoft.azure.management.network;

import java.util.Collection;

import com.microsoft.azure.management.apigeneration.Beta;
import com.microsoft.azure.management.apigeneration.Fluent;
import com.microsoft.azure.management.network.implementation.ApplicationGatewaysInner;
import com.microsoft.azure.management.network.implementation.NetworkManager;
import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsBatchDeletion;
import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsDeletingByResourceGroup;
import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsGettingByResourceGroup;
import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsGettingById;
import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsListingByResourceGroup;
import com.microsoft.azure.management.resources.fluentcore.arm.models.HasManager;
import com.microsoft.azure.management.resources.fluentcore.collection.SupportsBatchCreation;
import com.microsoft.azure.management.resources.fluentcore.collection.SupportsCreating;
import com.microsoft.azure.management.resources.fluentcore.collection.SupportsDeletingById;
import com.microsoft.azure.management.resources.fluentcore.collection.SupportsListing;
import com.microsoft.azure.management.resources.fluentcore.model.HasInner;

import rx.Observable;

/**
 * Entry point to application gateway management API in Azure.
 */
@Fluent()
@Beta()
public interface ApplicationGateways extends
    SupportsCreating<ApplicationGateway.DefinitionStages.Blank>,
    SupportsListing<ApplicationGateway>,
    SupportsListingByResourceGroup<ApplicationGateway>,
    SupportsGettingByResourceGroup<ApplicationGateway>,
    SupportsGettingById<ApplicationGateway>,
    SupportsDeletingById,
    SupportsDeletingByResourceGroup,
    SupportsBatchCreation<ApplicationGateway>,
    SupportsBatchDeletion,
    HasManager<NetworkManager>,
    HasInner<ApplicationGatewaysInner> {

    /**
     * Starts the specified application gateways.
     * @param ids application gateway resource ids
     */
    void start(String...ids);

    /**
     * Starts the specified application gateways.
     * @param ids application gateway resource ids
     */
    void start(Collection<String> ids);

    /**
     * Starts the specified application gateways in parallel asynchronously.
     * @param ids application gateway resource id
     * @return an Observable emitting the resource ID for each successfully started application gateway
     */
    Observable<String> startAsync(String... ids);

    /**
     * Starts the specified application gateways in parallel asynchronously.
     * @param ids application gateway resource id
     * @return an Observable emitting the resource ID for each successfully started application gateway
     */
    Observable<String> startAsync(Collection<String> ids);

    /**
     * Stops the specified application gateways.
     * @param ids application gateway resource ids
     */
    void stop(String...ids);

    /**
     * Stops the specified application gateways.
     * @param ids application gateway resource ids
     */
    void stop(Collection<String> ids);

    /**
     * Stops the specified application gateways in parallel asynchronously.
     * @param ids application gateway resource ids
     * @return an Observable emitting the resource ID for each successfully stopped application gateway
     */
    Observable<String> stopAsync(String...ids);

    /**
     * Stops the specified application gateways in parallel asynchronously.
     * @param ids application gateway resource id
     * @return an Observable emitting the resource ID for each successfully stopped application gateway
     */
    Observable<String> stopAsync(Collection<String> ids);
}


text:
"""An HTTP handler for urllib2 that supports HTTP 1.1 and keepalive.

  import urllib2
  from keepalive import HTTPHandler
  keepalive_handler = HTTPHandler()
  opener = urllib2.build_opener(keepalive_handler)
  urllib2.install_opener(opener)

  fo = urllib2.urlopen('http://www.python.org')

To remove the handler, simply re-run build_opener with no arguments, and
install that opener.

You can explicitly close connections by using the close_connection()
method of the returned file-like object (described below) or you can
use the handler methods:

  close_connection(host)
  close_all()
  open_connections()

Example:

  keepalive_handler.close_all()

EXTRA ATTRIBUTES AND METHODS

  Upon a status of 200, the object returned has a few additional
  attributes and methods, which should not be used if you want to
  remain consistent with the normal urllib2-returned objects:

    close_connection()  -  close the connection to the host
    readlines()         -  you know, readlines()
    status              -  the return status (ie 404)
    reason              -  english translation of status (ie 'File not found')

  If you want the best of both worlds, use this inside an
  AttributeError-catching try:

    try: status = fo.status
    except AttributeError: status = None

  Unfortunately, these are ONLY there if status == 200, so it's not
  easy to distinguish between non-200 responses.  The reason is that
  urllib2 tries to do clever things with error codes 301, 302, 401,
  and 407, and it wraps the object upon return.

  You can optionally set the module-level global HANDLE_ERRORS to 0,
  in which case the handler will always return the object directly.
  If you like the fancy handling of errors, don't do this.  If you
  prefer to see your error codes, then do.

"""
from httplib import _CS_REQ_STARTED, _CS_REQ_SENT, _CS_IDLE, CannotSendHeader

from lib.core.convert import unicodeencode
from lib.core.data import kb

import threading
import urllib2
import httplib
import socket

VERSION = (0, 1)
#STRING_VERSION = '.'.join(map(str, VERSION))
DEBUG = 0
HANDLE_ERRORS = 1

class HTTPHandler(urllib2.HTTPHandler):
    def __init__(self):
        self._connections = {}

    def close_connection(self, host):
        """close connection to <host>
        host is the host:port spec, as in 'www.cnn.com:8080' as passed in.
        no error occurs if there is no connection to that host."""
        self._remove_connection(host, close=1)

    def open_connections(self):
        """return a list of connected hosts"""
        retVal = []
        currentThread = threading.currentThread()
        for name, host in self._connections.keys():
            if name == currentThread.getName():
                retVal.append(host)
        return retVal

    def close_all(self):
        """close all open connections"""
        for _, conn in self._connections.items():
            conn.close()
        self._connections = {}

    def _remove_connection(self, host, close=0):
        key = self._get_connection_key(host)
        if self._connections.has_key(key):
            if close: self._connections[key].close()
            del self._connections[key]

    def _get_connection_key(self, host):
        return (threading.currentThread().getName(), host)

    def _start_connection(self, h, req):
        h.clearheaders()
        try:
            if req.has_data():
                data = req.get_data()
                h.putrequest('POST', req.get_selector())
                if not req.headers.has_key('Content-type'):
                    req.headers['Content-type'] = 'application/x-www-form-urlencoded'
                if not req.headers.has_key('Content-length'):
                    req.headers['Content-length'] = '%d' % len(data)
            else:
                h.putrequest(req.get_method() or 'GET', req.get_selector())

            if not req.headers.has_key('Connection'):
                req.headers['Connection'] = 'keep-alive'

            for args in self.parent.addheaders:
                h.putheader(*args)
            for k, v in req.headers.items():
                h.putheader(k, v)
            h.endheaders()
            if req.has_data():
                h.send(data)
        except socket.error, err:
            h.close()
            raise urllib2.URLError(err)

    def do_open(self, http_class, req):
        h = None
        host = req.get_host()
        if not host:
            raise urllib2.URLError('no host given')

        try:
            need_new_connection = 1
            key = self._get_connection_key(host)
            h = self._connections.get(key)
            if not h is None:
                try:
                    self._start_connection(h, req)
                except:
                    r = None
                else:
                    try: r = h.getresponse()
                    except httplib.ResponseNotReady, e: r = None
                    except httplib.BadStatusLine, e: r = None

                if r is None or r.version == 9:
                    # httplib falls back to assuming HTTP 0.9 if it gets a
                    # bad header back.  This is most likely to happen if
                    # the socket has been closed by the server since we
                    # last used the connection.
                    if DEBUG: print "failed to re-use connection to %s" % host
                    h.close()
                else:
                    if DEBUG: print "re-using connection to %s" % host
                    need_new_connection = 0
            if need_new_connection:
                if DEBUG: print "creating new connection to %s" % host
                h = http_class(host)
                self._connections[key] = h
                self._start_connection(h, req)
                r = h.getresponse()
        except socket.error, err:
            if h: h.close()
            raise urllib2.URLError(err)

        # if not a persistent connection, don't try to reuse it
        if r.will_close: self._remove_connection(host)

        if DEBUG:
            print "STATUS: %s, %s" % (r.status, r.reason)
        r._handler = self
        r._host = host
        r._url = req.get_full_url()

        #if r.status == 200 or not HANDLE_ERRORS:
            #return r
        if r.status == 200 or not HANDLE_ERRORS:
            # [speedplane] Must return an adinfourl object
            resp = urllib2.addinfourl(r, r.msg, req.get_full_url())
            resp.code = r.status
            resp.msg = r.reason
            return resp;
        else:
            r.code = r.status
            return self.parent.error('http', req, r, r.status, r.reason, r.msg)

    def http_open(self, req):
        return self.do_open(HTTPConnection, req)

class HTTPResponse(httplib.HTTPResponse):

    # we need to subclass HTTPResponse in order to
    # 1) add readline() and readlines() methods
    # 2) add close_connection() methods
    # 3) add info() and geturl() methods

    # in order to add readline(), read must be modified to deal with a
    # buffer.  example: readline must read a buffer and then spit back
    # one line at a time.  The only real alternative is to read one
    # BYTE at a time (ick).  Once something has been read, it can't be
    # put back (ok, maybe it can, but that's even uglier than this),
    # so if you THEN do a normal read, you must first take stuff from
    # the buffer.

    # the read method wraps the original to accomodate buffering,
    # although read() never adds to the buffer.
    # Both readline and readlines have been stolen with almost no
    # modification from socket.py

    def __init__(self, sock, debuglevel=0, strict=0, method=None):
        if method: # the httplib in python 2.3 uses the method arg
            httplib.HTTPResponse.__init__(self, sock, debuglevel, method)
        else: # 2.2 doesn't
            httplib.HTTPResponse.__init__(self, sock, debuglevel)
        self.fileno = sock.fileno
        self._method = method
        self._rbuf = ''
        self._rbufsize = 8096
        self._handler = None # inserted by the handler later
        self._host = None    # (same)
        self._url = None     # (same)

    _raw_read = httplib.HTTPResponse.read

    def close_connection(self):
        self.close()
        self._handler._remove_connection(self._host, close=1)

    def info(self):
        return self.msg

    def geturl(self):
        return self._url

    def read(self, amt=None):
        # the _rbuf test is only in this first if for speed.  It's not
        # logically necessary
        if self._rbuf and not amt is None:
            L = len(self._rbuf)
            if amt > L:
                amt -= L
            else:
                s = self._rbuf[:amt]
                self._rbuf = self._rbuf[amt:]
                return s

        s = self._rbuf + self._raw_read(amt)
        self._rbuf = ''
        return s

    def readline(self, limit=-1):
        data = ""
        i = self._rbuf.find('\n')
        while i < 0 and not (0 < limit <= len(self._rbuf)):
            new = self._raw_read(self._rbufsize)
            if not new: break
            i = new.find('\n')
            if i >= 0: i = i + len(self._rbuf)
            self._rbuf = self._rbuf + new
        if i < 0: i = len(self._rbuf)
        else: i = i+1
        if 0 <= limit < len(self._rbuf): i = limit
        data, self._rbuf = self._rbuf[:i], self._rbuf[i:]
        return data

    def readlines(self, sizehint = 0):
        total = 0
        list = []
        while 1:
            line = self.readline()
            if not line: break
            list.append(line)
            total += len(line)
            if sizehint and total >= sizehint:
                break
        return list

class HTTPConnection(httplib.HTTPConnection):
    # use the modified response class
    response_class = HTTPResponse
    _headers = None

    def clearheaders(self):
        self._headers = {}

    def putheader(self, header, value):
        """Send a request header line to the server.

        For example: h.putheader('Accept', 'text/html')
        """
        if self.__state != _CS_REQ_STARTED:
            raise CannotSendHeader()

        self._headers[header] = value

    def endheaders(self):
        """Indicate that the last header line has been sent to the server."""

        if self.__state == _CS_REQ_STARTED:
            self.__state = _CS_REQ_SENT
        else:
            raise CannotSendHeader()

        for header in ('Host', 'Accept-Encoding'):
            if header in self._headers:
                str = '%s: %s' % (header, self._headers[header])
                self._output(str)
                del self._headers[header]

        for header, value in self._headers.items():
            str = '%s: %s' % (header, value)
            self._output(str)

        self._send_output()

    def send(self, str):
        httplib.HTTPConnection.send(self, unicodeencode(str, kb.pageEncoding))

#########################################################################
#####   TEST FUNCTIONS
#########################################################################

def error_handler(url):
    global HANDLE_ERRORS
    orig = HANDLE_ERRORS
    keepalive_handler = HTTPHandler()
    opener = urllib2.build_opener(keepalive_handler)
    urllib2.install_opener(opener)
    pos = {0: 'off', 1: 'on'}
    for i in (0, 1):
        print "  fancy error handling %s (HANDLE_ERRORS = %i)" % (pos[i], i)
        HANDLE_ERRORS = i
        try:
            fo = urllib2.urlopen(url)
            foo = fo.read()
            fo.close()
            try: status, reason = fo.status, fo.reason
            except AttributeError: status, reason = None, None
        except IOError, e:
            print "  EXCEPTION: %s" % e
            raise
        else:
            print "  status = %s, reason = %s" % (status, reason)
    HANDLE_ERRORS = orig
    hosts = keepalive_handler.open_connections()
    print "open connections:", ' '.join(hosts)
    keepalive_handler.close_all()

def continuity(url):
    import md5
    format = '%25s: %s'

    # first fetch the file with the normal http handler
    opener = urllib2.build_opener()
    urllib2.install_opener(opener)
    fo = urllib2.urlopen(url)
    foo = fo.read()
    fo.close()
    m = md5.new(foo)
    print format % ('normal urllib', m.hexdigest())

    # now install the keepalive handler and try again
    opener = urllib2.build_opener(HTTPHandler())
    urllib2.install_opener(opener)

    fo = urllib2.urlopen(url)
    foo = fo.read()
    fo.close()
    m = md5.new(foo)
    print format % ('keepalive read', m.hexdigest())

    fo = urllib2.urlopen(url)
    foo = ''
    while 1:
        f = fo.readline()
        if f: foo = foo + f
        else: break
    fo.close()
    m = md5.new(foo)
    print format % ('keepalive readline', m.hexdigest())

def comp(N, url):
    print '  making %i connections to:\n  %s' % (N, url)

    sys.stdout.write('  first using the normal urllib handlers')
    # first use normal opener
    opener = urllib2.build_opener()
    urllib2.install_opener(opener)
    t1 = fetch(N, url)
    print '  TIME: %.3f s' % t1

    sys.stdout.write('  now using the keepalive handler       ')
    # now install the keepalive handler and try again
    opener = urllib2.build_opener(HTTPHandler())
    urllib2.install_opener(opener)
    t2 = fetch(N, url)
    print '  TIME: %.3f s' % t2
    print '  improvement factor: %.2f' % (t1/t2, )

def fetch(N, url, delay=0):
    lens = []
    starttime = time.time()
    for i in xrange(N):
        if delay and i > 0: time.sleep(delay)
        fo = urllib2.urlopen(url)
        foo = fo.read()
        fo.close()
        lens.append(len(foo))
    diff = time.time() - starttime

    j = 0
    for i in lens[1:]:
        j = j + 1
        if not i == lens[0]:
            print "WARNING: inconsistent length on read %i: %i" % (j, i)

    return diff

def test(url, N=10):
    print "checking error hander (do this on a non-200)"
    try: error_handler(url)
    except IOError, e:
        print "exiting - exception will prevent further tests"
        sys.exit()
    print
    print "performing continuity test (making sure stuff isn't corrupted)"
    continuity(url)
    print
    print "performing speed comparison"
    comp(N, url)

if __name__ == '__main__':
    import time
    import sys
    try:
        N = int(sys.argv[1])
        url = sys.argv[2]
    except:
        print "%s <integer> <url>" % sys.argv[0]
    else:
        test(url, N)


text:
import $ from 'jquery';

export const jqmPermissionDirective = ['µPermManager', function (µPermManager)
{
    return {
        restrict: 'A',
        replace: false,
        scope: {
            jqmPermission: "@",
        },
        link: function (scope, element, attrs)
        {
            var perms = µPermManager.perms;

            var shouldDisplay = function ()
            {
                // If the control does not ask for a particular permission,
                // always enable it.
                if (!scope.jqmPermission)
                {
                    return true;
                }

                // If the user has no permission at all, disable the control
                if (!perms.permissions || perms.permissions.length == 0)
                {
                    return false;
                }

                // The permission to look for (requested permission => r_)
                var r_noun = scope.jqmPermission.split(":")[0];
                var r_verb = scope.jqmPermission.split(":")[1];
                var i = 0;
                var found = false;

                for (i = 0; i < perms.permissions.length; i++)
                {
                    var p = perms.permissions[i];
                    var noun = p.split(":")[0];
                    var verb = p.split(":")[1];

                    if ((r_noun == noun || noun == "*") && (r_verb == verb || verb == "*"))
                    {
                        found = true;
                        break;
                    }
                }
                return found;
            };

            var updatePerm = function ()
            {
                if (!shouldDisplay())
                {
                    element.addClass('d-none');
                }
                else
                {
                    element.removeClass('d-none');
                }
            };

            perms.$promise.then(updatePerm);
        }
    };
}];


text:
package org.apache.giraph.examples;

import org.apache.giraph.graph.BasicComputation;
import org.apache.giraph.graph.Vertex;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;

import java.io.IOException;

/**
 * User applications can subclass IdentityComputation, which
 * simply prints the results that have been read for testing IO related
 * jobs under any inputformat
 *
 * @param <I> Vertex index value
 * @param <V> Vertex value
 * @param <E> Edge value
 * @param <M> Message value
 */
@SuppressWarnings("rawtypes")
public class IdentityComputation<I extends WritableComparable,
  V extends Writable, E extends Writable, M extends Writable>
  extends BasicComputation<I, V, E, M> {
  @Override
  public void compute(Vertex<I, V, E> vertex,
      Iterable<M> messages) throws IOException {
    vertex.voteToHalt();
  }
}


text:
package org.apache.naming.factory;

import java.util.Hashtable;
import javax.naming.Name;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.RefAddr;
import javax.naming.spi.ObjectFactory;
import org.apache.naming.ResourceEnvRef;

/**
 * Object factory for Resources env.
 *
 * @author Remy Maucherat
 * @version $Revision: 1.1.1.1 $ $Date: 2002/07/18 16:47:34 $
 */

public class ResourceEnvFactory
    implements ObjectFactory {

    // ----------------------------------------------------------- Constructors

    // -------------------------------------------------------------- Constants

    // ----------------------------------------------------- Instance Variables

    // --------------------------------------------------------- Public Methods

    // -------------------------------------------------- ObjectFactory Methods

    /**
     * Crete a new Resource env instance.
     *
     * @param obj The reference object describing the DataSource
     */
    public Object getObjectInstance(Object obj, Name name, Context nameCtx,
                                    Hashtable environment)
        throws Exception {

        if (obj instanceof ResourceEnvRef) {
            Reference ref = (Reference) obj;
            ObjectFactory factory = null;
            RefAddr factoryRefAddr = ref.get(Constants.FACTORY);
            if (factoryRefAddr != null) {
                // Using the specified factory
                String factoryClassName =
                    factoryRefAddr.getContent().toString();
                // Loading factory
                ClassLoader tcl =
                    Thread.currentThread().getContextClassLoader();
                Class factoryClass = null;
                if (tcl != null) {
                    try {
                        factoryClass = tcl.loadClass(factoryClassName);
                    } catch(ClassNotFoundException e) {
                    }
                } else {
                    try {
                        factoryClass = Class.forName(factoryClassName);
                    } catch(ClassNotFoundException e) {
                    }
                }
                if (factoryClass != null) {
                    try {
                        factory = (ObjectFactory) factoryClass.newInstance();
                    } catch(Throwable t) {
                    }
                }
            }
            // Note: No defaults here
            if (factory != null) {
                return factory.getObjectInstance
                    (obj, name, nameCtx, environment);
            } else {
                throw new NamingException
                    ("Cannot create resource instance");
            }
        }

        return null;

    }

}


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

namespace StackExchange.Opserver.Data.SQL
{
    public partial class SQLInstance
    {
        private Cache<List<TraceFlagInfo>> _traceFlags;
        public Cache<List<TraceFlagInfo>> TraceFlags => _traceFlags ?? (_traceFlags = SqlCacheList<TraceFlagInfo>(5*60));

        public class TraceFlagInfo : ISQLVersionedObject
        {
            // This likely works fine on 6+, need to test
            public Version MinVersion => SQLServerVersions.SQL2000.RTM;

            public int TraceFlag { get; internal set; }
            public bool Enabled { get; internal set; }
            public bool Global { get; internal set; }
            public int Session { get; internal set; }

            internal const string FetchSQL = @"
Declare @Flags Table(TraceFlag INT, Enabled BIT, Global BIT, Session INT);
Insert Into @Flags Exec('DBCC TRACESTATUS (-1) WITH NO_INFOMSGS');
Select * From @flags;";

            public string GetFetchSQL(Version v)
            {
                return FetchSQL;
            }
        }
    }
}


text:
package Colas;

import ListaDoble.IdDoble;

public interface QueueInterface<T> {

	/**
	 * Metodo: isEmpty()
	 * metodo el cual se encarga de verificar si la cola esta vacia
	 * @return: True, si esta vacia; False, si no lo esta
	 */
public boolean isEmpty();

/**
 * Metodo: getFront()
 * metodo el cual se encarga de retornar el primero de la cola
 * @return IdDoble<T>, con el primero de la cola
 */

public IdDoble<T> getFront();

/**
 * Metodo: getBack()
 * metodo el cual se encarga de retornar el ultimo de la cola
 * @return IdDoble<T>, con el ultimo de la cola
 */

public IdDoble<T> getBack();

/**
 * Metodo: deQueue()
 * metodo el cual se encarga de desencolar en la cola(eliminar el primero)
 */
public void deQueue();

/**
 * Metodo: enQueue()
 * metodo el cual se encarga de encolar en la cola(agregar de ultimo)
 * @param e , con el elemento el cual se va agregar
 */

public void enQueue(T e);

/**
 * Metodo: clear()
 * metodo el cual se encarga de eliminar toda la cola
 */

public void clear();

}


text:
const rbr = require('./index.js');
const test = require('ava');
const execa = require('execa');

test('Testando um domínio disponível', t => {
  rbr('ftonato.com.br').then(result => {
    t.true(result.available);
  });
});

test('Testando domínio indisponível', t => {
  rbr('google.com.br').then(result => {
    t.false(result.available);
  });
});

test('testando domínio com palavras reservadas', t => {
  rbr('braziljs.org').then(result => {
    t.false(result.available);
  });
});

test('deve retornar uma exceção quando a extensão não tiver .br', t => {
  t.throws(execa('./cli.js', ['test.com']), / url informada deve possuir uma das seguintes extensões:/);
});

test('deve retornar uma exceção quando a extensão se o tamanho for menor de dois caracteres', t => {
  t.throws(execa('./cli.js', ['a.com.br']), /O Hostname deve ter no mínimo de 2 e máximo de 26 caracteres./);
});

test('deve retornar uma exceção quando a extensão se o tamanho for maior que 26 caracteres', t => {
  const url = 'a'.repeat(27) + '.com.br';
  t.throws(execa('./cli.js', [url]), /O Hostname deve ter no mínimo de 2 e máximo de 26 caracteres./);
});

test('deve retornar uma exceção quando a hostname terminar com hífen', t => {
  t.throws(execa('./cli.js', ['test-.com.br']), /O Hostname não deve conter hífen no ínicio ou final./);
});

test('deve retornar uma exceção quando o hostname conter apenas números', t => {
  t.throws(execa('./cli.js', ['32132123.com.br']), /O Hostname não deve conter apenas números./);
});

test('deve retornar uma exceção quando o hostname conter caracteres inválidos', t => {
  t.throws(execa('./cli.js', ['te$t.com.br']), /O Hostname deve ser a-z, 0-9, hífen e os seguintes caracteres acentuados: à, á, â, ã, é, ê, í, ó, ô, õ, ú, ü, ç./);
});

test('deve retornar uma exceção quando a hostname iniciar com hífen', t => {
  t.throws(execa('./cli.js', ['-test.com.br']), /O Hostname não deve conter hífen no ínicio ou final./);
});

test('deve retornar uma exceção quando a url é inválida', t => {
  t.throws(execa('./cli.js'), /Por favor, digite uma url válida./);
});


text:
% Copyright 2020 Makani Technologies LLC
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%      http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.

function [dcm] = dcm_about_y(theta)
% dcm_about_y -- Generate a DCM corresponding to a rotation about the y axis.
%
% dcm = dcm_about_y(theta)

dcm = [cos(theta), 0, -sin(theta);
           0,      1,      0;
       sin(theta), 0,  cos(theta)];
end


text:
<?php

namespace UCD\Infrastructure\Repository\CharacterRepository\XMLRepository\ElementParser;

use UCD\Unicode\Codepoint;
use UCD\Unicode\CodepointAssigned;
use UCD\Exception\RuntimeException;
use UCD\Infrastructure\Repository\CharacterRepository\XMLRepository\ElementParser;

class CodepointAssignedParser implements ElementParser
{
    const TAG_NAME_CHAR = 'char';
    const TAG_NAME_NON_CHAR = 'noncharacter';
    const TAG_NAME_SURROGATE = 'surrogate';

    const ATTR_CODEPOINT = 'cp';
    const ATTR_CODEPOINT_FIRST = 'first-cp';
    const ATTR_CODEPOINT_LAST = 'last-cp';

    /**
     * @var CharacterParser
     */
    private $characterParser;

    /**
     * @var NonCharacterParser
     */
    private $nonCharacterParser;

    /**
     * @var SurrogateParser
     */
    private $surrogateParser;

    /**
     * @param CharacterParser $characterParser
     * @param NonCharacterParser $nonCharacterParser
     * @param SurrogateParser $surrogateParser
     */
    public function __construct(
        CharacterParser $characterParser,
        NonCharacterParser $nonCharacterParser,
        SurrogateParser $surrogateParser
    ) {
        $this->characterParser = $characterParser;
        $this->nonCharacterParser = $nonCharacterParser;
        $this->surrogateParser = $surrogateParser;
    }

    /**
     * @param \DOMElement $element
     * @return CodepointAssigned[]
     */
    public function parseElement(\DOMElement $element)
    {
        $parser = $this->getParserForElement($element);
        $codepointValues = $this->extractCodepoints($element);

        foreach ($codepointValues as $codepointValue) {
            $codepoint = Codepoint::fromInt($codepointValue);
            yield $parser->parseElement($element, $codepoint);
        }
    }

    /**
     * @param \DOMElement $element
     * @return CodepointAwareParser
     * @throws RuntimeException
     */
    private function getParserForElement(\DOMElement $element)
    {
        if ($element->tagName === self::TAG_NAME_CHAR) {
            return $this->characterParser;
        } elseif ($element->tagName === self::TAG_NAME_NON_CHAR) {
            return $this->nonCharacterParser;
        } elseif ($element->tagName === self::TAG_NAME_SURROGATE) {
            return $this->surrogateParser;
        }

        throw new RuntimeException(sprintf('No parser found for %s', $element->tagName));
    }

    /**
     * @param \DOMElement $element
     * @return \int[]
     */
    private function extractCodepoints(\DOMElement $element)
    {
        if ($element->hasAttribute(self::ATTR_CODEPOINT)) {
            $first = hexdec($element->getAttribute(self::ATTR_CODEPOINT));
            $last = $first;
        } else {
            $first = hexdec($element->getAttribute(self::ATTR_CODEPOINT_FIRST));
            $last = hexdec($element->getAttribute(self::ATTR_CODEPOINT_LAST));
        }

        return range($first, $last);
    }
}


text:
/*
 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */
package java.lang;

import java.util.*;

/*
 * Class to track and run user level shutdown hooks registered through
 * <tt>{@link Runtime#addShutdownHook Runtime.addShutdownHook}</tt>.
 *
 * @see java.lang.Runtime#addShutdownHook
 * @see java.lang.Runtime#removeShutdownHook
 */

class ApplicationShutdownHooks {
    /* The set of registered hooks */
    private static IdentityHashMap<Thread, Thread> hooks;
    static {
        try {
            Shutdown.add(1 /* shutdown hook invocation order */,
                false /* not registered if shutdown in progress */,
                new Runnable() {
                    public void run() {
                        runHooks();
                    }
                }
            );
            hooks = new IdentityHashMap<>();
        } catch (IllegalStateException e) {
            // application shutdown hooks cannot be added if
            // shutdown is in progress.
            hooks = null;
        }
    }

    private ApplicationShutdownHooks() {}

    /* Add a new shutdown hook.  Checks the shutdown state and the hook itself,
     * but does not do any security checks.
     */
    static synchronized void add(Thread hook) {
        if(hooks == null)
            throw new IllegalStateException("Shutdown in progress");

        if (hook.isAlive())
            throw new IllegalArgumentException("Hook already running");

        if (hooks.containsKey(hook))
            throw new IllegalArgumentException("Hook previously registered");

        hooks.put(hook, hook);
    }

    /* Remove a previously-registered hook.  Like the add method, this method
     * does not do any security checks.
     */
    static synchronized boolean remove(Thread hook) {
        if(hooks == null)
            throw new IllegalStateException("Shutdown in progress");

        if (hook == null)
            throw new NullPointerException();

        return hooks.remove(hook) != null;
    }

    /* Iterates over all application hooks creating a new thread for each
     * to run in. Hooks are run concurrently and this method waits for
     * them to finish.
     */
    static void runHooks() {
        Collection<Thread> threads;
        synchronized(ApplicationShutdownHooks.class) {
            threads = hooks.keySet();
            hooks = null;
        }

        for (Thread hook : threads) {
            hook.start();
        }
        for (Thread hook : threads) {
            try {
                hook.join();
            } catch (InterruptedException x) { }
        }
    }
}


text:
namespace Cartographer.Steps
{
	using System.Linq.Expressions;
	using Cartographer.Compiler;

	public class DelegatingConversionVisitor: ExpressionVisitor
	{
		readonly ParameterExpression contextParameter;

		readonly ParameterExpression mapperParameter;

		readonly ParameterExpression sourceValueParameter;

		readonly MappingStrategy strategy;

		public DelegatingConversionVisitor(MappingStrategy strategy, ParameterExpression sourceValueParameter, ParameterExpression mapperParameter, ParameterExpression contextParameter)
		{
			this.strategy = strategy;
			this.sourceValueParameter = sourceValueParameter;
			this.mapperParameter = mapperParameter;
			this.contextParameter = contextParameter;
		}

		protected override Expression VisitParameter(ParameterExpression node)
		{
			if (node == sourceValueParameter)
			{
				return strategy.ValueExpression;
			}
			if (node == mapperParameter)
			{
				return strategy.MapperExpression;
			}
			if (node == contextParameter)
			{
				return strategy.ContextExpression;
			}
			return base.VisitParameter(node);
		}
	}
}


text:
//
//  Generated by the J2ObjC translator.  DO NOT EDIT!
//  source: android/libcore/luni/src/main/java/java/security/KeyFactory.java
//

#include "../../J2ObjC_header.h"

#pragma push_macro("INCLUDE_ALL_JavaSecurityKeyFactory")
#ifdef RESTRICT_JavaSecurityKeyFactory
#define INCLUDE_ALL_JavaSecurityKeyFactory 0
#else
#define INCLUDE_ALL_JavaSecurityKeyFactory 1
#endif
#undef RESTRICT_JavaSecurityKeyFactory

#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"

#if !defined (JavaSecurityKeyFactory_) && (INCLUDE_ALL_JavaSecurityKeyFactory || defined(INCLUDE_JavaSecurityKeyFactory))
#define JavaSecurityKeyFactory_

@class IOSClass;
@class JavaSecurityKeyFactorySpi;
@class JavaSecurityProvider;
@protocol JavaSecurityKey;
@protocol JavaSecurityPrivateKey;
@protocol JavaSecurityPublicKey;
@protocol JavaSecuritySpecKeySpec;

/*!
 @brief KeyFactory is an engine class that can be used to translate between
 public and private key objects and convert keys between their external
 representation, that can be easily transported and their internal
 representation.
 */
@interface JavaSecurityKeyFactory : NSObject

#pragma mark Public

/*!
 @brief Generates a instance of PrivateKey from the given key
 specification.
 @param keySpec
 the specification of the private key.
 @return the private key.
 @throws InvalidKeySpecException
 if the specified keySpec is invalid.
 */
- (id<JavaSecurityPrivateKey>)generatePrivateWithJavaSecuritySpecKeySpec:(id<JavaSecuritySpecKeySpec>)keySpec;

/*!
 @brief Generates a instance of PublicKey from the given key
 specification.
 @param keySpec
 the specification of the public key
 @return the public key
 @throws InvalidKeySpecException
 if the specified keySpec is invalid
 */
- (id<JavaSecurityPublicKey>)generatePublicWithJavaSecuritySpecKeySpec:(id<JavaSecuritySpecKeySpec>)keySpec;

/*!
 @brief Returns the name of the algorithm associated with this KeyFactory
 .
 @return the name of the algorithm associated with this KeyFactory
 .
 */
- (NSString *)getAlgorithm;

/*!
 @brief Returns a new instance of KeyFactory that utilizes the specified
 algorithm.
 @param algorithm
 the name of the algorithm.
 @return a new instance of KeyFactory that utilizes the specified
 algorithm.
 @throws NoSuchAlgorithmException
 if no provider provides the requested algorithm.
 */
+ (JavaSecurityKeyFactory *)getInstanceWithNSString:(NSString *)algorithm;

/*!
 @brief Returns a new instance of KeyFactory that utilizes the specified
 algorithm from the specified provider.
 The provider supplied
 does not have to be registered.
 @param algorithm
 the name of the algorithm.
 @param provider
 the security provider.
 @return a new instance of KeyFactory that utilizes the specified
 algorithm from the specified provider.
 @throws NoSuchAlgorithmException
 if the provider does not provide the requested algorithm.
 @throws IllegalArgumentException if provider == null
 */
+ (JavaSecurityKeyFactory *)getInstanceWithNSString:(NSString *)algorithm
                           withJavaSecurityProvider:(JavaSecurityProvider *)provider;

/*!
 @brief Returns a new instance of KeyFactory that utilizes the specified
 algorithm from the specified provider.
 @param algorithm
 the name of the algorithm.
 @param provider
 the name of the provider.
 @return a new instance of KeyFactory that utilizes the specified
 algorithm from the specified provider.
 @throws NoSuchAlgorithmException
 if the provider does not provide the requested algorithm.
 @throws NoSuchProviderException
 if the requested provider is not available.
 @throws IllegalArgumentException if provider == null || provider.isEmpty()
 */
+ (JavaSecurityKeyFactory *)getInstanceWithNSString:(NSString *)algorithm
                                       withNSString:(NSString *)provider;

/*!
 @brief Returns the key specification for the specified key.
 @param key
 the key from which the specification is requested.
 @param keySpec
 the type of the requested KeySpec.
 @return the key specification for the specified key.
 @throws InvalidKeySpecException
 if the key can not be processed, or the requested requested
 KeySpec is inappropriate for the given key.
 */
- (id)getKeySpecWithJavaSecurityKey:(id<JavaSecurityKey>)key
                       withIOSClass:(IOSClass *)keySpec;

/*!
 @brief Returns the provider associated with this KeyFactory.
 @return the provider associated with this KeyFactory.
 */
- (JavaSecurityProvider *)getProvider;

/*!
 @brief Translates the given key into a key from this key factory.
 @param key
 the key to translate.
 @return the translated key.
 @throws InvalidKeyException
 if the specified key can not be translated by this key
 factory.
 */
- (id<JavaSecurityKey>)translateKeyWithJavaSecurityKey:(id<JavaSecurityKey>)key;

#pragma mark Protected

/*!
 @brief Constructs a new instance of KeyFactory with the specified
 arguments.
 @param keyFacSpi
 the concrete key factory service.
 @param provider
 the provider.
 @param algorithm
 the algorithm to use.
 */
- (instancetype)initWithJavaSecurityKeyFactorySpi:(JavaSecurityKeyFactorySpi *)keyFacSpi
                         withJavaSecurityProvider:(JavaSecurityProvider *)provider
                                     withNSString:(NSString *)algorithm;

@end

J2OBJC_STATIC_INIT(JavaSecurityKeyFactory)

FOUNDATION_EXPORT void JavaSecurityKeyFactory_initWithJavaSecurityKeyFactorySpi_withJavaSecurityProvider_withNSString_(JavaSecurityKeyFactory *self, JavaSecurityKeyFactorySpi *keyFacSpi, JavaSecurityProvider *provider, NSString *algorithm);

FOUNDATION_EXPORT JavaSecurityKeyFactory *new_JavaSecurityKeyFactory_initWithJavaSecurityKeyFactorySpi_withJavaSecurityProvider_withNSString_(JavaSecurityKeyFactorySpi *keyFacSpi, JavaSecurityProvider *provider, NSString *algorithm) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT JavaSecurityKeyFactory *create_JavaSecurityKeyFactory_initWithJavaSecurityKeyFactorySpi_withJavaSecurityProvider_withNSString_(JavaSecurityKeyFactorySpi *keyFacSpi, JavaSecurityProvider *provider, NSString *algorithm);

FOUNDATION_EXPORT JavaSecurityKeyFactory *JavaSecurityKeyFactory_getInstanceWithNSString_(NSString *algorithm);

FOUNDATION_EXPORT JavaSecurityKeyFactory *JavaSecurityKeyFactory_getInstanceWithNSString_withNSString_(NSString *algorithm, NSString *provider);

FOUNDATION_EXPORT JavaSecurityKeyFactory *JavaSecurityKeyFactory_getInstanceWithNSString_withJavaSecurityProvider_(NSString *algorithm, JavaSecurityProvider *provider);

J2OBJC_TYPE_LITERAL_HEADER(JavaSecurityKeyFactory)

#endif

#pragma clang diagnostic pop
#pragma pop_macro("INCLUDE_ALL_JavaSecurityKeyFactory")


text:
module AuthenticationHelper
  def stub_sign_in(user, token = hound_token)
    session[:remember_token] = user.remember_token
    session[:github_token] = token
  end

  def sign_in_as(user, token = hound_token)
    stub_oauth(
      username: user.github_username,
      email: user.email_address,
      token: token
    )
    visit root_path
    click_link(I18n.t('authenticate'), match: :first)
  end
end


text:
package com.demo.dao.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {
	private static DBUtil instance;

	private String driverClassName = "com.mysql.jdbc.Driver";

	private String url = "jdbc:mysql://localhost:3306/Spider001";

	private String user = "root";

	private String password = "123456";

	private DBUtil(){

		try {
			Class.forName(driverClassName);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static DBUtil getInstance(){
		if(instance == null){
			instance = new DBUtil();
		}
		return instance ;
	}

	public Connection getConnection() throws SQLException{
		Connection conn = null;
		conn = DriverManager.getConnection(url,user,password);
		return conn;
	}

	public void free(Connection conn, PreparedStatement stmt, ResultSet rs){
		try {
			if(rs!=null)
				rs.close();
			if(stmt!=null)
				stmt.close();
			if(conn!=null)
				conn.close();
			} catch (SQLException e) {
					// TODO Auto-generated catch block
				e.printStackTrace();
			}

	}
}


text:
ProfileInfoWatcher::ProfileInfoWatcher(
    Profile* profile, const base::Closure& callback)
    : profile_(profile), callback_(callback) {
  DCHECK(profile_);
  DCHECK(!callback_.is_null());

  ProfileManager* profile_manager = g_browser_process->profile_manager();
  // The profile_manager might be NULL in testing environments.
  if (profile_manager)
    profile_manager->GetProfileAttributesStorage().AddObserver(this);

  signin_allowed_pref_.Init(prefs::kSigninAllowed, profile_->GetPrefs(),
      base::Bind(&ProfileInfoWatcher::RunCallback, base::Unretained(this)));
}

ProfileInfoWatcher::~ProfileInfoWatcher() {
  ProfileManager* profile_manager = g_browser_process->profile_manager();
  // The profile_manager might be NULL in testing environments.
  if (profile_manager)
    profile_manager->GetProfileAttributesStorage().RemoveObserver(this);
}

void ProfileInfoWatcher::OnProfileAuthInfoChanged(
    const base::FilePath& profile_path) {
  RunCallback();
}

std::string ProfileInfoWatcher::GetAuthenticatedUsername() const {
  std::string username;
  SigninManagerBase* signin_manager = GetSigninManager();
  if (signin_manager)
    username = signin_manager->GetAuthenticatedAccountInfo().email;
  return username;
}

SigninManagerBase* ProfileInfoWatcher::GetSigninManager() const {
  return SigninManagerFactory::GetForProfile(profile_);
}

void ProfileInfoWatcher::RunCallback() {
  if (GetSigninManager())
    callback_.Run();
}


text:
package com.glaf.base.modules.tenant.web.springmvc;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.glaf.base.modules.sys.SysConstants;
import com.glaf.base.modules.sys.business.UpdateTreeBean;
import com.glaf.base.modules.sys.model.Dictory;
import com.glaf.base.modules.sys.model.SysOrganization;
import com.glaf.base.modules.sys.model.SysRole;
import com.glaf.base.modules.sys.model.SysTenant;
import com.glaf.base.modules.sys.model.SysUser;
import com.glaf.base.modules.sys.query.SysUserQuery;
import com.glaf.base.modules.sys.service.DictoryService;
import com.glaf.base.modules.sys.service.SysOrganizationService;
import com.glaf.base.modules.sys.service.SysRoleService;
import com.glaf.base.modules.sys.service.SysTenantService;
import com.glaf.base.modules.sys.service.SysUserService;
import com.glaf.base.utils.ParamUtil;
import com.glaf.base.utils.RequestUtil;
import com.glaf.core.base.TreeModel;
import com.glaf.core.cache.CacheUtils;
import com.glaf.core.config.ViewProperties;
import com.glaf.core.security.LoginContext;
import com.glaf.core.service.EntityService;
import com.glaf.core.service.ITableDataService;
import com.glaf.core.util.PageResult;
import com.glaf.core.util.ParamUtils;
import com.glaf.core.util.RequestUtils;
import com.glaf.core.util.ResponseUtils;
import com.glaf.core.util.StringTools;
import com.glaf.core.util.Tools;

@Controller("/tenant/user")
@RequestMapping("/tenant/user")
public class TenantUserController {
	private static final Log logger = LogFactory.getLog(TenantUserController.class);

	protected DictoryService dictoryService;

	protected EntityService entityService;

	protected SysRoleService sysRoleService;

	protected SysUserService sysUserService;

	protected ITableDataService tableDataService;

	protected SysOrganizationService sysOrganizationService;

	protected SysTenantService sysTenantService;

	@RequestMapping("/json")
	@ResponseBody
	public byte[] json(HttpServletRequest request) throws IOException {
		LoginContext loginContext = RequestUtils.getLoginContext(request);
		long organizationId = RequestUtils.getLong(request, "organizationId");

		Map<String, Object> params = RequestUtils.getParameterMap(request);

		SysUserQuery query = new SysUserQuery();
		Tools.populate(query, params);
		query.setDeleteFlag(0);
		query.setUserType(8);

		if (loginContext.isSystemAdministrator()) {
			query.tenantId(request.getParameter("tenantId"));
		} else {
			query.tenantId(loginContext.getTenantId());
		}

		if (organizationId > 0) {
			query.organizationId(organizationId);
		}

		int start = 0;
		int limit = 10;
		String orderName = null;
		String order = null;

		int pageNo = ParamUtils.getInt(params, "page");
		limit = ParamUtils.getInt(params, "rows");
		start = (pageNo - 1) * limit;
		orderName = ParamUtils.getString(params, "sortName");
		order = ParamUtils.getString(params, "sortOrder");

		if (start < 0) {
			start = 0;
		}

		if (limit <= 0) {
			limit = PageResult.DEFAULT_PAGE_SIZE;
		}

		JSONObject result = new JSONObject();
		int total = sysUserService.getSysUserCountByQueryCriteria(query);
		if (loginContext.isTenantAdmin()) {
			total = total - 1;
		}

		if (total > 0) {
			result.put("total", total);
			result.put("totalCount", total);
			result.put("totalRecords", total);
			result.put("start", start);
			result.put("startIndex", start);
			result.put("limit", limit);
			result.put("pageSize", limit);

			if (StringUtils.isNotEmpty(orderName)) {
				query.setSortOrder(orderName);
				if (StringUtils.equals(order, "desc")) {
					query.setSortOrder(" desc ");
				}
			}

			List<SysUser> list = sysUserService.getSysUsersByQueryCriteria(start, limit, query);

			if (list != null && !list.isEmpty()) {
				JSONArray rowsJSON = new JSONArray();

				for (SysUser sysUser : list) {
					if (loginContext.isTenantAdmin()
							&& StringUtils.equals(sysUser.getActorId(), loginContext.getActorId())) {
						continue;
					}
					JSONObject rowJSON = sysUser.toJsonObject();
					rowJSON.put("id", sysUser.getId());
					rowJSON.put("userId", sysUser.getUserId());
					rowJSON.put("startIndex", ++start);
					rowJSON.remove("token");
					rowsJSON.add(rowJSON);
				}

				result.put("rows", rowsJSON);

			}
		} else {
			result.put("total", total);
			result.put("totalCount", total);
			JSONArray rowsJSON = new JSONArray();
			result.put("rows", rowsJSON);
		}
		return result.toString().getBytes("UTF-8");
	}

	@RequestMapping
	public ModelAndView list(HttpServletRequest request, ModelMap modelMap) {
		RequestUtils.setRequestParameterToAttribute(request);

		String x_view = ViewProperties.getString("tenant.user.list");
		if (StringUtils.isNotEmpty(x_view)) {
			return new ModelAndView(x_view, modelMap);
		}

		String view = request.getParameter("view");
		if (StringUtils.isNotEmpty(view)) {
			return new ModelAndView(view, modelMap);
		}

		return new ModelAndView("/tenant/user/list", modelMap);
	}

	/**
	 * 显示增加页面
	 *
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("/prepareAdd")
	public ModelAndView prepareAdd(HttpServletRequest request, ModelMap modelMap) {
		RequestUtils.setRequestParameterToAttribute(request);
		LoginContext loginContext = RequestUtils.getLoginContext(request);
		String tenantId = request.getParameter("tenantId");
		if (!loginContext.isSystemAdministrator()) {
			tenantId = loginContext.getTenantId();
		}
		List<SysOrganization> list = sysOrganizationService.getSysOrganizationList(tenantId);
		if (list != null && !list.isEmpty()) {
			Map<Long, TreeModel> treeMap = new HashMap<Long, TreeModel>();
			List<TreeModel> treeModels = new ArrayList<TreeModel>();
			for (SysOrganization model2 : list) {
				treeModels.add(model2);
				treeMap.put(model2.getId(), model2);
			}
			StringTokenizer token = null;
			StringBuilder blank = new StringBuilder();
			UpdateTreeBean bean = new UpdateTreeBean();
			List<SysOrganization> modelList = new ArrayList<SysOrganization>();
			for (SysOrganization model2 : list) {
				String treeId = bean.getTreeId(treeMap, model2);
				if (treeId != null && treeId.indexOf("|") != -1) {
					token = new StringTokenizer(treeId, "|");
					if (token != null) {
						model2.setLevel(token.countTokens());
						blank.delete(0, blank.length());
						for (int i = 0; i < model2.getLevel(); i++) {
							blank.append("    ");
						}
						model2.setBlank(blank.toString());
					}
				}
				modelList.add(model2);
			}
			request.setAttribute("trees", modelList);
		}

		List<Dictory> dictories = dictoryService.getDictoryList(SysConstants.USER_HEADSHIP);
		modelMap.put("dictories", dictories);

		List<Dictory> accounts = dictoryService.getDictoryList(SysConstants.USER_ACCOUNTTYPE);
		modelMap.put("accountTypeDictories", accounts);

		String x_view = ViewProperties.getString("tenant.user.prepareAdd");
		if (StringUtils.isNotEmpty(x_view)) {
			return new ModelAndView(x_view, modelMap);
		}

		return new ModelAndView("/tenant/user/user_add", modelMap);
	}

	/**
	 * 显示修改页面
	 *
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("/prepareModify")
	public ModelAndView prepareModify(HttpServletRequest request, ModelMap modelMap) {
		RequestUtils.setRequestParameterToAttribute(request);
		LoginContext loginContext = RequestUtils.getLoginContext(request);
		String tenantId = request.getParameter("tenantId");
		if (!loginContext.isSystemAdministrator()) {
			tenantId = loginContext.getTenantId();
		}

		String userId = ParamUtil.getParameter(request, "userId");
		userId = RequestUtils.decodeString(userId);
		SysUser user = sysUserService.findById(userId);
		if (user != null) {
			tenantId = user.getTenantId();
			List<SysOrganization> list = sysOrganizationService.getSysOrganizationList(tenantId);
			if (list != null && !list.isEmpty()) {
				Map<Long, TreeModel> treeMap = new HashMap<Long, TreeModel>();
				List<TreeModel> treeModels = new ArrayList<TreeModel>();
				for (SysOrganization model2 : list) {
					treeModels.add(model2);
					treeMap.put(model2.getId(), model2);
				}
				StringTokenizer token = null;
				StringBuilder blank = new StringBuilder();
				UpdateTreeBean bean = new UpdateTreeBean();
				List<SysOrganization> modelList = new ArrayList<SysOrganization>();
				for (SysOrganization model2 : list) {
					String treeId = bean.getTreeId(treeMap, model2);
					if (treeId != null && treeId.indexOf("|") != -1) {
						token = new StringTokenizer(treeId, "|");
						if (token != null) {
							model2.setLevel(token.countTokens());
							blank.delete(0, blank.length());
							for (int i = 0; i < model2.getLevel(); i++) {
								blank.append("    ");
							}
							model2.setBlank(blank.toString());
						}
					}
					modelList.add(model2);
				}
				request.setAttribute("trees", modelList);
			}

			request.setAttribute("user", user);
			request.setAttribute("userId_encode", RequestUtils.encodeString(user.getActorId()));
		}

		List<Dictory> dictories = dictoryService.getDictoryList(SysConstants.USER_HEADSHIP);
		modelMap.put("dictories", dictories);

		List<Dictory> accounts = dictoryService.getDictoryList(SysConstants.USER_ACCOUNTTYPE);
		modelMap.put("accountTypeDictories", accounts);

		String x_view = ViewProperties.getString("tenant.user.prepareModify");
		if (StringUtils.isNotEmpty(x_view)) {
			return new ModelAndView(x_view, modelMap);
		}

		return new ModelAndView("/tenant/user/user_modify", modelMap);
	}

	/**
	 * 显示修改页面
	 *
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("/prepareModifyInfo")
	public ModelAndView prepareModifyInfo(HttpServletRequest request, ModelMap modelMap) {
		RequestUtils.setRequestParameterToAttribute(request);
		SysUser user = RequestUtil.getLoginUser(request);
		SysUser bean = sysUserService.findByAccount(user.getUserId());
		request.setAttribute("bean", bean);

		List<Dictory> dictories = dictoryService.getDictoryList(SysConstants.USER_HEADSHIP);
		modelMap.put("dictories", dictories);

		String x_view = ViewProperties.getString("tenant.user.prepareModifyInfo");
		if (StringUtils.isNotEmpty(x_view)) {
			return new ModelAndView(x_view, modelMap);
		}

		return new ModelAndView("/tenant/user/user_change_info", modelMap);
	}

	/**
	 * 显示修改页面
	 *
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("/prepareModifyPwd")
	public ModelAndView prepareModifyPwd(HttpServletRequest request, ModelMap modelMap) {
		RequestUtils.setRequestParameterToAttribute(request);
		SysUser bean = RequestUtil.getLoginUser(request);
		request.setAttribute("bean", bean);

		String x_view = ViewProperties.getString("tenant.user.prepareModifyPwd");
		if (StringUtils.isNotEmpty(x_view)) {
			return new ModelAndView(x_view, modelMap);
		}

		return new ModelAndView("/tenant/user/user_modify_pwd", modelMap);
	}

	/**
	 * 显示重置密码页面
	 *
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("/prepareResetPwd")
	public ModelAndView prepareResetPwd(HttpServletRequest request, ModelMap modelMap) {
		RequestUtils.setRequestParameterToAttribute(request);
		String userId = ParamUtil.getParameter(request, "userId");
		userId = RequestUtils.decodeString(userId);
		SysUser bean = sysUserService.findById(userId);
		request.setAttribute("user", bean);
		request.setAttribute("userId_encode", ParamUtil.getParameter(request, "userId"));

		String x_view = ViewProperties.getString("tenant.user.prepareResetPwd");
		if (StringUtils.isNotEmpty(x_view)) {
			return new ModelAndView(x_view, modelMap);
		}

		return new ModelAndView("/tenant/user/user_reset_pwd", modelMap);
	}

	/**
	 * 重置登录信息
	 *
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/resetLoginStatus")
	public byte[] resetLoginStatus(HttpServletRequest request) {
		logger.debug(RequestUtils.getParameterMap(request));
		String userId = request.getParameter("userId");
		userId = RequestUtils.decodeString(userId);
		SysUser user = sysUserService.findByAccount(userId);
		if (user != null) {
			sysUserService.resetLoginStatus(userId);
			return ResponseUtils.responseJsonResult(true, "重置登录信息成功。");
		}
		return ResponseUtils.responseResult(false);
	}

	/**
	 * 重置用户密码
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/resetPwd")
	@ResponseBody
	public byte[] resetPwd(HttpServletRequest request) {
		RequestUtils.setRequestParameterToAttribute(request);
		LoginContext loginContext = RequestUtils.getLoginContext(request);

		if (loginContext.isSystemAdministrator() || loginContext.isTenantAdmin()) {
			logger.debug(loginContext.getActorId() + " is admin");
		}

		/**
		 * 只允许admin账户才能重置其他用户的密码
		 */
		if (loginContext.isTenantAdmin() || (loginContext.isSystemAdministrator()
				&& (StringUtils.equalsIgnoreCase(loginContext.getActorId(), "admin")))) {
			String userId = ParamUtil.getParameter(request, "userId");
			userId = RequestUtils.decodeString(userId);
			SysUser user = sysUserService.findById(userId);
			if (user != null) {
				if (loginContext.isTenantAdmin()) {
					if (!StringUtils.equals(user.getTenantId(), loginContext.getTenantId())) {
						return ResponseUtils.responseResult(false);
					}
				}
				/**
				 * admin系统管理员的密码不允许重置
				 */
				if (!(StringUtils.equalsIgnoreCase(user.getUserId(), "admin"))) {
					String newPwd = ParamUtil.getParameter(request, "newPwd");
					if (user != null && StringUtils.isNotEmpty(newPwd)) {
						logger.info(loginContext.getActorId() + "重置" + user.getName() + "的密码。");
						try {
							sysUserService.changePassword(user.getUserId(), newPwd);
							return ResponseUtils.responseResult(true);
						} catch (Exception ex) {
							logger.error(ex);
						}
					}
				}
			}
		}

		return ResponseUtils.responseResult(false);
	}

	/**
	 * 提交增加信息
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/saveAdd")
	@ResponseBody
	public byte[] saveAdd(HttpServletRequest request) {
		LoginContext loginContext = RequestUtils.getLoginContext(request);
		if (loginContext.isTenantAdmin() || loginContext.isSystemAdministrator()) {
			String tenantId = request.getParameter("tenantId");
			SysTenant sysTenant = null;
			try {
				if (!loginContext.isSystemAdministrator()) {
					tenantId = loginContext.getTenantId();
				}
				sysTenant = sysTenantService.getSysTenantByTenantId(tenantId);
				if (sysTenant != null && sysTenant.getLocked() == 0) {
					SysUser bean = new SysUser();
					Tools.populate(bean, RequestUtils.getParameterMap(request));
					bean.setOrganizationId(RequestUtils.getLong(request, "organizationId"));
					bean.setTenantId(sysTenant.getTenantId());
					bean.setUserId(String.valueOf(sysTenant.getId()
							+ StringTools.getDigit3Id(entityService.nextId("tenant_" + sysTenant.getId()).intValue())));
					bean.setName(ParamUtil.getParameter(request, "name"));
					String password = ParamUtil.getParameter(request, "password");
					bean.setPasswordHash(password);
					bean.setSex(ParamUtil.getIntParameter(request, "sex", 0));
					bean.setMobile(ParamUtil.getParameter(request, "mobile"));
					bean.setEmail(ParamUtil.getParameter(request, "email"));
					bean.setTelephone(ParamUtil.getParameter(request, "telephone"));
					bean.setLocked(ParamUtil.getIntParameter(request, "locked", 0));
					bean.setHeadship(ParamUtil.getParameter(request, "headship"));
					bean.setAccountType(8);
					bean.setUserType(8);
					bean.setEvection(0);
					bean.setCreateTime(new Date());
					bean.setCreateBy(RequestUtils.getActorId(request));
					bean.setUpdateBy(RequestUtils.getActorId(request));

					if (StringUtils.isNotEmpty(bean.getUserId()) && StringUtils.isNotEmpty(bean.getName())) {
						if (sysUserService.findByAccount(bean.getUserId()) == null) {
							if (sysUserService.create(bean)) {
								return ResponseUtils.responseJsonResult(true, "新用户编号为" + bean.getUserId());
							}
							return ResponseUtils.responseResult(false);
						}
					}
				} else {
					return ResponseUtils.responseJsonResult(false, "必须是管理员才能创建用户。");
				}
			} catch (Exception ex) {
				logger.error(ex);
			}
		} else {
			return ResponseUtils.responseJsonResult(false, "管理员才能创建用户。");
		}
		return ResponseUtils.responseResult(false);
	}

	/**
	 * 提交修改信息
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/saveModify")
	@ResponseBody
	public byte[] saveModify(HttpServletRequest request) {
		LoginContext loginContext = RequestUtils.getLoginContext(request);
		if (loginContext.isTenantAdmin() || loginContext.isSystemAdministrator()) {
			String userId = ParamUtil.getParameter(request, "userId");
			try {
				userId = RequestUtils.decodeString(userId);
				logger.debug("userId = " + userId);
				SysUser bean = sysUserService.findById(userId);
				boolean ret = false;
				if (bean != null && (loginContext.isSystemAdministrator()
						|| StringUtils.equals(loginContext.getTenantId(), bean.getTenantId()))) {
					Tools.populate(bean, RequestUtils.getParameterMap(request));
					bean.setOrganizationId(RequestUtils.getLong(request, "organizationId"));
					bean.setName(ParamUtil.getParameter(request, "name"));
					bean.setSex(ParamUtil.getIntParameter(request, "sex", 0));
					bean.setMobile(ParamUtil.getParameter(request, "mobile"));
					bean.setEmail(ParamUtil.getParameter(request, "email"));
					bean.setTelephone(ParamUtil.getParameter(request, "telephone"));
					bean.setEvection(ParamUtil.getIntParameter(request, "evection", 0));
					bean.setLocked(ParamUtil.getIntParameter(request, "locked", 0));
					bean.setHeadship(ParamUtil.getParameter(request, "headship"));
					bean.setUpdateBy(RequestUtils.getActorId(request));
					bean.setUserId(userId);
					logger.debug("organizationId:" + bean.getOrganizationId());
					ret = sysUserService.update(bean);
					return ResponseUtils.responseResult(ret);
				}
			} catch (Exception ex) {
				logger.error(ex);
			}
		}
		return ResponseUtils.responseResult(false);
	}

	/**
	 * 提交修改信息
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/saveModifyInfo")
	@ResponseBody
	public byte[] saveModifyInfo(HttpServletRequest request) {
		SysUser bean = RequestUtil.getLoginUser(request);
		boolean ret = false;
		if (bean != null) {
			try {
				SysUser user = sysUserService.findById(bean.getActorId());
				user.setMobile(ParamUtil.getParameter(request, "mobile"));
				user.setEmail(ParamUtil.getParameter(request, "email"));
				user.setTelephone(ParamUtil.getParameter(request, "telephone"));
				user.setUpdateBy(RequestUtils.getActorId(request));
				ret = sysUserService.update(user);
				CacheUtils.clearUserCache(user.getUserId());
				return ResponseUtils.responseResult(ret);
			} catch (Exception ex) {
				logger.error(ex);
			}
		}

		return ResponseUtils.responseResult(false);
	}

	/**
	 * 修改用户密码
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/savePwd")
	@ResponseBody
	public byte[] savePwd(HttpServletRequest request) {
		SysUser bean = RequestUtil.getLoginUser(request);
		String oldPwd = ParamUtil.getParameter(request, "oldPwd");
		String newPwd = ParamUtil.getParameter(request, "newPwd");
		if (bean != null && StringUtils.isNotEmpty(oldPwd) && StringUtils.isNotEmpty(newPwd)) {
			try {
				SysUser user = sysUserService.findById(bean.getActorId());
				if (sysUserService.checkPassword(user.getUserId(), oldPwd)) {
					sysUserService.changePassword(user.getUserId(), newPwd);
					return ResponseUtils.responseResult(true);
				}
			} catch (Exception ex) {
				logger.error(ex);
			}
		}
		return ResponseUtils.responseResult(false);
	}

	/**
	 * 设置用户角色
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/saveRole")
	@ResponseBody
	public byte[] saveRole(HttpServletRequest request) {
		LoginContext loginContext = RequestUtils.getLoginContext(request);
		if (loginContext.isTenantAdmin() || loginContext.isSystemAdministrator()) {
			String userId = ParamUtil.getParameter(request, "userId");
			SysUser user = sysUserService.findById(userId);// 查找用户对象
			if (user != null && (loginContext.isSystemAdministrator()
					|| StringUtils.equals(loginContext.getTenantId(), user.getTenantId()))) {// 用户存在
				String[] ids = ParamUtil.getParameterValues(request, "id");// 获取页面参数
				if (ids != null) {
					Set<SysRole> newRoles = new HashSet<SysRole>();
					for (int i = 0; i < ids.length; i++) {
						logger.debug("id[" + i + "]=" + ids[i]);
						SysRole role = sysRoleService.findById(ids[i]);// 查找角色对象
						if (role != null) {
							newRoles.add(role);// 加入到角色列表
						}
					}
					user.setUpdateBy(RequestUtils.getActorId(request));
					if (sysUserService.updateUserRole(user, 0, newRoles)) {// 授权成功
						return ResponseUtils.responseResult(true);
					}
				}
			}
		}

		return ResponseUtils.responseResult(false);
	}

	/**
	 * 提交修改信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/saveUserRole")
	public byte[] saveUserRole(HttpServletRequest request) {
		LoginContext loginContext = RequestUtils.getLoginContext(request);
		if (loginContext.isTenantAdmin() || loginContext.isSystemAdministrator()) {
			String roleId = ParamUtil.getParameter(request, "roleId");
			String userId = request.getParameter("userId");
			String operation = request.getParameter("operation");
			SysRole bean = sysRoleService.findById(roleId);
			SysUser user = sysUserService.findByAccountWithAll(userId);
			if (bean != null && user != null && (loginContext.isSystemAdministrator()
					|| StringUtils.equals(loginContext.getTenantId(), user.getTenantId()))) {
				if (StringUtils.equals(operation, "revoke")) {
					sysUserService.deleteRoleUser(roleId, userId);
				} else {
					sysUserService.createRoleUser(roleId, userId);
				}
				return ResponseUtils.responseResult(true);
			}
		}

		return ResponseUtils.responseResult(false);
	}

	/**
	 * 设置用户角色
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/saveUserRoles")
	public byte[] saveUserRoles(HttpServletRequest request) {
		LoginContext loginContext = RequestUtils.getLoginContext(request);
		if (loginContext.isTenantAdmin() || loginContext.isSystemAdministrator()) {
			String userId = RequestUtils.decodeString(request.getParameter("userId"));
			String objectIds = request.getParameter("objectIds");
			logger.debug("userId:" + userId);
			SysUser user = sysUserService.findById(userId);// 查找用户对象
			logger.debug("user:" + user);
			if (user != null && (loginContext.isSystemAdministrator()
					|| StringUtils.equals(loginContext.getTenantId(), user.getTenantId()))) {
				Set<SysRole> newRoles = new HashSet<SysRole>();
				if (StringUtils.isNotEmpty(objectIds)) {
					List<String> roleIds = StringTools.split(objectIds);// 获取页面参数
					if (roleIds != null) {
						for (int i = 0; i < roleIds.size(); i++) {
							logger.debug("roleId[" + i + "]=" + roleIds.get(i));
							SysRole role = sysRoleService.findById(roleIds.get(i));// 查找角色对象
							if (role != null) {
								newRoles.add(role);// 加入到角色列表
							}
						}
					}
				}
				logger.debug("newRoles:" + newRoles);
				user.setUpdateBy(RequestUtils.getActorId(request));
				if (sysUserService.updateUserRole(user, 0, newRoles)) {
					// 授权成功
					return ResponseUtils.responseResult(true);
				}
			}
		}
		return ResponseUtils.responseResult(false);
	}

	@javax.annotation.Resource
	public void setDictoryService(DictoryService dictoryService) {
		this.dictoryService = dictoryService;
	}

	@javax.annotation.Resource
	public void setEntityService(EntityService entityService) {
		this.entityService = entityService;
	}

	@javax.annotation.Resource
	public void setSysOrganizationService(SysOrganizationService sysOrganizationService) {
		this.sysOrganizationService = sysOrganizationService;
	}

	@javax.annotation.Resource
	public void setSysRoleService(SysRoleService sysRoleService) {
		this.sysRoleService = sysRoleService;
	}

	@javax.annotation.Resource
	public void setSysTenantService(SysTenantService sysTenantService) {
		this.sysTenantService = sysTenantService;
	}

	@javax.annotation.Resource
	public void setSysUserService(SysUserService sysUserService) {
		this.sysUserService = sysUserService;
	}

	@javax.annotation.Resource
	public void setTableDataService(ITableDataService tableDataService) {
		this.tableDataService = tableDataService;
	}

	/**
	 * 显示角色
	 *
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("/showRole")
	public ModelAndView showRole(HttpServletRequest request, ModelMap modelMap) {
		RequestUtils.setRequestParameterToAttribute(request);
		String userId = ParamUtil.getParameter(request, "userId");
		userId = RequestUtils.decodeString(userId);
		logger.debug("userId:" + userId);
		LoginContext loginContext = RequestUtils.getLoginContext(request);
		if (loginContext.isTenantAdmin() || loginContext.isSystemAdministrator()) {
			SysUser user = sysUserService.findByAccountWithAll(userId);
			if (user != null && (loginContext.isSystemAdministrator()
					|| StringUtils.equals(loginContext.getTenantId(), user.getTenantId()))) {
				List<SysRole> list = new ArrayList<SysRole>();
				List<SysRole> roles = sysRoleService.getSysRoleList();
				if (roles != null && !roles.isEmpty()) {
					for (SysRole role : roles) {
						if (StringUtils.equals(role.getIsUseOrganization(), "Y")) {
							list.add(role);
						}
					}
				}

				List<SysRole> userRoles = sysUserService.getUserRoles(userId);
				List<String> selecteds = new ArrayList<String>();

				if (userRoles != null && !userRoles.isEmpty()) {
					for (SysRole role : userRoles) {
						selecteds.add(role.getId());
					}
				}

				request.setAttribute("user", user);
				request.setAttribute("list", list);

				logger.debug("可分配角色:" + list.size());

				StringBuilder bufferx = new StringBuilder();
				StringBuilder buffery = new StringBuilder();

				if (list != null && list.size() > 0) {
					for (int j = 0; j < list.size(); j++) {
						SysRole r = (SysRole) list.get(j);
						if (selecteds != null && selecteds.contains(r.getId())) {
							buffery.append("\n<option value=\"").append(r.getId()).append("\">").append(r.getName())
									.append("</option>");
						} else {
							bufferx.append("\n<option value=\"").append(r.getId()).append("\">").append(r.getName())
									.append("</option>");
						}
					}
				}

				request.setAttribute("bufferx", bufferx.toString());
				request.setAttribute("buffery", buffery.toString());
			}
		}

		String x_view = ViewProperties.getString("tenant.user.userRole");
		if (StringUtils.isNotEmpty(x_view)) {
			return new ModelAndView(x_view, modelMap);
		}

		// 显示列表页面
		return new ModelAndView("/tenant/user/userRole", modelMap);
	}

	/**
	 * 查看角色用户
	 *
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("/showUser")
	public ModelAndView showUser(HttpServletRequest request, ModelMap modelMap) {
		RequestUtils.setRequestParameterToAttribute(request);
		String userId = ParamUtil.getParameter(request, "userId");
		userId = RequestUtils.decodeString(userId);
		SysUser user = sysUserService.findById(userId);
		request.setAttribute("user", user);

		String x_view = ViewProperties.getString("tenant.user.showUser");
		if (StringUtils.isNotEmpty(x_view)) {
			return new ModelAndView(x_view, modelMap);
		}

		return new ModelAndView("/tenant/user/user_info", modelMap);
	}

}


text:
namespace EasyNetQ.Management.Client.Model
{
    public class AuthMechanism
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public bool Enabled { get; set; }
    }
}


text:
// <auto-generated/>
using System.Reflection;

[assembly: AssemblyTitleAttribute("Topshelf")]
[assembly: AssemblyDescriptionAttribute("Topshelf is an open source project for hosting services without friction. By referencing Topshelf, your console application *becomes* a service installer with a comprehensive set of command-line options for installing, configuring, and running your application as a service.")]
[assembly: AssemblyProductAttribute("Topshelf")]
[assembly: AssemblyVersionAttribute("4.0.0.0")]
[assembly: AssemblyFileVersionAttribute("4.0.3.0")]
[assembly: AssemblyInformationalVersionAttribute("4.0.3.0 (develop/0b352d8c)")]
[assembly: AssemblyCopyrightAttribute("Copyright 2012 Chris Patterson, Dru Sellers, Travis Smith, All rights reserved.")]
namespace System {
    internal static class AssemblyVersionInformation {
        internal const System.String AssemblyTitle = "Topshelf";
        internal const System.String AssemblyDescription = "Topshelf is an open source project for hosting services without friction. By referencing Topshelf, your console application *becomes* a service installer with a comprehensive set of command-line options for installing, configuring, and running your application as a service.";
        internal const System.String AssemblyProduct = "Topshelf";
        internal const System.String AssemblyVersion = "4.0.0.0";
        internal const System.String AssemblyFileVersion = "4.0.3.0";
        internal const System.String AssemblyInformationalVersion = "4.0.3.0 (develop/0b352d8c)";
        internal const System.String AssemblyCopyright = "Copyright 2012 Chris Patterson, Dru Sellers, Travis Smith, All rights reserved.";
    }
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>BlurFilter Demo</title>
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
    <canvas id="demoCanvas" width="500" height="500"></canvas>
<script type="text/javascript" src="https://code.createjs.com/easeljs-0.8.1.min.js"></script>
<script src="/js/ch_02.js"></script>
</body>
</html>


text:
<bill session="115" type="sj" number="47" updated="2017-09-11T03:06:22Z">
  <state datetime="2017-07-20">REFERRED</state>
  <status>
    <introduced datetime="2017-07-20"/>
  </status>
  <introduced datetime="2017-07-20"/>
  <titles>
    <title type="official" as="introduced">A joint resolution providing for congressional disapproval under chapter 8 of title 5, United States Code, of the rule submitted by Bureau of Consumer Financial Protection relating to "Arbitration Agreements".</title>
    <title type="display">A joint resolution providing for congressional disapproval under chapter 8 of title 5, United States Code, of the rule submitted by Bureau of Consumer Financial Protection relating to "Arbitration Agreements".</title>
  </titles>
  <sponsor bioguide_id="C000880"/>
  <cosponsors>
    <cosponsor bioguide_id="B001261" joined="2017-07-20"/>
    <cosponsor bioguide_id="B000575" joined="2017-07-20"/>
    <cosponsor bioguide_id="B001236" joined="2017-07-24"/>
    <cosponsor bioguide_id="C001047" joined="2017-07-20"/>
    <cosponsor bioguide_id="C000567" joined="2017-07-20"/>
    <cosponsor bioguide_id="C001071" joined="2017-07-20"/>
    <cosponsor bioguide_id="C001095" joined="2017-07-20"/>
    <cosponsor bioguide_id="C001098" joined="2017-07-20"/>
    <cosponsor bioguide_id="E000285" joined="2017-07-20"/>
    <cosponsor bioguide_id="H000338" joined="2017-07-20"/>
    <cosponsor bioguide_id="H001041" joined="2017-07-20"/>
    <cosponsor bioguide_id="I000024" joined="2017-07-24"/>
    <cosponsor bioguide_id="I000055" joined="2017-07-20"/>
    <cosponsor bioguide_id="J000293" joined="2017-07-27"/>
    <cosponsor bioguide_id="L000575" joined="2017-07-20"/>
    <cosponsor bioguide_id="L000577" joined="2017-07-26"/>
    <cosponsor bioguide_id="M000934" joined="2017-07-20"/>
    <cosponsor bioguide_id="P000603" joined="2017-09-05"/>
    <cosponsor bioguide_id="P000612" joined="2017-07-20"/>
    <cosponsor bioguide_id="R000584" joined="2017-07-27"/>
    <cosponsor bioguide_id="R000307" joined="2017-07-27"/>
    <cosponsor bioguide_id="R000605" joined="2017-07-20"/>
    <cosponsor bioguide_id="R000595" joined="2017-07-20"/>
    <cosponsor bioguide_id="S001197" joined="2017-07-20"/>
    <cosponsor bioguide_id="S001184" joined="2017-07-20"/>
    <cosponsor bioguide_id="S000320" joined="2017-07-20"/>
    <cosponsor bioguide_id="S001202" joined="2017-07-20"/>
    <cosponsor bioguide_id="S001198" joined="2017-07-27"/>
    <cosponsor bioguide_id="T000476" joined="2017-07-20"/>
    <cosponsor bioguide_id="T000461" joined="2017-07-20"/>
    <cosponsor bioguide_id="W000437" joined="2017-07-20"/>
  </cosponsors>
  <actions>
    <action datetime="2017-07-20">
      <text>Introduced in Senate</text>
    </action>
    <action datetime="2017-07-20" state="REFERRED">
      <text>Read twice and referred to the Committee on Banking, Housing, and Urban Affairs.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="SSBK" name="Senate Banking, Housing, and Urban Affairs" activity="Referral"/>
  </committees>
  <relatedbills>
    <bill type="hj" session="115" relation="identical" number="111"/>
  </relatedbills>
  <subjects>
    <term name="Finance and financial sector"/>
    <term name="Administrative law and regulatory procedures"/>
    <term name="Alternative dispute resolution, mediation, arbitration"/>
    <term name="Business records"/>
    <term name="Congressional oversight"/>
    <term name="Consumer Financial Protection Bureau"/>
    <term name="Consumer credit"/>
    <term name="Financial services and investments"/>
    <term name="Government information and archives"/>
  </subjects>
  <amendments/>
  <summary date="2017-07-20T04:00:00Z" status="Introduced in Senate">This joint resolution nullifies a rule submitted by the Consumer Financial Protection Bureau (CFPB) regarding arbitration agreements.

(The rule regulates the use of arbitration agreements in contracts for specific consumer financial products and services. It prohibits the use of a predispute arbitration agreement to prevent a consumer from filing or participating in certain class action suits. The rule also requires consumer financial product and service providers to furnish the CFPB with particular information regarding arbitrations.)</summary>
  <committee-reports/>
</bill>