text:
/**
 * Module dependencies.
 */
var util = require('util')
  , url = require('url')
  , utils = require('./utils')
  , OAuth2Strategy = require('passport-oauth2')
  , Profile = require('./profile')
  , InternalOAuthError = require('passport-oauth2').InternalOAuthError
  , AuthorizationError = require('passport-oauth2').AuthorizationError;

/**
 * `Strategy` constructor.
 *
 * The GitHub authentication strategy authenticates requests by delegating to
 * GitHub using the OAuth 2.0 protocol.
 *
 * Applications must supply a `verify` callback which accepts an `accessToken`,
 * `refreshToken` and service-specific `profile`, and then calls the `done`
 * callback supplying a `user`, which should be set to `false` if the
 * credentials are not valid.  If an exception occured, `err` should be set.
 *
 * Options:
 *   - `clientID`      your GitHub application's Client ID
 *   - `clientSecret`  your GitHub application's Client Secret
 *   - `callbackURL`   URL to which GitHub will redirect the user after granting authorization
 *   - `scope`         array of permission scopes to request.  valid scopes include:
 *                     'user', 'public_repo', 'repo', 'gist', or none.
 *                     (see http://developer.github.com/v3/oauth/#scopes for more info)
 *   — `userAgent`     All API requests MUST include a valid User Agent string.
 *                     e.g: domain name of your application.
 *                     (see http://developer.github.com/v3/#user-agent-required for more info)
 *
 * Examples:
 *
 *     passport.use(new GitHubStrategy({
 *         clientID: '123-456-789',
 *         clientSecret: 'shhh-its-a-secret'
 *         callbackURL: 'https://www.example.net/auth/github/callback',
 *         userAgent: 'myapp.com'
 *       },
 *       function(accessToken, refreshToken, profile, done) {
 *         User.findOrCreate(..., function (err, user) {
 *           done(err, user);
 *         });
 *       }
 *     ));
 *
 * @param {Object} options
 * @param {Function} verify
 * @api public
 */
function Strategy(options, verify) {
  options = options || {};
  options.authorizationURL = options.authorizationURL || 'https://cad.onshape.com/oauth/authorize';
  options.tokenURL = options.tokenURL || 'https://cad.onshape.com/oauth/token';
  options.scopeSeparator = options.scopeSeparator || ',';
  options.customHeaders = options.customHeaders || {};

  if (!options.customHeaders['User-Agent']) {
    options.customHeaders['User-Agent'] = options.userAgent || 'passport-onshape';
  }

  OAuth2Strategy.call(this, options, verify);
  this.name = 'onshape';
  this._userProfileURL = options.userProfileURL || 'https://cad.onshape.com/api/users/sessioninfo';
  this._oauth2.useAuthorizationHeaderforGET(true);
}

/**
 * Inherit from `OAuth2Strategy`.
 */
util.inherits(Strategy, OAuth2Strategy);

/**
 * Authenticate request by delegating to a service provider using OAuth 2.0.
 *
 * @param {Object} req
 * @api protected
 */
Strategy.prototype.authenticate = function(req, options) {
  options = options || {};
  var self = this;

  if (req.query && req.query.error) {
    if (req.query.error == 'access_denied') {
      return this.fail({ message: req.query.error_description });
    } else {
      return this.error(new AuthorizationError(req.query.error_description, req.query.error, req.query.error_uri));
    }
  }

  var callbackURL = options.callbackURL || this._callbackURL;
  if (callbackURL) {
    var parsed = url.parse(callbackURL);
    if (!parsed.protocol) {
      // The callback URL is relative, resolve a fully qualified URL from the
      // URL of the originating request.
      callbackURL = url.resolve(utils.originalURL(req, { proxy: this._trustProxy }), callbackURL);
    }
  }

  var meta = {
    authorizationURL: this._oauth2._authorizeUrl,
    tokenURL: this._oauth2._accessTokenUrl,
    clientID: this._oauth2._clientId
  }

  if (req.query && req.query.code) {
    function loaded(err, ok, state) {
      if (err) { return self.error(err); }
      if (!ok) {
        return self.fail(state, 403);
      }

      var code = req.query.code;

      var params = self.tokenParams(options);
      params.grant_type = 'authorization_code';
      if (callbackURL) { params.redirect_uri = callbackURL; }

      self._oauth2.getOAuthAccessToken(code, params,
        function(err, accessToken, refreshToken, params) {
          if (err) { return self.error(self._createOAuthError('Failed to obtain access token', err)); }

          self._loadUserProfile(accessToken, function(err, profile) {
            if (err) { return self.error(err); }

            function verified(err, user, info) {
              if (err) { return self.error(err); }
              if (!user) { return self.fail(info); }

              info = info || {};
              if (state) { info.state = state; }
              self.success(user, info);
            }

            try {
              if (self._passReqToCallback) {
                var arity = self._verify.length;
                if (arity == 6) {
                  self._verify(req, accessToken, refreshToken, params, profile, verified);
                } else { // arity == 5
                  self._verify(req, accessToken, refreshToken, profile, verified);
                }
              } else {
                var arity = self._verify.length;
                if (arity == 5) {
                  self._verify(accessToken, refreshToken, params, profile, verified);
                } else { // arity == 4
                  self._verify(accessToken, refreshToken, profile, verified);
                }
              }
            } catch (ex) {
              return self.error(ex);
            }
          });
        }
      );
    }

    var state = req.query.state;
    try {
      var arity = this._stateStore.verify.length;
      if (arity == 4) {
        this._stateStore.verify(req, state, meta, loaded);
      } else { // arity == 3
        this._stateStore.verify(req, state, loaded);
      }
    } catch (ex) {
      return this.error(ex);
    }
  } else {
    var params = this.authorizationParams(req, options);
    params.response_type = 'code';
    if (callbackURL) { params.redirect_uri = callbackURL; }
    var scope = options.scope || this._scope;
    if (scope) {
      if (Array.isArray(scope)) { scope = scope.join(this._scopeSeparator); }
      params.scope = scope;
    }

    var state = options.state;
    if (state) {
      params.state = state;

      var parsed = url.parse(this._oauth2._authorizeUrl, true);
      utils.merge(parsed.query, params);
      parsed.query['client_id'] = this._oauth2._clientId;
      delete parsed.search;
      var location = url.format(parsed);
      this.redirect(location);
    } else {
      function stored(err, state) {
        if (err) { return self.error(err); }

        if (state) { params.state = state; }
        var parsed = url.parse(self._oauth2._authorizeUrl, true);
        utils.merge(parsed.query, params);
        parsed.query['client_id'] = self._oauth2._clientId;
        delete parsed.search;
        var location = url.format(parsed);
        self.redirect(location);
      }

      try {
        var arity = this._stateStore.store.length;
        if (arity == 3) {
          this._stateStore.store(req, meta, stored);
        } else { // arity == 2
          this._stateStore.store(req, stored);
        }
      } catch (ex) {
        return this.error(ex);
      }
    }
  }
};

/**
 * Return extra parameters to be included in the authorization request.
 *
 * Some OAuth 2.0 providers allow additional, non-standard parameters to be
 * included when requesting authorization.  Since these parameters are not
 * standardized by the OAuth 2.0 specification, OAuth 2.0-based authentication
 * strategies can overrride this function in order to populate these parameters
 * as required by the provider.
 *
 * @param {Object} req
 * @param {Object} options
 * @return {Object}
 * @api protected
 */
Strategy.prototype.authorizationParams = function(req, options) {
  return req.query.companyId ? {company_id: req.query.companyId} : {};
};

/**
 * Retrieve user profile from GitHub.
 *
 * This function constructs a normalized profile, with the following properties:
 *
 *   - `provider`         always set to `github`
 *   - `id`               the user's GitHub ID
 *   - `username`         the user's GitHub username
 *   - `displayName`      the user's full name
 *   - `profileUrl`       the URL of the profile for the user on GitHub
 *   - `emails`           the user's email addresses
 *
 * @param {String} accessToken
 * @param {Function} done
 * @api protected
 */
Strategy.prototype.userProfile = function(accessToken, done) {
  this._oauth2.get(this._userProfileURL, accessToken, function (err, body, res) {
    var json;

    if (err) {
      return done(new InternalOAuthError('Failed to fetch user profile', err));
    }

    try {
      json = JSON.parse(body);
    } catch (ex) {
      return done(new Error('Failed to parse user profile'));
    }

    var profile = Profile.parse(json);
    profile.provider  = 'onshape';
    profile._raw = body;
    profile._json = json;

    done(null, profile);
  });
};

/**
 * Expose `Strategy`.
 */
module.exports = Strategy;


text:
<?php

namespace PSX\Framework\Template\Generator;

use PSX\Data\GraphTraverser;
use PSX\Data\Visitor;
use PSX\Framework\Template\GeneratorInterface;
use PSX\Record\RecordInterface;

/**
 * Html
 *
 * @author  Christoph Kappestein <christoph.kappestein@gmail.com>
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @link    http://phpsx.org
 */
class Html implements GeneratorInterface
{
    public function generate(RecordInterface $data)
    {
        $visitor = new Visitor\HtmlWriterVisitor();
        $graph   = new GraphTraverser();
        $graph->traverse($data, $visitor);

        return $this->getTemplate($visitor->getOutput());
    }

    protected function getTemplate($html)
    {
        return <<<HTML
<!DOCTYPE>
<html>
<head>
	<style type="text/css">
	body
	{
		font-family:monospace;
	}

	dl
	{
		margin:0px;
	}

	dt
	{
		background-color:#eee;
		padding-left:8px;
		padding-top:8px;
		padding-bottom:8px;
		border-bottom:1px solid #999;
	}

	dd
	{
		margin:0px;
		margin-left:24px;
		padding-left:8px;
		padding-top:8px;
		padding-bottom:8px;
		white-space:pre-wrap;
	}

	ul
	{
		margin:0px;
		padding:0px;
		list-style-type:none;
	}

	li
	{
		border-bottom:2px solid #222;
		padding-bottom:8px;
		margin-bottom:8px;
		white-space:pre-wrap;
	}
	</style>
</head>
<body>

{$html}

</body>
</html>
HTML;
    }
}

redpajama_set_name: RedPajamaGithub


text:
var forms = require('forms'),
    fields = forms.fields;

var testField = function(field){

    exports[field + ' options'] = function(test){
        var fn1 = function(){return 'one'};

        var f = fields[field]({
            required: true,
            label: 'test label',
            validators: [fn1],
            widget: 'some widget',
            choices: {one:'option one', two:'option two'}
        });

        test.equals(f.required, true);
        test.equals(f.label, 'test label');
        test.equals(f.validators[f.validators.length-1], fn1);
        test.equals(f.widget, 'some widget');
        test.same(f.choices, {one:'option one', two:'option two'});
        test.equals(f.validate, undefined);
        test.done();
    };

    exports[field + ' bind'] = function(test){
        test.expect(7);

        var f = fields[field]({
            label: 'test label',
            validators: [
                function(form, field, callback){
                    test.ok(false, 'validators should not be called');
                }
            ]
        });
        f.parse = function(data){
            test.equals(data, 'some data');
            return 'some data parsed';
        };
        var bound = f.bind('some data');
        test.equals(bound.label, 'test label');
        test.equals(bound.value, 'some data');
        test.equals(bound.data, 'some data parsed');
        test.equals(bound.error, undefined);
        test.ok(bound.validate instanceof Function);
        test.ok(bound != f, 'bind returns a new field object');
        test.done();
    };

    exports[field + ' validate'] = function(test){
        test.expect(10);

        var f = fields[field]({label: 'test label'});
        f.validators = [
            function(form, field, callback){
                test.equals(field.data, 'some data parsed');
                test.equals(field.value, 'some data');
                callback(null);
            },
            function(form, field, callback){
                test.equals(field.data, 'some data parsed');
                test.equals(field.value, 'some data');
                callback(new Error('validation error'));
            }
        ];

        f.parse = function(data){
            test.equals(data, 'some data');
            return 'some data parsed';
        };
        f.bind('some data').validate('form', function(err, bound){
            test.equals(bound.label, 'test label');
            test.equals(bound.value, 'some data');
            test.equals(bound.data, 'some data parsed');
            test.equals(bound.error, 'Error: validation error');
            test.ok(bound != f, 'bind returns a new field object');
            test.done();
        });
    };

    exports[field + ' validate multiple errors'] = function(test){
        test.expect(1);

        var f = fields[field]();
        f.validators = [
            function(form, field, callback){
                callback('error one');
            },
            function(form, field, callback){
                test.ok(false, 'second validator should not be called');
                callback('error two');
            }
        ];

        f.parse = function(data){
            return 'some data parsed';
        };
        f.bind('some data').validate('form', function(err, bound){
            test.equals(bound.error, 'error one');
            test.done();
        });
    };

    exports[field + ' validate empty'] = function(test){
        test.expect(1);
        var f = fields[field]({
            validators: [function(form, field, callback){
                test.ok(false, 'validators should not be called');
                callback('some error');
            }]
        });
        f.parse = function(data){
            return;
        };
        f.bind().validate('form', function(err, bound){
            test.equals(bound.error, undefined);
            test.done();
        });
    };

    exports[field + ' validate required'] = function(test){
        test.expect(5);
        var f = fields[field]({required: true});
        f.validators = [];
        f.bind(undefined).validate('form', function(err, f){
            test.equals(f.value, undefined);
            test.equals(f.error, 'This field is required.');
        });
        var f2 = fields[field]({required: true});
        f2.parse = function(val){return val;};
        f2.validators = [];
        f2.bind('val').validate('form', function(err, f2){
            test.equals(f2.value, 'val');
            test.equals(f2.data, 'val');
            test.equals(f2.error, null);
        });
        setTimeout(test.done, 25);
    };

    exports[field + ' validate no validators'] = function(test){
        test.expect(4);
        var f = fields[field]();
        f.validators = [];
        f.parse = function(data){
            test.equals(data, 'some data');
            return 'some data parsed';
        };
        f.bind('some data').validate('form', function(err, f){
            test.equals(f.value, 'some data');
            test.equals(f.data, 'some data parsed');
            test.equals(f.error, null);
            test.done();
        });
    };
};

testField('string');

exports['string parse'] = function(test){
    test.equals(fields.string().parse(), '');
    test.equals(fields.string().parse(null), '');
    test.equals(fields.string().parse(0), '0');
    test.equals(fields.string().parse(''), '');
    test.equals(fields.string().parse('some string'), 'some string');
    test.done();
};

exports['string toHTML'] = function(test){
    test.expect(3);
    test.equals(
        fields.string().toHTML('fieldname'),
        '
' +
            'Fieldname' +
            '<input type="text" name="fieldname" id="id_fieldname" />' +
        '
'
    );
    var f = fields.string();
    f.widget.toHTML = function(name, field){
        test.equals(name, 'fieldname');
        test.equals(field, f);
        test.done();
    };
    f.toHTML('fieldname');
};

testField('number');

exports['number parse'] = function(test){
    test.ok(isNaN(fields.number().parse()));
    test.ok(isNaN(fields.number().parse(null)));
    test.equals(fields.number().parse(0), 0);
    test.ok(isNaN(fields.number().parse('')));
    test.equals(fields.number().parse('123'), 123);
    test.done();
};

exports['number toHTML'] = function(test){
    test.equals(
        fields.number().toHTML('fieldname'),
        '
' +
            'Fieldname' +
            '<input type="text" name="fieldname" id="id_fieldname" />' +
        '
'
    );
    test.done();
};

testField('boolean');

exports['boolean parse'] = function(test){
    test.equals(fields.boolean().parse(), false);
    test.equals(fields.boolean().parse(null), false);
    test.equals(fields.boolean().parse(0), false);
    test.equals(fields.boolean().parse(''), false);
    test.equals(fields.boolean().parse('on'), true);
    test.equals(fields.boolean().parse('true'), true);
    test.done();
};

exports['boolean toHTML'] = function(test){
    test.equals(
        fields.boolean().toHTML('fieldname'),
        '
' +
            'Fieldname' +
            '<input type="checkbox" name="fieldname" id="id_fieldname" />' +
        '
'
    );
    test.done();
};

testField('email');

exports['email parse'] = function(test){
    test.equals(
        fields.email().parse.toString(),
        fields.string().parse.toString()
    );
    test.done();
};

exports['email toHTML'] = function(test){
    test.equals(
        fields.email().toHTML.toString(),
        fields.string().toHTML.toString()
    );
    test.done();
};

exports['email validators'] = function(test){
    test.equals(
        fields.email().validators[0].toString(),
        forms.validators.email().toString()
    );
    var fn1 = function(){return 'one';};
    var fn2 = function(){return 'two';};
    var f = fields.email({validators: [fn1, fn2]});
    test.equals(
        f.validators[0].toString(),
        forms.validators.email().toString()
    );
    test.same(f.validators.slice(1), [fn1, fn2]);
    test.done();
};

testField('password');

exports['password parse'] = function(test){
    test.equals(
        fields.password().parse.toString(),
        fields.string().parse.toString()
    );
    test.done();
};

exports['password toHTML'] = function(test){
    test.equals(
        fields.password().toHTML.toString(),
        fields.string().toHTML.toString()
    );
    test.done();
};

testField('url');

exports['url parse'] = function(test){
    test.equals(
        fields.url().parse.toString(),
        fields.string().parse.toString()
    );
    test.done();
};

exports['url toHTML'] = function(test){
    test.equals(
        fields.url().toHTML.toString(),
        fields.string().toHTML.toString()
    );
    test.done();
};

exports['url validators'] = function(test){
    test.equals(
        fields.url().validators[0].toString(),
        forms.validators.url().toString()
    );
    var fn1 = function(){return 'one';};
    var fn2 = function(){return 'two';};
    var f = fields.url({validators: [fn1, fn2]});
    test.equals(
        f.validators[0].toString(),
        forms.validators.url().toString()
    );
    test.same(f.validators.slice(1), [fn1, fn2]);
    test.done();
};

testField('array');

exports['array parse'] = function(test){
    test.same(fields.array().parse(), []);
    test.same(fields.array().parse(null), [null]);
    test.same(fields.array().parse(0), [0]);
    test.same(fields.array().parse(''), ['']);
    test.same(fields.array().parse('abc'), ['abc']);
    test.same(
        fields.array().parse(['one','two','three']), ['one','two','three']
    );
    test.done();
};

exports['array toHTML'] = function(test){
    test.equals(
        fields.array().toHTML.toString(),
        fields.string().toHTML.toString()
    );
    test.done();
};


text:
package id.jsonmapper;

import java.util.Optional;

import id.jsonmapper.support.JSONObject;

/**
 * @author indroneel
 *
 */

public interface Converter {

	<T> T json2Object(Object jsonObj, Class<T> type);

	Optional<JSONObject> object2Json(Object obj);
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>São José</logradouro><bairro>Claudete</bairro><cidade>Cascavel</cidade><uf>PR</uf><cep>85807420</cep></feed>


text:
package org.apache.jackrabbit.test.api.query.qom;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.List;
import java.util.ArrayList;

import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import javax.jcr.query.Query;
import javax.jcr.query.QueryResult;
import javax.jcr.query.Row;
import javax.jcr.query.RowIterator;
import javax.jcr.query.qom.QueryObjectModel;

import org.apache.jackrabbit.test.api.query.AbstractQueryTest;

/**
 * AbstractQOMTest is a base class for test cases on the JQOM.
 */
public abstract class AbstractQOMTest extends AbstractQueryTest {

    /**
     * Binds the given value to the variable named
     * var.
     *
     * @param q     the query
     * @param var   name of variable in query
     * @param value value to bind
     * @throws IllegalArgumentException if var is not a valid
     *                                  variable in this query.
     * @throws RepositoryException      if an error occurs.
     */
    protected void bindVariableValue(Query q, String var, Value value)
            throws RepositoryException {
        q.bindValue(var, value);
    }

    protected void checkResultOrder(QueryObjectModel qom,
                                    String[] selectorNames,
                                    Node[][] nodes)
            throws RepositoryException {
        checkResultOrder(qom.execute(), selectorNames, nodes);
        checkResultOrder(qm.createQuery(qom.getStatement(), Query.JCR_SQL2).execute(),
                selectorNames, nodes);
    }

    protected void checkResultOrder(QueryResult result,
                                    String[] selectorNames,
                                    Node[][] nodes)
            throws RepositoryException {
        // collect rows
        List<String> expectedPaths = new ArrayList<String>();
        log.println("expected:");
        for (int i = 0; i < nodes.length; i++) {
            StringBuffer aggregatedPaths = new StringBuffer();
            for (int j = 0; j < nodes[i].length; j++) {
                aggregatedPaths.append(getPath(nodes[i][j]));
                aggregatedPaths.append("|");
            }
            expectedPaths.add(aggregatedPaths.toString());
            log.println(aggregatedPaths.toString());
        }

        List<String> resultPaths = new ArrayList<String>();
        log.println("result:");
        for (RowIterator it = result.getRows(); it.hasNext();) {
            Row r = it.nextRow();
            StringBuffer aggregatedPaths = new StringBuffer();
            for (int i = 0; i < selectorNames.length; i++) {
                aggregatedPaths.append(getPath(r.getNode(selectorNames[i])));
                aggregatedPaths.append("|");
            }
            resultPaths.add(aggregatedPaths.toString());
            log.println(aggregatedPaths.toString());
        }

        assertEquals("wrong result order", expectedPaths, resultPaths);
    }

    /**
     * Checks the query object model by executing it directly and matching the
     * result against the given nodes. Then the QOM is executed
     * again using {@link QueryObjectModel#getStatement()} with {@link
     * Query#JCR_SQL2}.
     *
     * @param qom   the query object model to check.
     * @param nodes the result nodes.
     * @throws RepositoryException if an error occurs while executing the
     *                             query.
     */
    protected void checkQOM(QueryObjectModel qom, Node[] nodes)
            throws RepositoryException {
        checkResult(qom.execute(), nodes);
        checkResult(qm.createQuery(qom.getStatement(), Query.JCR_SQL2).execute(), nodes);
    }

    /**
     * Checks the query object model by executing it directly and matching the
     * result against the given nodes. Then the QOM is executed
     * again using {@link QueryObjectModel#getStatement()} with
     * {@link Query#JCR_SQL2}.
     *
     * @param qom           the query object model to check.
     * @param selectorNames the selector names of the qom.
     * @param nodes         the result nodes.
     * @throws RepositoryException if an error occurs while executing the
     *                             query.
     */
    protected void checkQOM(QueryObjectModel qom,
                            String[] selectorNames,
                            Node[][] nodes) throws RepositoryException {
        checkResult(qom.execute(), selectorNames, nodes);
        checkResult(qm.createQuery(qom.getStatement(), Query.JCR_SQL2).execute(),
                selectorNames, nodes);
    }

    protected void checkResult(QueryResult result,
                               String[] selectorNames,
                               Node[][] nodes)
            throws RepositoryException {
        // collect rows
        Set<String> expectedPaths = new HashSet<String>();
        log.println("expected:");
        for (int i = 0; i < nodes.length; i++) {
            StringBuffer aggregatedPaths = new StringBuffer();
            for (int j = 0; j < nodes[i].length; j++) {
                aggregatedPaths.append(getPath(nodes[i][j]));
                aggregatedPaths.append("|");
            }
            expectedPaths.add(aggregatedPaths.toString());
            log.println(aggregatedPaths.toString());
        }

        Set<String> resultPaths = new HashSet<String>();
        log.println("result:");
        for (RowIterator it = result.getRows(); it.hasNext();) {
            Row r = it.nextRow();
            StringBuffer aggregatedPaths = new StringBuffer();
            for (int i = 0; i < selectorNames.length; i++) {
                aggregatedPaths.append(getPath(r.getNode(selectorNames[i])));
                aggregatedPaths.append("|");
            }
            resultPaths.add(aggregatedPaths.toString());
            log.println(aggregatedPaths.toString());
        }

        // check if all expected are in result
        for (Iterator<String> it = expectedPaths.iterator(); it.hasNext();) {
            String path = it.next();
            assertTrue(path + " is not part of the result set", resultPaths.contains(path));
        }
        // check result does not contain more than expected
        for (Iterator<String> it = resultPaths.iterator(); it.hasNext();) {
            String path = it.next();
            assertTrue(path + " is not expected to be part of the result set", expectedPaths.contains(path));
        }
    }

    /**
     * Returns the path of the node or an empty string if
     * node is null.
     *
     * @param node a node or null.
     * @return the path of the node or an empty string if node is
     *         null.
     * @throws RepositoryException if an error occurs while reading from the
     *                             repository.
     */
    protected static String getPath(Node node) throws RepositoryException {
        if (node != null) {
            return node.getPath();
        } else {
            return "";
        }
    }

    /**
     * Calls back the callable first with the qom and
     * then a JCR_SQL2 query created from {@link QueryObjectModel#getStatement()}.
     *
     * @param qom      a query object model.
     * @param callable the callback.
     * @throws RepositoryException if an error occurs.
     */
    protected void forQOMandSQL2(QueryObjectModel qom, Callable callable)
            throws RepositoryException {
        List<Query> queries = new ArrayList<Query>();
        queries.add(qom);
        queries.add(qm.createQuery(qom.getStatement(), Query.JCR_SQL2));
        for (Iterator<Query> it = queries.iterator(); it.hasNext();) {
            callable.call(it.next());
        }
    }

    protected interface Callable {

        public Object call(Query query) throws RepositoryException;
    }
}


text:
/*
 * reserved comment block
 * DO NOT REMOVE OR ALTER!
 */
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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.
 */
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;

import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Iterator;

import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SubjectName;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;

public class X509SubjectNameResolver extends KeyResolverSpi {

    /** {@link org.apache.commons.logging} logging facility */
    private static java.util.logging.Logger log =
        java.util.logging.Logger.getLogger(X509SubjectNameResolver.class.getName());

    /**
     * Method engineResolvePublicKey
     *
     * @param element
     * @param BaseURI
     * @param storage
     * @return null if no {@link PublicKey} could be obtained
     * @throws KeyResolverException
     */
    public PublicKey engineLookupAndResolvePublicKey(
        Element element, String baseURI, StorageResolver storage
    ) throws KeyResolverException {

        X509Certificate cert =
            this.engineLookupResolveX509Certificate(element, baseURI, storage);

        if (cert != null) {
            return cert.getPublicKey();
        }

        return null;
    }

    /**
     * Method engineResolveX509Certificate
     * @inheritDoc
     * @param element
     * @param baseURI
     * @param storage
     *
     * @throws KeyResolverException
     */
    public X509Certificate engineLookupResolveX509Certificate(
        Element element, String baseURI, StorageResolver storage
    ) throws KeyResolverException {
        if (log.isLoggable(java.util.logging.Level.FINE)) {
            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
        }
        Element[] x509childNodes = null;
        XMLX509SubjectName x509childObject[] = null;

        if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
            if (log.isLoggable(java.util.logging.Level.FINE)) {
                log.log(java.util.logging.Level.FINE, "I can't");
            }
            return null;
        }
        x509childNodes =
            XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SUBJECTNAME);

        if (!((x509childNodes != null)
            && (x509childNodes.length > 0))) {
            if (log.isLoggable(java.util.logging.Level.FINE)) {
                log.log(java.util.logging.Level.FINE, "I can't");
            }
            return null;
        }

        try {
            if (storage == null) {
                Object exArgs[] = { Constants._TAG_X509SUBJECTNAME };
                KeyResolverException ex =
                    new KeyResolverException("KeyResolver.needStorageResolver", exArgs);

                if (log.isLoggable(java.util.logging.Level.FINE)) {
                    log.log(java.util.logging.Level.FINE, "", ex);
                }

                throw ex;
            }

            x509childObject = new XMLX509SubjectName[x509childNodes.length];

            for (int i = 0; i < x509childNodes.length; i++) {
                x509childObject[i] = new XMLX509SubjectName(x509childNodes[i], baseURI);
            }

            Iterator<Certificate> storageIterator = storage.getIterator();
            while (storageIterator.hasNext()) {
                X509Certificate cert = (X509Certificate)storageIterator.next();
                XMLX509SubjectName certSN =
                    new XMLX509SubjectName(element.getOwnerDocument(), cert);

                if (log.isLoggable(java.util.logging.Level.FINE)) {
                    log.log(java.util.logging.Level.FINE, "Found Certificate SN: " + certSN.getSubjectName());
                }

                for (int i = 0; i < x509childObject.length; i++) {
                    if (log.isLoggable(java.util.logging.Level.FINE)) {
                        log.log(java.util.logging.Level.FINE, "Found Element SN:     "
                              + x509childObject[i].getSubjectName());
                    }

                    if (certSN.equals(x509childObject[i])) {
                        if (log.isLoggable(java.util.logging.Level.FINE)) {
                            log.log(java.util.logging.Level.FINE, "match !!! ");
                        }

                        return cert;
                    }
                    if (log.isLoggable(java.util.logging.Level.FINE)) {
                        log.log(java.util.logging.Level.FINE, "no match...");
                    }
                }
            }

            return null;
        } catch (XMLSecurityException ex) {
            if (log.isLoggable(java.util.logging.Level.FINE)) {
                log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
            }

            throw new KeyResolverException("generic.EmptyMessage", ex);
        }
    }

    /**
     * Method engineResolveSecretKey
     * @inheritDoc
     * @param element
     * @param baseURI
     * @param storage
     *
     */
    public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
        Element element, String baseURI, StorageResolver storage
    ) {
        return null;
    }
}


text:
Flow-typed supports a config file to help you set various project level settings.

`<PROJECT_ROOT>/flow-typed.config.json`

## env

`env` accepts an array of strings that map to environment definitions that you can you can find [here](https://github.com/flow-typed/flow-typed/tree/master/definitions/environments).

```js
{
  env: ['jsx', 'node'],
}
```

Learn more about [environment definitions](env-definitions.md)

## ignore

When you have a dependencies you don't want updated or swapped out during the `install` command you can add this property which takes an array of strings referencing either package scopes or package names explicitly to ignore.

```js
{
  ignore: ['@babel', '@custom/', 'eslint', 'eslint-plugin-ft-flow']
}
```


text:
package com.youkaicountry.youml.module.layer;
import java.lang.Math;

import com.youkaicountry.youml.module.Module;
import com.youkaicountry.youml.module.layer.LinearLayer.LayerOptions;
import com.youkaicountry.youml.parameter.NullVector;

public class SigmoidLayer extends Layer
{
    public SigmoidLayer(String name, int neurons)
    {
        super(name);
        this.moduleInit(neurons, neurons, new NullVector(this));
        return;
    }

    public SigmoidLayer(LayerOptions lo)
    {
        this(lo.name, lo.neurons);
        return;
    }

    //For the loader class
    public static class LayerOptions
    {
        public String name;
        public int neurons;
    }

    @Override
    public void forwardProp(double[] input, double[] output)
    {
        for (int i = 0; i < this.input_dim; i++)
        {
            output[i+this.output_offset] = 1.0/(1.0+Math.exp(-input[i+this.input_offset]));
        }
    }

    @Override
    public void backProp(double[] outerr, double[] inerr, double[] output, double[] input)
    {
        double val;
        for (int i = 0; i < this.input_dim; i++)
        {
            val = output[i+this.output_offset];
            inerr[i+this.inerr_offset] = val * (1.0 - val) * outerr[i+this.outerr_offset];
        }
        return;
    }
}


text:
/*
 * lcdHAL.h
 *
 *  Created on: 18.12.2012
 *      Author: Andrey
 */

#ifndef GUIPRIMITIVES_H_
#define GUIPRIMITIVES_H_

#include "gui.h"

// GPIO config
// LCD reset

//*********************************************************************************
// global extern

typedef struct
{
	int16_t X;
	int16_t Y;
} Point, * pPoint;

#define ASSEMBLE_RGB(R ,G, B)    ((((R)& 0xFC) << 8) | (((G) & 0xFC) << 2) | (((B) & 0xF0) >> 4))
#define MAX_POLY_CORNERS   200

typedef struct
{
	unsigned clRed		: 6;
	unsigned clGreen	: 6;
	unsigned clBlue		: 4;
} RGB16;

typedef struct
{
	unsigned clRed		: 6;
	unsigned clGreen	: 6;
	unsigned clBlue		: 6;
} RGB32;

//*****************************************************************************
// PROTOTIPES

// high level primitives

//
//extern void LCD_ClearLine(uint16_t Line);

//extern void LCD_SetCursor(uint16_t Xpos, uint16_t Ypos);
extern void LCD_SetDisplayWindow(uint16_t Xpos, uint16_t Ypos, uint16_t Height, uint16_t Width);
extern void LCD_WindowModeDisable(void);
extern void LCD_ASCII(V_FONT * vFont);

//**************************************************************************
extern void LCD_DrawTransparentChar(uint16_t Xpos, uint16_t Ypos, uint16_t codeChar);
extern void LCD_Clear(uint16_t Color);
extern void LCD_DrawString(char * text, uint16_t len, uint16_t Xpos, uint16_t Ypos);
extern void LCD_DrawLine(uint16_t Xpos, uint16_t Ypos, uint16_t Length, uint8_t Direction);
extern void LCD_DrawRect(uint16_t Xpos, uint16_t Ypos, uint8_t Height, uint16_t Width);
extern void LCD_DrawCircle(uint16_t Xpos, uint16_t Ypos, uint16_t Radius);
extern void LCD_DrawFullCircle(uint16_t Xpos, uint16_t Ypos, uint16_t Radius);
extern void LCD_DrawQuadRound(uint16_t Xpos, uint16_t Ypos, uint16_t Radius, uint16_t Quadrant);
extern void LCD_DrawRoundedRect(uint16_t Xpos, uint16_t Ypos, uint16_t Width, uint16_t Height, uint16_t LineWidth);
extern void LCD_DrawUniLine(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2);
extern void LCD_DrawFullRect(uint16_t Xpos, uint16_t Ypos, uint16_t Width, uint16_t Height);
extern void LCD_PolyLine(pPoint Points, uint16_t PointCount);
extern void LCD_PolyLineRelative(pPoint Points, uint16_t PointCount);
extern void LCD_ClosedPolyLine(pPoint Points, uint16_t PointCount);
extern void LCD_ClosedPolyLineRelative(pPoint Points, uint16_t PointCount);
extern void LCD_FillPolyLine(pPoint Points, uint16_t PointCount);

//**************************************************************************

#endif /* LCDHAL_H_ */


text:
module.exports = {
  command(...args) {
    this.execute(function(selector, property, value) {
      var element = document.querySelector(selector);
      element[property] = value;
    }, [ ...args ]);
  }
}


text:
package org.onosproject.ovsdb.controller;

/**
 * Representation for an entity that carries important information for a listener.
 */
public interface EventSubject {
}


text:
Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # In the development environment your application's code is reloaded on
  # every request. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports and disable caching.
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  # ActionMailer Config
  config.action_mailer.raise_delivery_errors = true
  # Change mail delvery to either :smtp, :sendmail, :file, :test
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address: "smtp.gmail.com",
    port: 587,
    authentication: "plain",
    enable_starttls_auto: true,
    user_name: Rails.application.secrets.gmail_un,
    password: Rails.application.secrets.gmail_pw
  }
  config.action_mailer.default_url_options = { :host => 'jrmyward.dev' }
  config.action_mailer.default :charset => "utf-8"

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise an error on page load if there are pending migrations.
  config.active_record.migration_error = :page_load

  # Debug mode disables concatenation and preprocessing of assets.
  # This option may cause significant delays in view rendering with a large
  # number of complex assets.
  config.assets.debug = true

  # Asset digests allow you to set far-future HTTP expiration dates on all assets,
  # yet still be able to expire them through the digest params.
  config.assets.digest = true

  # Adds additional error checking when serving assets at runtime.
  # Checks for improperly declared sprockets dependencies.
  # Raises helpful error messages.
  config.assets.raise_runtime_errors = true

  # Raises error for missing translations
  # config.action_view.raise_on_missing_translations = true
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Runtime.Remoting.Messaging;

namespace OSky.Core.Context
{
    /// <summary>
    /// 应用程序数据管理 基于[CallContext]上下文 支持多线程之间数据交换,随线程一起自动销毁
    /// </summary>
    public class ApplicationContext : Dictionary<string, object>, ILogicalThreadAffinative
    {
        public const string ContextKey = "OSky.ApplicationContexts.ApplicationContext";
        public const string OperatorKey = "OSky.ApplicationContexts.ApplicationContext.Operator";

        /// <summary>
        /// 获取或设置 当前会话上下文
        /// </summary>
        public static ApplicationContext Current
        {
            get
            {
                if (null == CallContext.GetData(ContextKey))
                {
                    CallContext.SetData(ContextKey, new ApplicationContext());
                }
                return CallContext.GetData(ContextKey) as ApplicationContext;
            }
            //set
            //{
            //    if (value == null)
            //    {
            //        CallContext.FreeNamedDataSlot(ContextKey);
            //        return;
            //    }
            //    CallContext.SetData(ContextKey, value);
            //}
        }

        /// <summary>
        /// 获取 当前操作者信息类
        /// </summary>
        public Operator Operator
        {
            get
            {
                if (!ContainsKey(OperatorKey))
                {
                    this[OperatorKey] = new Operator();
                }
                return this[OperatorKey] as Operator;
            }
            set
            {
                this[OperatorKey] = value;
            }
        }

    }
}


text:
"use strict";
var QueryTreeNode_1 = require("../noSql/QueryTreeNode");
var MappedEntityArray_1 = require("../../core/MappedEntityArray");
var LastObjectTracker_1 = require("./LastObjectTracker");
var QueryBridgeConfiguration = (function () {
    function QueryBridgeConfiguration() {
        // This is for conflicts on OneToMany references
        this.failOnConflicts = true;
    }
    return QueryBridgeConfiguration;
}());
exports.QueryBridgeConfiguration = QueryBridgeConfiguration;
/**
 a) Reconstruct the Many-To-One relations by Id
 for this we need
 1) a map of all entities [by Type]:[by id]:Entity
 2) a map of all stubs Many-To-One stubs, [by Type]:[by id]: { propertyName, parentObject }
 Then it's a simple operation of mapping all available entities to all stubs
 b) Reconstruct the One-To-Many relations by Tree
 for this we need
 1) the entity map from 1a)
 2) a similar map of all One-To-Many stubs, [by Type]:[by id]: { propertyName, parentObject,
manyEntitySet }
 where manyEntitySet is a set of all entities in a given OneToMany collection, by their id
 Then we need to navigate all entities in the entity map, and
 - for every found Many-To-One reference in each entity
 Lookup the related One-To-Many stub
 If the stub is found, add this entity to the manyEntitySet
 - at the end we need to go though all the One-To-Many stubs and create arrays ouf of the sets
 */
var QueryBridge = (function () {
    function QueryBridge(performBridging, mapEntityArrays, config, qEntity, qEntityMap) {
        this.performBridging = performBridging;
        this.mapEntityArrays = mapEntityArrays;
        this.config = config;
        this.qEntity = qEntity;
        this.qEntityMap = qEntityMap;
        // Keys can only be strings or numbers | TODO: change to JS Maps, if needed
        this.entityMap = {};
        this.otmObjectReference = new OtmObjectReference();
        this.lastObjectTracker = new LastObjectTracker_1.LastObjectTracker();
        // For MtO mapping
        // Map of all objects that have a given MtO reference
        this.mtoStubReferenceMap = {};
        // One-To-Many temp stubs (before entityIds are available
        this.otmStubBuffer = [];
        this.mtoStubBuffer = [];
    }
    QueryBridge.prototype.addEntity = function (entityAlias, resultObject) {
        if (!this.performBridging) {
            this.lastObjectTracker.addEntity(entityAlias, resultObject);
        }
    };
    QueryBridge.prototype.addProperty = function (entityAlias, resultObject, dataType, propertyName) {
        if (!this.performBridging) {
            this.lastObjectTracker.addProperty(entityAlias, resultObject, dataType, propertyName);
        }
    };
    QueryBridge.prototype.bufferManyToOneStub = function (entityAlias, qEntity, entityMetadata, resultObject, propertyName, relationQEntity, relationEntityMetadata, relatedEntityId) {
        if (!this.performBridging) {
            this.lastObjectTracker.addManyToOneReference(entityAlias, resultObject, propertyName, relationEntityMetadata.idProperty);
            return;
        }
        this.bufferManyToOne(resultObject, propertyName, relationQEntity, relationEntityMetadata, relatedEntityId);
    };
    QueryBridge.prototype.bufferManyToOneObject = function (entityAlias, qEntity, entityMetadata, resultObject, propertyName, relationQEntity, relationEntityMetadata, relatedEntityId) {
        if (!this.performBridging) {
            this.lastObjectTracker.addManyToOneObject(entityAlias, resultObject, propertyName);
            return;
        }
        this.bufferManyToOne(resultObject, propertyName, relationQEntity, relationEntityMetadata, relatedEntityId);
    };
    QueryBridge.prototype.bufferManyToOne = function (resultObject, propertyName, relationQEntity, relationEntityMetadata, relatedEntityId) {
        var otmEntityField;
        for (var otmRelationProperty in relationQEntity.__entityRelationMap__) {
            var otmRelation = relationQEntity.__entityRelationMap__[otmRelationProperty];
            if (otmRelation.relationType === QueryTreeNode_1.RelationType.ONE_TO_MANY) {
                var otmElements = relationEntityMetadata.oneToManyMap[otmRelationProperty];
                if (otmElements.mappedBy === propertyName) {
                    otmEntityField = otmRelationProperty;
                    break;
                }
            }
        }
        this.mtoStubBuffer.push({
            otmEntityId: relatedEntityId,
            otmEntityIdField: relationEntityMetadata.idProperty,
            otmEntityName: relationQEntity.__entityName__,
            otmEntityField: otmEntityField,
            mtoRelationField: propertyName,
            mtoParentObject: resultObject
        });
    };
    QueryBridge.prototype.bufferBlankManyToOne = function (entityAlias, qEntity, entityMetadata, resultObject, propertyName, relationQEntity, relationEntityMetadata) {
        if (!this.performBridging) {
            this.lastObjectTracker.addManyToOneReference(entityAlias, resultObject, propertyName, relationEntityMetadata.idProperty);
        }
    };
    QueryBridge.prototype.bufferOneToManyStub = function (resultObject, otmEntityName, propertyName, relationEntityMetadata, childResultObject) {
        if (!this.performBridging) {
            return;
        }
        this.bufferOneToMany(resultObject, otmEntityName);
    };
    QueryBridge.prototype.bufferOneToManyCollection = function (entityAlias, resultObject, otmEntityName, propertyName, relationEntityMetadata, childResultObject) {
        if (!this.performBridging) {
            this.lastObjectTracker.addOneToManyCollection(entityAlias, resultObject, propertyName);
            return [childResultObject];
        }
        this.bufferOneToMany(resultObject, otmEntityName);
        var childResultsArray = new MappedEntityArray_1.MappedEntityArray(relationEntityMetadata.idProperty);
        childResultsArray.put(childResultObject);
        return childResultsArray;
    };
    QueryBridge.prototype.bufferBlankOneToMany = function (entityAlias, resultObject, otmEntityName, propertyName, relationEntityMetadata, childResultObject) {
        if (!this.performBridging) {
            this.lastObjectTracker.addOneToManyCollection(entityAlias, resultObject, propertyName);
            return [];
        }
        return new MappedEntityArray_1.MappedEntityArray(relationEntityMetadata.idProperty);
    };
    QueryBridge.prototype.bufferOneToMany = function (resultObject, otmEntityName) {
        this.otmStubBuffer.push({
            otmEntityName: otmEntityName,
            otmObject: resultObject
        });
    };
    QueryBridge.prototype.flushEntity = function (entityAlias, qEntity, entityMetadata, selectClauseFragment, entityPropertyTypeMap, entityRelationMap, entityId, resultObject) {
        if (!this.performBridging) {
            return this.lastObjectTracker.mergeEntity(entityAlias, resultObject);
        }
        if (!entityId) {
            throw "No Id provided for entity of type '" + qEntity.__entityName__ + "'";
        }
        var currentEntity = this.getEntityToFlush(qEntity, entityMetadata, selectClauseFragment, entityPropertyTypeMap, entityRelationMap, entityId, resultObject);
        this.flushOneToManyStubBuffer(qEntity, entityMetadata, entityId);
        return currentEntity;
    };
    QueryBridge.prototype.getEntityToFlush = function (qEntity, entityMetadata, selectClauseFragment, entityPropertyTypeMap, entityRelationMap, entityId, resultObject) {
        var entityName = qEntity.__entityName__;
        if (!entityId) {
            throw "Entity ID not specified for entity '" + entityName + "'";
        }
        var entityMapForType = this.entityMap[entityName];
        if (!entityMapForType) {
            entityMapForType = {};
            this.entityMap[entityName] = entityMapForType;
        }
        var existingEntity = entityMapForType[entityId];
        var currentEntity = this.mergeEntities(existingEntity, resultObject, qEntity, selectClauseFragment, entityPropertyTypeMap, entityRelationMap);
        entityMapForType[entityId] = currentEntity;
        return currentEntity;
    };
    // Must merge the one-to-many relationships returned as part of the result tree
    QueryBridge.prototype.mergeEntities = function (source, target, qEntity, selectClauseFragment, entityPropertyTypeMap, entityRelationMap) {
        var _this = this;
        if (!source || target === source) {
            return target;
        }
        var entityMetadata = qEntity.__entityConstructor__;
        var entityName = qEntity.__entityName__;
        var id = target[entityMetadata.idProperty];
        var _loop_1 = function(propertyName) {
            if (selectClauseFragment[propertyName] === undefined) {
                return "continue";
            }
            // Merge properties (conflicts detected at query parsing time):
            if (entityPropertyTypeMap[propertyName]) {
                // If source property doesn't exist
                if (!source[propertyName] && source[propertyName] != false && source[propertyName] != '' && source[propertyName] != 0) {
                    // set the source property to value of target
                    source[propertyName] = target[propertyName];
                }
            }
            else if (entityRelationMap[propertyName]) {
                var childSelectClauseFragment = selectClauseFragment[propertyName];
                // For stubs (conflicts detected at query parsing time)
                if (childSelectClauseFragment == null) {
                    // For Many-to-One stubs, assume they are are the same and don't detect conflicts, just merge
                    source[propertyName] = target[propertyName];
                }
                else {
                    var childEntityName = entityRelationMap[propertyName].entityName;
                    var entityMetadata_1 = this_1.qEntityMap[childEntityName].__entityConstructor__;
                    var childIdProperty_1 = entityMetadata_1.idProperty;
                    // Many-to-One (conflicts detected at query parsing time)
                    if (entityMetadata_1.manyToOneMap[propertyName]) {
                        // If source is missing this mapping and target has it
                        if (source[propertyName] === undefined && target[propertyName] !== undefined) {
                            // set the source property to value of target
                            source[propertyName] = target[propertyName];
                        }
                    }
                    else {
                        var sourceArray_1 = source[propertyName];
                        var targetArray = target[propertyName];
                        // Because parseQueryResult is depth-first, all child objects have already been processed
                        // TODO: this will probably fail, since the merged in array should always have only one entity in it,
                        // because it is created for a single result set row.
                        if (this_1.config.failOnConflicts) {
                            if ((!sourceArray_1 && targetArray)
                                || (!targetArray && sourceArray_1)
                                || sourceArray_1.length != targetArray.length) {
                                throw "One-to-Many child arrays don't match for '" + entityName + "." + propertyName + "', @Id(" + entityMetadata_1.idProperty + ") = " + id;
                            }
                        }
                        var sourceSet_1 = {};
                        if (sourceArray_1) {
                            sourceArray_1.forEach(function (sourceChild) {
                                sourceSet_1[sourceChild[childIdProperty_1]] = sourceChild;
                            });
                        }
                        else {
                            sourceArray_1 = [];
                            source[propertyName] = sourceArray_1;
                        }
                        if (targetArray) {
                            targetArray.forEach(function (targetChild) {
                                var childId = targetChild[childIdProperty_1];
                                if (_this.config.failOnConflicts && !sourceSet_1[childId]) {
                                    throw "One-to-Many child arrays don't match for '" + entityName + "." + propertyName + "', @Id(" + entityMetadata_1.idProperty + ") = " + id;
                                }
                                // If target child array has a value that source doesn't
                                if (!sourceSet_1[childId]) {
                                    // add it to source (preserve order)
                                    sourceArray_1.push(targetChild);
                                }
                            });
                        }
                    }
                }
            }
        };
        var this_1 = this;
        for (var propertyName in selectClauseFragment) {
            var state_1 = _loop_1(propertyName);
            if (state_1 === "continue") continue;
        }
        return source;
    };
    QueryBridge.prototype.flushOneToManyStubBuffer = function (qEntity, entityMetadata, entityId) {
        var _this = this;
        var otmStubBuffer = this.otmStubBuffer;
        this.otmStubBuffer = [];
        otmStubBuffer.forEach(function (otmStub) {
            _this.otmObjectReference.addOtmReference(otmStub, entityId);
        });
        var mtoStubBuffer = this.mtoStubBuffer;
        this.mtoStubBuffer = [];
        mtoStubBuffer.forEach(function (mtoStub) {
            _this.otmObjectReference.addMtoReference(mtoStub, entityId);
        });
    };
    QueryBridge.prototype.flushRow = function () {
        if (!this.performBridging) {
            this.lastObjectTracker.flushRow();
        }
    };
    QueryBridge.prototype.bridge = function (parsedResults, selectClauseFragment) {
        if (!this.performBridging) {
            return parsedResults;
        }
        this.otmObjectReference.populateOtms(this.entityMap, this.mapEntityArrays);
        var entityMetadata = this.qEntity.__entityConstructor__;
        var resultMEA = new MappedEntityArray_1.MappedEntityArray(entityMetadata.idProperty);
        resultMEA.putAll(parsedResults);
        if (this.mapEntityArrays) {
            return resultMEA;
        }
        return resultMEA.toArray();
    };
    return QueryBridge;
}());
exports.QueryBridge = QueryBridge;
//# sourceMappingURL=QueryBridge.js.map


text:
package org.apache.olingo.commons.api.edm.geo;

import java.util.List;

import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;

public class MultiPoint extends ComposedGeospatial<Point> {

  private static final long serialVersionUID = 4951011255142116129L;

  public MultiPoint(final Dimension dimension, final SRID srid, final List<Point> points) {
    super(dimension, Type.MULTIPOINT, srid, points);
  }

  @Override
  public EdmPrimitiveTypeKind getEdmPrimitiveTypeKind() {
    return dimension == Dimension.GEOGRAPHY
        ? EdmPrimitiveTypeKind.GeographyMultiPoint
            : EdmPrimitiveTypeKind.GeometryMultiPoint;
  }

}


text:
<?php

namespace AVBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use AVBundle\Entity\RespuestaReto;
use AVBundle\Form\RespuestaRetoType;

/**
 * RespuestaReto controller.
 *
 */
class RespuestaRetoController extends Controller
{

    /**
     * Lists all RespuestaReto entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('AVBundle:RespuestaReto')->findAll();

        return $this->render('AVBundle:RespuestaReto:index.html.twig', array(
            'entities' => $entities,
        ));
    }
    private function obtenerRespuestasReto($respuestaReto){

    	$respuestaField= $respuestaReto->getRespuestaRetado();
    	//Se convierte a un array asociativo php
    	$respuestasRetador=  json_decode( $respuestaField, true );

    	$retoObj= $respuestaReto->getIdReto();

    	$preguntasReto= $retoObj->getPreguntas();
    	$PregsopcionesCorrectas=array();
    	foreach ($preguntasReto as $pregunta) {

             $respPregunta=   json_decode( $pregunta->getRespuestaReal(),true );

             $PregsopcionesCorrectas[]= array(
             		"idpreg"=>$pregunta->getId(),
             		"OpCorrecta"=>$respPregunta["opcionCorrecta"],
             );

        }
        $total;
        $cantCorrectas=0;
        $cantIncorrectas=0;
        $RespuestasPregs=array();
        for ($i=0; $i < sizeof( $PregsopcionesCorrectas )  ; $i++) {

        	foreach ($respuestasRetador as $idpreg => $resp) {
    			if($idpreg== $PregsopcionesCorrectas[$i]["idpreg"] ){
    					$respPregunta=null;
    					if($resp== $PregsopcionesCorrectas[$i]["OpCorrecta"]){
    							$cantCorrectas++;
    							$respPregunta= array(
		    						"idPreg"=> $idpreg,
		    						"respuesta"=> "Correcta",
		    					);
    					}else{
    							$cantIncorrectas++;
    							$respPregunta= array(
		    						"idPreg"=> $idpreg,
		    						"respuesta"=> "Incorrecta",
		    					);
    					}
    					$RespuestasPregs[]= $respPregunta;

    			}

    		}

        }
        $total=array(
    		"respuestasAlasPregs"=>$RespuestasPregs,
    		"cantCorrectas"=>$cantCorrectas,
    		"cantIncorrectas"=>$cantIncorrectas,
    	);

    	//echo json_encode($total);
    	return $total;
    }
    private function registrarPuntosReto($respuestas){
    	//echo json_encode($respuestas);

    	//cuantos puntos vale un reto?
    	$puntosPorReto= 5;

    	$cantCorrectas= $respuestas["cantCorrectas"];
    	$cantIncorrectas= $respuestas["cantIncorrectas"];
    	$cantPregs= $cantCorrectas+ $cantIncorrectas;

   		//falta ver criterio de puntos...... :S

    }
    /**
     * Creates a new RespuestaReto entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity = new RespuestaReto();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        //verificado respuesta del retador;

	    $respuestas= $this->obtenerRespuestasReto($entity);

	    $puntos= $this->registrarPuntosReto($respuestas);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

              return  $this->redirect($this->getRequest()->headers->get('referer'));
        }

          return  $this->redirect($this->getRequest()->headers->get('referer'));
    }

    /**
     * Creates a form to create a RespuestaReto entity.
     *
     * @param RespuestaReto $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(RespuestaReto $entity)
    {
        $form = $this->createForm(new RespuestaRetoType(), $entity, array(
            'action' => $this->generateUrl('respuestareto_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new RespuestaReto entity.
     *
     */
    public function newAction()
    {
        $entity = new RespuestaReto();
        $form   = $this->createCreateForm($entity);

        return $this->render('AVBundle:RespuestaReto:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a RespuestaReto entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AVBundle:RespuestaReto')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find RespuestaReto entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('AVBundle:RespuestaReto:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing RespuestaReto entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AVBundle:RespuestaReto')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find RespuestaReto entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('AVBundle:RespuestaReto:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
    * Creates a form to edit a RespuestaReto entity.
    *
    * @param RespuestaReto $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(RespuestaReto $entity)
    {
        $form = $this->createForm(new RespuestaRetoType(), $entity, array(
            'action' => $this->generateUrl('respuestareto_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing RespuestaReto entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AVBundle:RespuestaReto')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find RespuestaReto entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('respuestareto_edit', array('id' => $id)));
        }

        return $this->render('AVBundle:RespuestaReto:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
    /**
     * Deletes a RespuestaReto entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('AVBundle:RespuestaReto')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find RespuestaReto entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('respuestareto'));
    }

    /**
     * Creates a form to delete a RespuestaReto entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('respuestareto_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: AlmogBaku
 * Date: 05/12/2015
 * Time: 4:03 PM
 */

namespace AlmogBaku\SharedSecretBundle\DependencyInjection\Security\Factory;

use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\HttpBasicFactory;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\DefinitionDecorator;

class SharedSecretFactory extends HttpBasicFactory
{
    /**
     * {@inheritdoc}
     */
    public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint)
    {
        $providerId = 'security.authentication.provider.shared_secret.'.$id;
        $container->setDefinition($providerId, new DefinitionDecorator('almogbaku.shared_secret.authentication.provider'));

        $listenerId = 'security.authentication.listener.shared_secret.'.$id;
        $container->setDefinition($listenerId, new DefinitionDecorator('almogbaku.shared_secret.authentication.listener'));

        $entryPointId = $this->createEntryPoint($container, $id, $config, $defaultEntryPoint);

        return array($providerId, $listenerId, $entryPointId);
    }

    /**
     * Define the key you need to put in your `security.yml` firewall
     */
    public function getKey()
    {
        return 'shared_secret';
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: okonek
 * Date: 3/14/17
 * Time: 7:42 PM
 */

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use AppBundle\Utils\Slugifier;

/**
 * @ORM\Entity
 * @ORM\Table(name="category")
 * @UniqueEntity(fields={
 *	"name",
 *	"slug"
 * })
 * @ORM\HasLifecycleCallbacks()
 */
class Category
{

    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\OneToMany(targetEntity="Post", mappedBy="category", cascade={"persist"})
     */
    private $posts;

    /**
     * @ORM\Column(name="name", length=32, unique=true)
     */
	private $name;

	/**
	 * @ORM\Column(name="slug", length=32, unique=true)
	 */
	private $slug;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->posts = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Category
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Add post
     *
     * @param \AppBundle\Entity\Post $post
     *
     * @return Category
     */
    public function addPost(\AppBundle\Entity\Post $post)
    {
        $this->posts[] = $post;

        return $this;
    }

    /**
     * Remove post
     *
     * @param \AppBundle\Entity\Post $post
     */
    public function removePost(\AppBundle\Entity\Post $post)
    {
        $this->posts->removeElement($post);
    }

    /**
     * Get posts
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getPosts()
    {
        return $this->posts;
	}

	/**
     * Get slug
     *
     * @return string
     */
    public function getSlug()
    {
        return $this->slug;
    }

	/**
     * @ORM\PrePersist
     */
    public function setSlug(){
        $slugifier = new Slugifier();
        $this->slug = $slugifier->slugify($this->name);
    }

}


text:
/*
 * Copyright (c) 2007-2012 Concurrent, Inc. All Rights Reserved.
 *
 * Project and contact information: http://www.cascading.org/
 *
 * This file is part of the Cascading project.
 *
 * 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.
 */

package io.datalayer.cascading.p5;

import java.util.Properties;

import cascading.flow.Flow;
import cascading.flow.FlowDef;
import cascading.flow.hadoop.HadoopFlowConnector;
import cascading.operation.Insert;
import cascading.operation.aggregator.Count;
import cascading.operation.expression.ExpressionFunction;
import cascading.operation.regex.RegexFilter;
import cascading.operation.regex.RegexSplitGenerator;
import cascading.pipe.CoGroup;
import cascading.pipe.Each;
import cascading.pipe.Every;
import cascading.pipe.GroupBy;
import cascading.pipe.HashJoin;
import cascading.pipe.Pipe;
import cascading.pipe.assembly.Rename;
import cascading.pipe.assembly.Retain;
import cascading.pipe.assembly.SumBy;
import cascading.pipe.assembly.Unique;
import cascading.pipe.joiner.LeftJoin;
import cascading.property.AppProps;
import cascading.scheme.hadoop.TextDelimited;
import cascading.tap.Tap;
import cascading.tap.hadoop.Hfs;
import cascading.tuple.Fields;

public class Main {
    public static void main(String... args) {
        String docPath = args[0];
        String wcPath = args[1];
        String stopPath = args[2];
        String tfidfPath = args[3];

        Properties properties = new Properties();
        AppProps.setApplicationJarClass(properties, Main.class);
        HadoopFlowConnector flowConnector = new HadoopFlowConnector(properties);

        // create source and sink taps
        Tap docTap = new Hfs(new TextDelimited(true, "\t"), docPath);
        Tap wcTap = new Hfs(new TextDelimited(true, "\t"), wcPath);

        Fields stop = new Fields("stop");
        Tap stopTap = new Hfs(new TextDelimited(stop, true, "\t"), stopPath);
        Tap tfidfTap = new Hfs(new TextDelimited(true, "\t"), tfidfPath);

        // specify a regex operation to split the "document" text lines into a
        // token stream
        Fields token = new Fields("token");
        Fields text = new Fields("text");
        RegexSplitGenerator splitter = new RegexSplitGenerator(token, "[ \\[\\]\\(\\),.]");
        Fields fieldSelector = new Fields("doc_id", "token");
        Pipe docPipe = new Each("token", text, splitter, fieldSelector);

        // define "ScrubFunction" to clean up the token stream
        Fields scrubArguments = new Fields("doc_id", "token");
        docPipe = new Each(docPipe, scrubArguments, new ScrubFunction(scrubArguments), Fields.RESULTS);

        // perform a left join to remove stop words, discarding the rows
        // which joined with stop words, i.e., were non-null after left join
        Pipe stopPipe = new Pipe("stop");
        Pipe tokenPipe = new HashJoin(docPipe, token, stopPipe, stop, new LeftJoin());
        tokenPipe = new Each(tokenPipe, stop, new RegexFilter("^$"));
        tokenPipe = new Retain(tokenPipe, fieldSelector);

        // one branch of the flow tallies the token counts for term frequency
        // (TF)
        Pipe tfPipe = new Pipe("TF", tokenPipe);
        tfPipe = new GroupBy(tfPipe, new Fields("doc_id", "token"));

        Fields tf_count = new Fields("tf_count");
        tfPipe = new Every(tfPipe, Fields.ALL, new Count(tf_count), Fields.ALL);
        Fields tf_token = new Fields("tf_token");
        tfPipe = new Rename(tfPipe, token, tf_token);

        // one branch counts the number of documents (D)
        Fields doc_id = new Fields("doc_id");
        Fields tally = new Fields("tally");
        Fields rhs_join = new Fields("rhs_join");
        Fields n_docs = new Fields("n_docs");
        Pipe dPipe = new Unique("D", tokenPipe, doc_id);
        dPipe = new Each(dPipe, new Insert(tally, 1), Fields.ALL);
        dPipe = new Each(dPipe, new Insert(rhs_join, 1), Fields.ALL);
        dPipe = new SumBy(dPipe, rhs_join, tally, n_docs, long.class);

        // one branch tallies the token counts for document frequency (DF)
        Pipe dfPipe = new Unique("DF", tokenPipe, Fields.ALL);
        dfPipe = new GroupBy(dfPipe, token);

        Fields df_count = new Fields("df_count");
        Fields df_token = new Fields("df_token");
        Fields lhs_join = new Fields("lhs_join");
        dfPipe = new Every(dfPipe, Fields.ALL, new Count(df_count), Fields.ALL);
        dfPipe = new Rename(dfPipe, token, df_token);
        dfPipe = new Each(dfPipe, new Insert(lhs_join, 1), Fields.ALL);

        // join to bring together all the components for calculating TF-IDF
        // the D side of the join is smaller, so it goes on the RHS
        Pipe idfPipe = new HashJoin(dfPipe, lhs_join, dPipe, rhs_join);

        // the IDF side of the join is smaller, so it goes on the RHS
        Pipe tfidfPipe = new CoGroup(tfPipe, tf_token, idfPipe, df_token);

        // calculate the TF-IDF weights, per token, per document
        Fields tfidf = new Fields("tfidf");
        String expression = "(double) tf_count * Math.log( (double) n_docs / ( 1.0 + df_count ) )";
        ExpressionFunction tfidfExpression = new ExpressionFunction(tfidf, expression, Double.class);
        Fields tfidfArguments = new Fields("tf_count", "df_count", "n_docs");
        tfidfPipe = new Each(tfidfPipe, tfidfArguments, tfidfExpression, Fields.ALL);

        fieldSelector = new Fields("tf_token", "doc_id", "tfidf");
        tfidfPipe = new Retain(tfidfPipe, fieldSelector);
        tfidfPipe = new Rename(tfidfPipe, tf_token, token);

        // keep the word counts, which are useful for QA
        Pipe wcPipe = new Pipe("wc", tfPipe);
        wcPipe = new Retain(wcPipe, tf_token);
        wcPipe = new GroupBy(wcPipe, tf_token);
        wcPipe = new Every(wcPipe, Fields.ALL, new Count(), Fields.ALL);

        Fields count = new Fields("count");
        wcPipe = new GroupBy(wcPipe, count, count);

        // connect the taps, pipes, etc., into a flow
        FlowDef flowDef = FlowDef.flowDef().setName("tfidf").addSource(docPipe, docTap).addSource(stopPipe, stopTap)
                .addTailSink(tfidfPipe, tfidfTap).addTailSink(wcPipe, wcTap);

        // write a DOT file and run the flow
        Flow tfidfFlow = flowConnector.connect(flowDef);
        tfidfFlow.writeDOT("dot/tfidf.dot");
        tfidfFlow.complete();
    }
}


text:
/*
 * 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.
 */

package responses

import (
	"bytes"
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
)

type AcsResponse interface {
	IsSuccess() bool
	GetHttpStatus() int
	GetHttpHeaders() map[string][]string
	GetHttpContentString() string
	GetHttpContentBytes() []byte
	GetOriginHttpResponse() *http.Response
	parseFromHttpResponse(httpResponse *http.Response) error
}

// Unmarshal object from http response body to target Response
func Unmarshal(response AcsResponse, httpResponse *http.Response, format string) (err error) {
	err = response.parseFromHttpResponse(httpResponse)
	if err != nil {
		return
	}
	if !response.IsSuccess() {
		err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), "")
		return
	}

	if _, isCommonResponse := response.(*CommonResponse); isCommonResponse {
		// common response need not unmarshal
		return
	}

	if len(response.GetHttpContentBytes()) == 0 {
		return
	}

	if strings.ToUpper(format) == "JSON" {
		err = jsonParser.Unmarshal(response.GetHttpContentBytes(), response)
		if err != nil {
			err = errors.NewClientError(errors.JsonUnmarshalErrorCode, errors.JsonUnmarshalErrorMessage, err)
		}
	} else if strings.ToUpper(format) == "XML" {
		err = xml.Unmarshal(response.GetHttpContentBytes(), response)
	}
	return
}

type BaseResponse struct {
	httpStatus         int
	httpHeaders        map[string][]string
	httpContentString  string
	httpContentBytes   []byte
	originHttpResponse *http.Response
}

func (baseResponse *BaseResponse) GetHttpStatus() int {
	return baseResponse.httpStatus
}

func (baseResponse *BaseResponse) GetHttpHeaders() map[string][]string {
	return baseResponse.httpHeaders
}

func (baseResponse *BaseResponse) GetHttpContentString() string {
	return baseResponse.httpContentString
}

func (baseResponse *BaseResponse) GetHttpContentBytes() []byte {
	return baseResponse.httpContentBytes
}

func (baseResponse *BaseResponse) GetOriginHttpResponse() *http.Response {
	return baseResponse.originHttpResponse
}

func (baseResponse *BaseResponse) IsSuccess() bool {
	if baseResponse.GetHttpStatus() >= 200 && baseResponse.GetHttpStatus() < 300 {
		return true
	}

	return false
}

func (baseResponse *BaseResponse) parseFromHttpResponse(httpResponse *http.Response) (err error) {
	defer httpResponse.Body.Close()
	body, err := ioutil.ReadAll(httpResponse.Body)
	if err != nil {
		return
	}
	baseResponse.httpStatus = httpResponse.StatusCode
	baseResponse.httpHeaders = httpResponse.Header
	baseResponse.httpContentBytes = body
	baseResponse.httpContentString = string(body)
	baseResponse.originHttpResponse = httpResponse
	return
}

func (baseResponse *BaseResponse) String() string {
	resultBuilder := bytes.Buffer{}
	// statusCode
	// resultBuilder.WriteString("\n")
	resultBuilder.WriteString(fmt.Sprintf("%s %s\n", baseResponse.originHttpResponse.Proto, baseResponse.originHttpResponse.Status))
	// httpHeaders
	//resultBuilder.WriteString("Headers:\n")
	for key, value := range baseResponse.httpHeaders {
		resultBuilder.WriteString(key + ": " + strings.Join(value, ";") + "\n")
	}
	resultBuilder.WriteString("\n")
	// content
	//resultBuilder.WriteString("Content:\n")
	resultBuilder.WriteString(baseResponse.httpContentString + "\n")
	return resultBuilder.String()
}

type CommonResponse struct {
	*BaseResponse
}

func NewCommonResponse() (response *CommonResponse) {
	return &CommonResponse{
		BaseResponse: &BaseResponse{},
	}
}


text:
<?php

namespace Sparta\Validators;

use DateTime;

/**
 * Validation Class.
 *
 * @author  Mohammed Ashour <ashoms0a@gmail.com>
 *
 * @link    http://www.coderavine.com/
 */
class Date extends AbstractValidator
{
    /**
     * Default format that will be used when nothing has
     * been specified yet.
     *
     * @var string
     */
    const DEFAULT_FORMAT = 'Y-m-d';

    /**
     * @var string
     */
    protected $classMessage = [
        'invalid_data' => '%s does not seem to be a valid date',
    ];

    /**
     * Date constructor.
     *
     * @param array $options
     */
    public function __construct($options = [])
    {
        $options = $this->normalizeArguments($options);

        if (array_key_exists('format', $options)) {
            $this->setFormat($options['format']);
        } elseif (!empty($options)) {
            $this->setFormat(array_shift($options));
        }
    }

    /**
     * Set date format.
     *
     * @param string $format
     */
    public function setFormat($format)
    {
        $this->options['format'] = $format;
    }

    /**
     * Get date format.
     *
     * @return string
     */
    public function getFormat()
    {
        return (empty($this->options['format'])) ? self::DEFAULT_FORMAT : $this->options['format'];
    }

    /**
     * Validate given data.
     *
     * @param mixed $input
     *
     * @return bool
     */
    public function isValid($input)
    {
        if ($input instanceof DateTime) {
            return true;
        }

        $date = DateTime::createFromFormat($this->getFormat(), $input);
        $errors = DateTime::getLastErrors();
        if ($errors['warning_count'] > 0 || $errors['error_count'] > 0) {
            $this->errors[] = sprintf($this->message('invalid_data'), $input, $this->getFormat());

            return false;
        }

        return true;
    }
}


text:
export EventError,
       DeserializationError,
       UnknownEventTypeError,
       MissingTypeError,
       InvalidJSONError

abstract EventError

immutable DeserializationError <: EventError
    key::UTF8String
    text::UTF8String
    event_type::DataType
end

immutable UnknownEventTypeError <: EventError
    text::UTF8String
    event_type::UTF8String
end

immutable MissingTypeError <: EventError
    text::UTF8String
end

immutable InvalidJSONError <: EventError
    text::UTF8String
end


text:
package org.jboss.hal.dmr.dispatch;

public enum RequestHeader {

    // only those which are used in HAL
    ACCEPT("Accept"),
    CONTENT_TYPE("Content-Type"),
    X_MANAGEMENT_CLIENT_NAME("X-Management-Client-Name");

    private final String header;

    RequestHeader(final String header) {
        this.header = header;
    }

    public String header() {
        return header;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Flora, Jena 44: (1861)

#### Original name
Physcia euploca Tuck.

### Remarks
null


text:
using CSharp7.Demo.Common;
using Functional.Programs.Library;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Functional.Programs.Tests
{
    [TestClass]
    public class FilterDataTests
    {
        readonly List<int> _numbers = new List<int> { 3, 8, 4, 6, 1, 7, 5, 2, 9, 10 };
        readonly IFilterData _filterData;

        public FilterDataTests()
        {
            _filterData = new FilterData();
        }

        [TestMethod]
        public void When_SelectValues_IsPassed_ValidData()
        {
            var evenNumbers = _filterData.SelectValues(_numbers, e => e % 2 == 0);

            Assert.AreEqual(5, evenNumbers.Count);
        }

        [TestMethod]
        public void When_SelectValues_IsPassed_ValidData_ForOddNumbers()
        {
            var oddNumbers = _filterData.SelectValues(_numbers, e => e % 2 == 1);

            Assert.AreEqual(5, oddNumbers.Count);
        }

        [TestMethod]
        public void When_SelectValuesWithOrderBy_IsPassed_ValidData()
        {
            var evenNumbers = _filterData.SelectValuesWithOrderBy(_numbers, e => e % 2 == 0, e => e);

            Assert.AreEqual(5, evenNumbers.Count);
            Assert.IsTrue(IsSorted(evenNumbers));
        }

        private static bool IsSorted<T>(IEnumerable<T> list) where T : IComparable<T>
        {
            var y = list.First();
            return list.Skip(1).All(x =>
            {
                bool b = y.CompareTo(x) < 0;
                y = x;
                return b;
            });
        }

    }

}


text:
namespace ck
{
    namespace math
    {
        /// Returns (value >= minValue && value <= maxValue)
        template<typename _T>
        bool belongsTo(_T value, _T minValue, _T maxValue)
        {
            return (value >= minValue && value <= maxValue);
        }

        /// Returns (value > minValue && value < maxValue)
        template<typename _T>
        bool strictlyBelongsTo(_T value, _T minValue, _T maxValue)
        {
            return (value > minValue && value < maxValue);
        }

    }
}

#endif


text:
/**
 * Module dependencies.
 */

var express = require('express')
  , app = express()
  , server = require('http').createServer(app)
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path')
  , io   = require('socket.io').listen(server);

io.configure(function(){
  io.set('log level', 1);
});

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', routes.index);
app.get('/users', user.list);

server.listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

io.sockets.on('connection', function (socket) {
  socket.on('input', function (data) {
    socket.broadcast.emit('output', { socketName: socket.id, data: data });
  });
});


text:
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.QuartzIntegration.Tests
{
    using System;
    using System.Threading.Tasks;
    using NUnit.Framework;
    using Turnout.Contracts;

    [TestFixture]
    public class A_turnout_check_consumer :
        QuartzInMemoryTestFixture
    {
        [Test]
        public async Task Should_find_existing_jobs_and_continue_to_check_them()
        {
            var completed = SubscribeHandler<JobCompleted>();

            await Bus.Publish(new ProcessFile
            {
                Filename = "log.txt",
                Size = 10000
            });

            var context = await completed;
        }

        IInMemoryBusFactoryConfigurator _busFactoryConfigurator;

        protected override void ConfigureBus(IInMemoryBusFactoryConfigurator configurator)
        {
            base.ConfigureBus(configurator);

            _busFactoryConfigurator = configurator;
        }

        protected override void ConfigureInputQueueEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
        {
            base.ConfigureInputQueueEndpoint(configurator);

            configurator.Turnout<ProcessFile>(_busFactoryConfigurator, x =>
            {
                x.SuperviseInterval = TimeSpan.FromSeconds(1);
                x.SetJobFactory(async context =>
                {
                    await Console.Out.WriteLineAsync($"Started: {context.Message.Filename}");

                    await Task.Delay(context.Message.Size);

                    await Console.Out.WriteLineAsync($"Stopped: {context.Message.Filename}");
                });
            });
        }

        public class ProcessFile
        {
            public string Filename { get; set; }
            public int Size { get; set; }
        }
    }
}


text:
<!DOCTYPE html>

  <title>User Profiles</title>

{{user.name}}

Hair Color: {{ user.hair_color }}