text:
/**
 * PackageController
 *
 * @description :: Server-side logic for managing packages
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {

  /**
  * @api {get} /packages/:name Request Package Information
  * @apiName Get Package
  * @apiGroup Package
  *
  * @apiParam {String} name Name of the package
  *
  * @apiUse Timestamps
  * @apiSuccess {String}   name                   Package name
  * @apiSuccess {Integer}  latest_version_id      Last version (more recent) of this package
  * @apiSuccess {String}   uri                    Url to `self`
  * @apiSuccess {String}   api_uri                Url to the api endpoint of `self`
  * @apiSuccess {Integer}  type_id                Represents the repository from which the package is retrieved (1 for cran, 2 for bioconductor and 3 for github).
  * @apiSuccess {String}   created_at             The moment at which the record was created.
  * @apiSuccess {String}   updated_at             The moment at which the most recent update to the record occured.
  * @apiSuccess {Object[]} versions               List of versions of this package
  * @apiSuccess {String}   versions.uri           Url to this version
  * @apiSuccess {String}   versions.api_uri       Url to the api endpoint of this version
  * @apiSuccess {Integer}  versions.id            Id of this version
  * @apiSuccess {String}   versions.package_name  Name of the package of this version
  * @apiSuccess {String}   versions.version       String describing the version of the package
  * @apiSuccess {String}   versions.title         Title of the version
  * @apiSuccess {String}   versions.description   Description of the package version
  * @apiSuccess {Date}     versions.release_date  Release date of the package version
  * @apiSuccess {String}   versions.license       License of the package version
  * @apiSuccess {String}   versions.url           Url to official site of package
  * @apiSuccess {String}   versions.copyright     Copyright notice included in package
  * @apiSuccess {String}   versions.readmemd      Readme included in the package
  * @apiSuccess {String}   versions.sourceJSON    The sourceJSON containing the data from which the package is parsed.
  * @apiSuccess {Date}     created_at             The moment at which the record was created.
  * @apiSuccess {Date}     updated_at             The moment at which the most recent update to the record occured.
  * @apiSuccess {Integer}  versions.maintainer_id Id of the maintainer of the package version
  * @apiSuccess {String}   type                   Always 'package'
  */
  findByName: function(req, res) {
    var packageName = req.param('name');

    Package.findOne({
      where: {
        name: packageName
      },
      include: [
        { model: PackageVersion, as: 'versions' }
      ]
    }).then(function(_package) {
      if (_package === null) {
        return res.rstudio_redirect(301, '/search?q=' + encodeURIComponent(packageName));
        // there seems to be a problem with redirected requests if text/html is set as contentype for the ajax request, so I just
        // adapt this so Rstudio still gets the html
      } else if ((req.wantsJSON || req.path.startsWith('/api/')) && !req.param('viewer_pane') == 1) {
        _package = _package.toJSON();
        _package.type = 'package';
        return res.json(_package);
      } else {
        if (_package.versions.length === 0)
          return Package.findOne({
            where: {name: packageName},
            include: [{ model: PackageVersion, attributes: ['package_name', 'version', 'id'], as: 'reverse_dependencies'}]
          }).then(function(packageInstance) {
            if (packageInstance === null) return res.notFound();
            var _package = packageInstance.toJSON();
            _package.pageTitle = packageInstance.name;
            return res.ok(_package, 'package/show.ejs');
          });
        else return res.rstudio_redirect(301, _package.versions.sort(PackageService.compareVersions('desc', 'version'))[0].uri);
      }
    }).catch(function(err) {
      return res.negotiate(err);
    });

  },

  /**
  * @api {get} /packages List all packages
  * @apiName Get Packages
  * @apiGroup Package
  * @apiDescription Return an array of package object containing listed attributes and total number of package objects header.
  *
  * @apiHeader (Header) {String} x-total-count total count of packages.
  *
  * @apiParam {String} limit    the number to use when limiting records to send back (useful for pagination)
  * @apiParam {String} skip     the number of records to skip when limiting (useful for pagination)
  * @apiParam {String} sort     the order of returned records, e.g. `name ASC` or `name DESC`
  * @apiParam {String} criteria Limits packages to ones matching the given criteria. Criteria on the following columns are supported: `name`, `created_at`, `updated_at`, `latest_version_id` and `type_id` (being the number given to the repository in which the package is 1 for cran, 2 for bioconductor and 3 for github).
  * (e.g.: If you only want packages from github the argument type_id=3 can be passed.)
  *
  * @apiSuccess {String}   name                   Package name
  * @apiSuccess {Integer}  latest_version_id      Id of the last version (more recent) of this package
  * @apiSuccess {String}   uri                    Url to `self`
  * @apiSuccess {String}   api_uri                Url to the api endpoint of `self`
  * @apiSuccess {String}   type_id                Represents the repository from which the package is retrieved (1 for cran, 2 for bioconductor and 3 for github).
  * @apiSuccess {Date}     created_at             The moment at which the record was created.
  * @apiSuccess {Date}     updated_at             The moment at which the most recent update to the record occured.
  * @apiUse Timestamps
  */
  find: function(req, res) {
    var limit = Utils.parseLimit(req);
    var offset = Utils.parseSkip(req);
    var sort = Utils.parseSort(req);
    var criteria = Utils.parseCriteria(req);

    Package.findAll({
      limit: limit,
      where: criteria,
      offset: offset,
      order: sort,
      include: []
    }).then(function(packages) {
      res.set('X-Total-Count', packages.length);
      return res.json(packages);
    }).catch(function(err) {
      return res.negotiate(err);
    });
  },

  toggleStar: function(req, res) {
    var packageName = req.param('name');
    var user = req.user;

    RedisService.delPrefix('view_package_version_' + packageName);
    Package.findOne({
      where: {name: packageName},
      include: [
        { model: TaskView, as: 'inViews', attributes: ['name'] }
      ]
    }).then(function(_package) {
      var views = _package.inViews;
      views.forEach(function(view) {
        RedisService.del('rdocs_view_show_' + view.name);
      });
    });

    Star.findOrCreate({
      where: {
        user_id: user.id,
        package_name: packageName
      }
    }).spread(function(instance, created) {
      var destroyPromise = created ? Promise.resolve() : instance.destroy();
      destroyPromise.then(function() {
        return Star.findAll({
          where: { package_name: packageName }
        }).then(function(stars) {
          var newCount = stars.length;
          if (created) {
            return res.created({
              newCount: newCount,
              star: instance
            });
          }
          return res.send(200, {
            newCount: newCount,
            star: 'deleted'
          });
        });
      });
    }).catch(function(err) {
      return res.negotiate(err);
    });
  },

  toParse: function(req, res) {
    var limit = Utils.parseLimit(req);
    var offset = Utils.parseSkip(req);
    var parserVersion = req.param('parser_version');

    Package
    .findMostPopularUnfailedOldPackages(parserVersion, limit, offset)
    .then(function(packages) {
      return res.json(packages);
    }).catch(function(err) {
      return res.negotiate(err);
    });
  }
};


text:
Control flow component for executing functions concurrently. Usable in a browser or Node.js environment.

The motivation was to handle the parallel execution of functions without depending on a control flow library like [async](https://github.com/caolan/async).

## Installation

    bower install konexmedia/race

OR

    npm install konexmedia/race

## Usage example

```javascript
var race = require('race'); // Browser: var race = konexmedia.race;

race([
    function daFirst (callback) {
        setTimeout(function () {
            callback(null, 1);
        }, 200);
    },
    function daSecond (callback) {
        setTimeout(function () {
            callback(null, 'ehlo');
        }, 100);
    }
])
.finish(function (err, results) {
    if (err) {
        return console.error(err);
    }

    console.log(results.daFirst); => 1
    console.log(results.daSecond); => 'ehlo'
});
```

## Author

Copyright 2014, [konexmedia](http://konexmedia.com)

redpajama_set_name: RedPajamaGithub


text:
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Tomataboard.Services.AccessTokens;
using Tomataboard.Services.Extensions;
using Tomataboard.Services.Photos.Api500px.Contracts;

// ReSharper disable InconsistentNaming

namespace Tomataboard.Services.Photos.Api500px
{
    /// <summary>
    /// https://github.com/500px/api-documentation
    /// https://apigee.com/vova/embed/console/api500px
    /// OAuth 1.0a
    ///
    /// Good ideas here: http://www.rahulpnath.com/blog/exploring-oauth-c-and-500px/
    /// To check the signature: http://oauth.googlecode.com/svn/code/javascript/example/signature.html
    /// </summary>
    public class Api500px : OauthService, IApi500px
    {
        /// <summary>
        /// https://github.com/500px/api-documentation
        /// 1,000,000 requesters per month
        /// </summary>
        public Quota Quota => new Quota() { Requests = 1000000 / 30, Time = TimeSpan.FromDays(1) };

        public TimeSpan? Expiration => TimeSpan.FromHours(6);

        private OauthToken _accessToken;
        private OauthToken AccessToken => _accessToken ?? (_accessToken = _accessTokensRepository.Find(GetType().Name));
        private readonly Random _rnd = new Random();

        #region Constructors

        public Api500px(
            ILogger<Api500px> logger,
            IOptions<Api500pxKeys> keys,
            IAccessTokensRepository accessTokensRepository)
            : base(logger, accessTokensRepository)
        {
            _logger = logger;
            _keys = keys;
            AccessTokenUrl = "https://api.500px.com/v1/oauth/access_token";
            AuthorizeUrl = "https://api.500px.com/v1/oauth/authorize";
            RequestTokenUrl = "https://api.500px.com/v1/oauth/request_token";
            AlwaysEscapeSignature = true;
        }

        #endregion Constructors

        #region Public Methods

        private async Task<int> GetTotalPages(Dictionary<string, string> oauthParams, Dictionary<string, string> queryParams, string url)
        {
            AuthorizationParameters = new Dictionary<string, string>(oauthParams);
            Sign(url, _keys.Value.ConsumerSecret, AccessToken.Secret, "GET", queryParams);
            var json = await GetRequest(url, queryParams);
            var photosResponse = JsonConvert.DeserializeObject<GetPhotosResponse>(json);
            return photosResponse?.Photos == null ? 0 : photosResponse.TotalPages;
        }

        /// <summary>
        /// https://github.com/500px/api-documentation/blob/master/endpoints/photo/GET_photos.md
        /// </summary>
        /// <param name="category">Case sensitive, separate multiple values with a comma.</param>
        /// <returns></returns>
        private async Task<List<Photo>> GetPopularPhotos(string category)
        {
            var url = "https://api.500px.com/v1/photos";

            var oauthParams = new Dictionary<string, string>
            {
                    {OauthParameter.OauthConsumerKey, _keys.Value.ConsumerKey},
                    {OauthParameter.OauthNonce, ""},
                    {OauthParameter.OauthSignatureMethod, OAuthSignatureMethod},
                    {OauthParameter.OauthTimestamp, GetTimeStamp()},
                    {OauthParameter.OauthToken, AccessToken.Token},
                    {OauthParameter.OauthVersion, OAuthVersion}
            };

            var queryParams = new Dictionary<string, string>
            {
                { "feature", "popular"},
                { "only", category },
                { "page", "" },
                { "rpp", "100" },
                { "image_size", "1080,1600,2048" }
            };

            oauthParams[OauthParameter.OauthNonce] = GetNonce();
            queryParams["page"] = "1";
            var totalPages = await GetTotalPages(oauthParams, queryParams, url);

            oauthParams[OauthParameter.OauthNonce] = GetNonce();
            queryParams["page"] = GetRandomPageNumber(totalPages).ToString();
            AuthorizationParameters = oauthParams;

            Sign(url, _keys.Value.ConsumerSecret, AccessToken.Secret, "GET", queryParams);
            var json = await GetRequest(url, queryParams);
            return GetResult(json);
        }

        public async Task<List<Photo>> Execute(string parameters)
        {
            try
            {
                if (AccessToken == null)
                {
                    throw new Exception("Where is the AccessToken?");
                }

                // ignore the parameters for now and always return Landscapes
                return await GetPopularPhotos("Landscapes");
            }
            catch (Exception ex)
            {
                _logger.LogError($"{GetType().Name}: Cannot get photos for '{parameters}'. Exception: " + ex.GetError());
            }

            return null;
        }

        private int GetRandomPageNumber(int totalPages)
        {
            if (totalPages == 0) return 1;
            return _rnd.Next(1, totalPages + 1);
        }

        private List<Photo> GetResult(string json)
        {
            var photosResponse = JsonConvert.DeserializeObject<GetPhotosResponse>(json);
            if (photosResponse?.Photos == null) return null;

            var photos = new List<Photo>();
            foreach (var item in photosResponse.Photos)
            {
                var url = item.GetUrl();
                if (string.IsNullOrEmpty(url)) continue;
                if (item.Views == 0) continue;

                var photo = new Photo
                {
                    Service = "500px",
                    Name = item.Name.LimitTo(PhotoConstants.MaxNameLength),
                    AuthorName = item.User.FullName,
                    //AuthorProfilePage = item.GetAuthorProfilePage(),
                    PhotoPage = item.GetPhotoPage(),
                    Url = url
                };

                photos.Add(photo);
            }

            return photos.Count == 0 ? null : photos;
        }

        #endregion Public Methods
    }
}


text:
package org.wso2.carbon.siddhi.editor.core.util.designview.constants.query;

/**
 * Type of a Query List.
 */
public enum QueryListType {
    WINDOW_FILTER_PROJECTION,
    JOIN,
    PATTERN,
    SEQUENCE
}


text:
using System.Windows.Forms;

public class Form1
{

    private void btnReflectivePlane_Click(object sender, System.EventArgs e)
    {
        SolidEdgePart.PartDocument objPartDoc = null;
        SolidEdgePart.Profile objProfile = null;
        SolidEdgePart.Sketch sketch = null;
        SolidEdgeFrameworkSupport.Point2d objPoint = null;
        SolidEdgeFrameworkSupport.Line2d objOrientation = null;
        SolidEdgeFramework.Application objApplication = null;
        SolidEdgeFrameworkSupport.Point2d objPointOut = null;
        SolidEdgeFrameworkSupport.Line2d objOrientationOut = null;
        bool bStatus = false;
        double dDistance = 0;
        int iTransparency = 30;

        try
        {

            // Create/get the application with specific settings
            objApplication = Microsoft.VisualBasic.Interaction.GetObject(null, "SolidEdge.Application");
            if (objApplication == null)
            {
                MessageBox.Show("Could not get application.");
            }

            // open the document mentioned in the doc files.
            objPartDoc = objApplication.Documents.Open("C:\\ReflectivePlane.par");
            if (objPartDoc == null)
            {
                MessageBox.Show("Could not open document ");
            }

            objPartDoc.ActivateReflectivePlane();

            objPartDoc.SetReflectivePlane(SolidEdgePart.ReflectivePlaneConstants.igTopPlane, true, 0.3);
            objPartDoc.SetReflectivePlane(SolidEdgePart.ReflectivePlaneConstants.igRightPlane, true, 0.4);
            objPartDoc.SetReflectivePlane(SolidEdgePart.ReflectivePlaneConstants.igFrontPlane, true, 0.5);

            objPartDoc.GetReflectivePlane(SolidEdgePart.ReflectivePlaneConstants.igTopPlane, bStatus, dDistance);
            objPartDoc.GetReflectivePlane(SolidEdgePart.ReflectivePlaneConstants.igRightPlane, bStatus, dDistance);
            objPartDoc.GetReflectivePlane(SolidEdgePart.ReflectivePlaneConstants.igFrontPlane, bStatus, dDistance);

            objPartDoc.SetReflectivePlaneTransparency(true, iTransparency);
            objPartDoc.GetReflectivePlaneTransparency(bStatus, iTransparency);

            //objPartDoc.DeActivateReflectivePlane()

            if (objPartDoc == null)
            {
                objPartDoc.Close(false);
                objPartDoc = null;
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    public Form1()
    {
    	SubscribeToEvents();
    }

	private bool EventsSubscribed = false;
	private void SubscribeToEvents()
	{
		if (EventsSubscribed)
			return;
		else
			EventsSubscribed = true;

		btnReflectivePlane.Click += btnReflectivePlane_Click;
	}

}


text:
from __future__ import print_function
from sklearn.ensemble.base import BaseEnsemble
from sklearn.ensemble.weight_boosting import AdaBoostClassifier
from sklearn.multiclass import OneVsRestClassifier
from scipy.stats import itemfreq

import numpy as np
import itertools

def hash_row(row):
    one = np.uint64(1)
    zero = np.uint64(0)
    acc = zero
    for i in row:
        acc = np.left_shift(acc, one)
        acc = np.bitwise_or(acc, one if i else zero)
    return acc

def unhash_row(h, cols = None):
    row = []
    h = np.uint64(h)
    one = np.uint64(1)
    zero = np.uint64(0)

    if cols is None:
        while h > 0:
            row.append(np.bitwise_and(h, one)==zero)
            h = np.right_shift(h, one)
    else:
        for col in range(cols):
            row.append(np.bitwise_and(h, one)==zero)
            h = np.right_shift(h, one)
    return row[::-1]

def weights(y):
    return {x : 1.*f/len(y) for x,f in itemfreq(y)}

def transform_X_for_hash(X, h = 0):
    cols = np.array(unhash_row(h, X.shape[1]))
    rows = ~np.isnan(X[:,cols]).any(axis=1)
    return X[rows][:,cols], rows, cols

class AbstainingClassifier(BaseEnsemble):
    def __init__(self,
                 base_estimator=None,
                 n_estimators=50,
                 estimator_params=tuple(),
                 learning_rate=1.,
                 random_state=None,
                 verbose = False):

        super(AbstainingClassifier, self).__init__(
            base_estimator=base_estimator,
            n_estimators=n_estimators,
            estimator_params=estimator_params)

        self._verbose = verbose
        self._poly2features = False

    def fit(self, X, y):
        self.classes_ = np.unique(y)
        self.n_classes_ = len(self.classes_)

        # Find all feature hashes
        # Feature: poly2 missing, etc hashes
        hashes = np.unique(np.array([hash_row(i) for i in np.isnan(X)], dtype = np.uint64))

        if self._poly2features:
            hashes = np.unique([np.bitwise_or(i,j) for i,j in list(itertools.product(hashes, hashes))])

        self._validate_estimator()

        self.estimators_ = {}
        self.estimator_weights_ = {}
        self.estimator_errors_ = {}

        for h in hashes:
            self.estimators_[h] = self._make_estimator(append = False)
            if self._verbose: print('Training on hash #%d' % h)

            X_trans, rows, cols = transform_X_for_hash(X, h)
            y_trans = y[rows]

            if np.unique(y_trans).shape[0] == 1:
                # Abstain from all data since there is only one class.
                # Possible improvement - could this tell us that these features don't do anything?
                self.estimator_weights_[h] = 0.
                del self.estimators_[h]
                continue

            self.estimators_[h].fit(X_trans,y_trans)
            incorrect = sum(self.estimators_[h].predict(X_trans) != y_trans)
            abstaining = X.shape[0] - rows.sum()
            wM = np.min(1. * incorrect / X.shape[0], 0.000001)
            wA = 1. * abstaining / X.shape[0]
            wC = 1 - wM - wA
            print(wC, wM, wA)
            self.estimator_weights_[h] = 1.#np.log(wC/wM) - np.log(len(self.estimators_[h].classes_) - 1)

        weightsum = sum(self.estimator_weights_.values())
        for h in self.estimator_weights_.iterkeys():
            self.estimator_weights_[h] /= weightsum

    def predict_proba(self, X):
        #hashes = np.array([hash_row(i) for i in np.isnan(X)], dtype=long)

        yres = np.zeros([X.shape[0], len(self.classes_)])

        for h in self.estimators_.iterkeys():
            weight = self.estimator_weights_[h]
            estimator = self.estimators_[h]

            X_trans, rows, cols = transform_X_for_hash(X, h)
            if X_trans.shape[0] < 2 or X_trans.shape[1] < 2: continue

            print(h,X_trans.shape)
            y_predict = estimator.predict_proba(X_trans)

            for cls in estimator.classes_:
                yres[rows][:,self.classes_ == cls] += weight * y_predict[:,estimator.classes_ == cls]
        return yres

    def predict(self, X):
        pred = self.decision_function(X)

        if self.n_classes_ == 2:
            return self.classes_.take(pred > 0, axis=0)

        return self.classes_.take(np.argmax(pred, axis=1), axis=0)

    def decision_function(self, X):
        #check_is_fitted(self, "n_classes_")
        #X = self._validate_X_predict(X)

        pred = None

        pred = np.zeros([X.shape[0], self.n_classes_])
        for h in self.estimators_.iterkeys():
            X_trans, rows, cols = transform_X_for_hash(X, h)
            classes = self.estimators_[h].classes_[:, np.newaxis]
            n_classes = len(self.estimators_[h].classes_)
            pred[rows] += np.array([self.classes_ == self.estimators_[h].classes_[i] for i in (self.estimators_[h].predict(X_trans) == classes).T])
            pred[rows] *= self.estimator_weights_[h]

        #pred /= sum(self.estimator_weights_.values())
        #if n_classes == 2:
        #    pred[:, 0] *= -1
        #    return pred.sum(axis=1)
        return pred

if __name__ == '__main__':
    print(__doc__)

    # Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org>
    # License: BSD 3 clause

    # Standard scientific Python imports
    import matplotlib.pyplot as plt

    # Import datasets, classifiers and performance metrics
    from sklearn import datasets, linear_model, metrics, svm

    # The digits dataset
    digits = datasets.load_digits()

    # The data that we are interested in is made of 8x8 images of digits, let's
    # have a look at the first 3 images, stored in the `images` attribute of the
    # dataset.  If we were working from image files, we could load them using
    # pylab.imread.  Note that each image must have the same size. For these
    # images, we know which digit they represent: it is given in the 'target' of
    # the dataset.
    images_and_labels = list(zip(digits.images, digits.target))
    for index, (image, label) in enumerate(images_and_labels[:4]):
        plt.subplot(2, 4, index + 1)
        plt.axis('off')
        plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
        plt.title('Training: %i' % label)

    # To apply a classifier on this data, we need to flatten the image, to
    # turn the data in a (samples, feature) matrix:
    n_samples = len(digits.images)

    data = digits.images.reshape((n_samples, -1))
    R = (np.random.random(data[:n_samples / 2].shape) > 0.01)
    data[:n_samples / 2] += np.power(R-1.,0.5)

    # Create a classifier: a support vector classifier
    baseclassifier = svm.SVC(gamma = 0.001)
    classifier = AbstainingClassifier(baseclassifier)

    # We learn the digits on the first half of the digits
    classifier.fit(data[:n_samples / 2], digits.target[:n_samples / 2])

    # Now predict the value of the digit on the second half:
    expected = digits.target[n_samples / 2:]
    predicted = classifier.predict(data[n_samples / 2:])

    print("Classification report for classifier %s:\n%s\n"
        % (classifier, metrics.classification_report(expected, predicted)))
    print("Confusion matrix:\n%s" % metrics.confusion_matrix(expected, predicted))

    images_and_predictions = list(zip(digits.images[n_samples / 2:], predicted))
    for index, (image, prediction) in enumerate(images_and_predictions[:4]):
        plt.subplot(2, 4, index + 5)
        plt.axis('off')
        plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
        plt.title('Prediction: %i' % prediction)

    plt.show()


text:
<?php

declare(strict_types=1);

namespace Sylius\Component\Core\Model;

use Sylius\Component\Order\Model\OrderAwareInterface;
use Sylius\Component\Payment\Model\PaymentInterface as BasePaymentInterface;

interface PaymentInterface extends BasePaymentInterface, OrderAwareInterface
{
}


text:
package org.apache.hadoop.oncrpc;

import java.net.SocketAddress;

import org.jboss.netty.buffer.ChannelBuffer;

/**
 * RpcResponse encapsulates a response to a RPC request. It contains the data
 * that is going to cross the wire, as well as the information of the remote
 * peer.
 */
public class RpcResponse {
  private final ChannelBuffer data;
  private final SocketAddress remoteAddress;

  public RpcResponse(ChannelBuffer data, SocketAddress remoteAddress) {
    this.data = data;
    this.remoteAddress = remoteAddress;
  }

  public ChannelBuffer data() {
    return data;
  }

  public SocketAddress remoteAddress() {
    return remoteAddress;
  }
}


text:
"use strict";

var fs = require("fs");
var path = require("path");
var utils = require("./utils");

/**
 * Creates a new `Gentleman`
 * @param {array} packageNames
 * @param {function} callback
 * @class
 * @public
 */

var Gentleman = module.exports = function Gentleman(packageNames, callback) {
	return new proto.initialize(packageNames, callback);
};

var proto = utils.extend(Gentleman.prototype, {
	version: "0.1.0",

	/**
	 * @constructs `Gentleman`
	 * @see `Gentleman`
	 */

	initialize: function (packageNames, callback) {
		var that = this;
		var errors = {};

		(function next() {
			var packageName;
			var context;

			try {
				packageName = packageNames.shift();

				if (packageName && packageName !== "*") {
					context = (that[packageName + "Package"] = {});

					that.constructor.getPackage(packageName).call(context, that);

					return next();
				} else if (packageName === "*") {
					packageNames = that.constructor.generatePackageNames();

					return next();
				}
			} catch (error) {
				error.packageName = packageName;
				errors[packageName] = error;

				return next();
			}
		})();

		(callback || utils.noop).call(that, errors);
	},

	utils: utils
});

proto.initialize.prototype = proto;

utils.extend(Gentleman, {
	addPackage: function (packageName, callback) {
		var that = this;

		if (utils.hasOwnProp(that.packages, packageName)) {
			throw new Error(packageName + " already exists");
		}

		that.packages[packageName] = callback;
	},

	getPackage: function (packageName) {
		var that = this;

		if (!utils.hasOwnProp(that.packages, packageName)) {
			throw new ReferenceError(packageName + " does not exist");
		}

		return that.packages[packageName];
	},

	generatePackageNames: function () {
		var that = this;

		return Object.keys(that.packages).map(function (packageName) {
			return packageName;
		});
	}
});

/**
 * Collections of modules
 * @public
 */

Gentleman.packages = exports.packages = {};

/**
 * Auto-loads packages
 * @public
 */

(function (load) {
	fs.readdirSync(path.join(__dirname, "./", "packages")).forEach(function (filename) {
		var packageName;

		if (!(/\.js$/.test(filename))) {
			return;
		}

		packageName = path.basename(filename, ".js");
		Gentleman.packages[packageName] = load(packageName);
	});
})(function (packageName) {
	return require("./packages/" + packageName);
});


text:
"use strict";

module.exports  = function(resolve, reject) {
  return function(err, data) {
    if(err)
      return reject(err);
    return resolve(data);
  };
};


text:
package org.apache.storm.testing;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.storm.spout.SpoutOutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichSpout;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Values;
import org.apache.storm.utils.InprocMessaging;

public class FeederSpout extends BaseRichSpout {
    private int _id;
    private Fields _outFields;
    private SpoutOutputCollector _collector;
    private AckFailDelegate _ackFailDelegate;

    public FeederSpout(Fields outFields) {
        _id = InprocMessaging.acquireNewPort();
        _outFields = outFields;
    }

    public void setAckFailDelegate(AckFailDelegate d) {
        _ackFailDelegate = d;
    }

    public void feed(List<Object> tuple) {
        feed(tuple, UUID.randomUUID().toString());
    }

    public void feed(List<Object> tuple, Object msgId) {
        InprocMessaging.sendMessage(_id, new Values(tuple, msgId));
    }

    public void feedNoWait(List<Object> tuple, Object msgId) {
        InprocMessaging.sendMessageNoWait(_id, new Values(tuple, msgId));
    }

    public void waitForReader() {
        InprocMessaging.waitForReader(_id);
    }

    public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
        _collector = collector;
    }

    public void close() {

    }

    public void nextTuple() {
        List<Object> toEmit = (List<Object>) InprocMessaging.pollMessage(_id);
        if (toEmit!=null) {
            List<Object> tuple = (List<Object>) toEmit.get(0);
            Object msgId = toEmit.get(1);

            _collector.emit(tuple, msgId);
        }
    }

    public void ack(Object msgId) {
        if(_ackFailDelegate!=null) {
            _ackFailDelegate.ack(msgId);
        }
    }

    public void fail(Object msgId) {
        if(_ackFailDelegate!=null) {
            _ackFailDelegate.fail(msgId);
        }
    }

    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(_outFields);
    }

    @Override
    public Map<String, Object> getComponentConfiguration() {
        return new HashMap<String, Object>();
    }
}


text:
#ifndef __TDA665x_H
#define __TDA665x_H

struct tda665x_config {
	char name[128];

	u8	addr;
	u32	frequency_min;
	u32	frequency_max;
	u32	frequency_offst;
	u32	ref_multiplier;
	u32	ref_divider;
};

#if defined(CONFIG_DVB_TDA665x) || (defined(CONFIG_DVB_TDA665x_MODULE) && defined(MODULE))

extern struct dvb_frontend *tda665x_attach(struct dvb_frontend *fe,
					   const struct tda665x_config *config,
					   struct i2c_adapter *i2c);

#else

static inline struct dvb_frontend *tda665x_attach(struct dvb_frontend *fe,
						  const struct tda665x_config *config,
						  struct i2c_adapter *i2c)
{
	printk(KERN_WARNING "%s: Driver disabled by Kconfig\n", __func__);
	return NULL;
}

#endif /* CONFIG_DVB_TDA665x */

#endif /* __TDA665x_H */


text:
    <meta charset="UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>DSGos Slides</title>
    <link rel="stylesheet" type="text/css" href="/usr/share/DSGos-Installer/data/css/slides-style.css"/>
    <link rel="stylesheet" type="text/css" href="/usr/share/DSGos-Installer/data/css/lightSlider.css"/>


text:
namespace logic
{
  ASTNot::ASTNot(const Token& token, AST* right)
    : AST(token, {right})
  {
    assert(token.type == Token::Type::NOT);
  }

  AST* ASTNot::clone() const
  {
    return new ASTNot(token_, right_get().clone());
  }

  void ASTNot::accept(Visitor& visitor)
  {
    visitor.visit(*this);
  }

  const AST& ASTNot::right_get() const
  {
    return child_get(0);
  }

  AST& ASTNot::right_get()
  {
    return child_get(0);
  }
}


text:
describe('<Confirmation />', () => {
  it('Expect to have unit tests specified', () => {
    expect(true).toEqual(false);
  });
});


text:
// AUTOMATICALLY GENERATED BY MIDDLECRAFT
/* Allows plugins to access server functions without needing to link the actual server Jar. */
package net.minecraft.server;

public abstract class TileEntityChest extends TileEntity {
	// FIELDS
	private ItemStack[] chestContents;

	// METHODS

	/**
	 *
	 */
	public abstract int MIDDLECRAFT_func_739_a();

	/**
	 *
	 */
	public abstract ItemStack MIDDLECRAFT_func_740_a(int a);

	/**
	 *
	 */
	public abstract ItemStack MIDDLECRAFT_func_741_a(int a, int b);

	/**
	 *
	 */
	public abstract void MIDDLECRAFT_func_742_a(int a, ItemStack b);

	/**
	 *
	 */
	public abstract void MIDDLECRAFT_func_744_a(NBTTagCompound a);

	/**
	 *
	 */
	public abstract boolean MIDDLECRAFT_func_747_a_(EntityPlayer a);

	/**
	 *
	 */
	public abstract java.lang.String MIDDLECRAFT_func_743_b();

	/**
	 *
	 */
	public abstract void MIDDLECRAFT_func_745_b(NBTTagCompound a);

	/**
	 *
	 */
	public abstract int MIDDLECRAFT_func_746_c();

}


text:
module Main where

-- Test thread creation.
-- (from: Einar Wolfgang Karlsen <ewk@Informatik.Uni-Bremen.DE>)

import Control.Concurrent

main :: IO ()
main = do
   mvar <- newEmptyMVar

   let
        spawner :: (IO () -> IO ThreadId) -> Int -> IO ()
        spawner c 0 = putMVar mvar ()
        spawner c n = do { c (spawner c (n-1)); return ()}

   spawner forkIO 100000
   takeMVar mvar
   putStr "done"


text:
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.
// http://code.google.com/p/protobuf/
//
// 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 org.apache.activemq.protobuf.compiler;

import java.io.IOException;
import java.math.BigInteger;
import java.nio.CharBuffer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.activemq.protobuf.Buffer;
import org.apache.activemq.protobuf.UTF8Buffer;

/**
 * Provide ascii text parsing and formatting support for proto2 instances.
 * The implementation largely follows google/protobuf/text_format.cc.
 *
 * HRC: I wish the original class was not package protected so we did not need
 * to copy this file over.  We need to request that the protobuf folks open
 * this class up amoung a few others.
 *
 * @author wenboz@google.com Wenbo Zhu
 * @author kenton@google.com Kenton Varda
 */
public final class TextFormat {

  /** Convert an unsigned 32-bit integer to a string. */
  private static String unsignedToString(int value) {
    if (value >= 0) {
      return Integer.toString(value);
    } else {
      return Long.toString(((long) value) & 0x00000000FFFFFFFFL);
    }
  }

  /** Convert an unsigned 64-bit integer to a string. */
  private static String unsignedToString(long value) {
    if (value >= 0) {
      return Long.toString(value);
    } else {
      // Pull off the most-significant bit so that BigInteger doesn't think
      // the number is negative, then set it again using setBit().
      return BigInteger.valueOf(value & 0x7FFFFFFFFFFFFFFFL)
                       .setBit(63).toString();
    }
  }

  // =================================================================
  // Parsing

  /**
   * Represents a stream of tokens parsed from a {@code String}.
   *
   *
The Java standard library provides many classes that you might think
   * would be useful for implementing this, but aren't.  For example:
   *
   *

   *
{@code java.io.StreamTokenizer}:  This almost does what we want -- or,
   *   at least, something that would get us close to what we want -- except
   *   for one fatal flaw:  It automatically un-escapes strings using Java
   *   escape sequences, which do not include all the escape sequences we
   *   need to support (e.g. '\x').
   *
{@code java.util.Scanner}:  This seems like a great way at least to
   *   parse regular expressions out of a stream (so we wouldn't have to load
   *   the entire input into a single string before parsing).  Sadly,
   *   {@code Scanner} requires that tokens be delimited with some delimiter.
   *   Thus, although the text "foo:" should parse to two tokens ("foo" and
   *   ":"), {@code Scanner} would recognize it only as a single token.
   *   Furthermore, {@code Scanner} provides no way to inspect the contents
   *   of delimiters, making it impossible to keep track of line and column
   *   numbers.
   *

   *
   *
Luckily, Java's regular expression support does manage to be useful to
   * us.  (Barely:  We need {@code Matcher.usePattern()}, which is new in
   * Java 1.5.)  So, we can use that, at least.  Unfortunately, this implies
   * that we need to have the entire input in one contiguous string.
   */
  private static final class Tokenizer {
    private final CharSequence text;
    private final Matcher matcher;
    private String currentToken;

    // The character index within this.text at which the current token begins.
    private int pos = 0;

    // The line and column numbers of the current token.
    private int line = 0;
    private int column = 0;

    // The line and column numbers of the previous token (allows throwing
    // errors *after* consuming).
    private int previousLine = 0;
    private int previousColumn = 0;

    private static Pattern WHITESPACE =
      Pattern.compile("(\\s|(#.*$))+", Pattern.MULTILINE);
    private static Pattern TOKEN = Pattern.compile(
      "[a-zA-Z_][0-9a-zA-Z_+-]*|" +                 // an identifier
      "[0-9+-][0-9a-zA-Z_.+-]*|" +                  // a number
      "\"([^\"\n\\\\]|\\\\.)*(\"|\\\\?$)|" +        // a double-quoted string
      "\'([^\"\n\\\\]|\\\\.)*(\'|\\\\?$)",          // a single-quoted string
      Pattern.MULTILINE);

    private static Pattern DOUBLE_INFINITY = Pattern.compile(
      "-?inf(inity)?",
      Pattern.CASE_INSENSITIVE);
    private static Pattern FLOAT_INFINITY = Pattern.compile(
      "-?inf(inity)?f?",
      Pattern.CASE_INSENSITIVE);
    private static Pattern FLOAT_NAN = Pattern.compile(
      "nanf?",
      Pattern.CASE_INSENSITIVE);

    /** Construct a tokenizer that parses tokens from the given text. */
    public Tokenizer(CharSequence text) {
      this.text = text;
      this.matcher = WHITESPACE.matcher(text);
      skipWhitespace();
      nextToken();
    }

    /** Are we at the end of the input? */
    public boolean atEnd() {
      return currentToken.length() == 0;
    }

    /** Advance to the next token. */
    public void nextToken() {
      previousLine = line;
      previousColumn = column;

      // Advance the line counter to the current position.
      while (pos < matcher.regionStart()) {
        if (text.charAt(pos) == '\n') {
          ++line;
          column = 0;
        } else {
          ++column;
        }
        ++pos;
      }

      // Match the next token.
      if (matcher.regionStart() == matcher.regionEnd()) {
        // EOF
        currentToken = "";
      } else {
        matcher.usePattern(TOKEN);
        if (matcher.lookingAt()) {
          currentToken = matcher.group();
          matcher.region(matcher.end(), matcher.regionEnd());
        } else {
          // Take one character.
          currentToken = String.valueOf(text.charAt(pos));
          matcher.region(pos + 1, matcher.regionEnd());
        }

        skipWhitespace();
      }
    }

    /**
     * Skip over any whitespace so that the matcher region starts at the next
     * token.
     */
    private void skipWhitespace() {
      matcher.usePattern(WHITESPACE);
      if (matcher.lookingAt()) {
        matcher.region(matcher.end(), matcher.regionEnd());
      }
    }

    /**
     * If the next token exactly matches {@code token}, consume it and return
     * {@code true}.  Otherwise, return {@code false} without doing anything.
     */
    public boolean tryConsume(String token) {
      if (currentToken.equals(token)) {
        nextToken();
        return true;
      } else {
        return false;
      }
    }

    /**
     * If the next token exactly matches {@code token}, consume it.  Otherwise,
     * throw a {@link ParseException}.
     */
    public void consume(String token) throws ParseException {
      if (!tryConsume(token)) {
        throw parseException("Expected \"" + token + "\".");
      }
    }

    /**
     * Returns {@code true} if the next token is an integer, but does
     * not consume it.
     */
    public boolean lookingAtInteger() {
      if (currentToken.length() == 0) {
        return false;
      }

      char c = currentToken.charAt(0);
      return ('0' <= c && c <= '9') ||
             c == '-' || c == '+';
    }

    /**
     * If the next token is an identifier, consume it and return its value.
     * Otherwise, throw a {@link ParseException}.
     */
    public String consumeIdentifier() throws ParseException {
      for (int i = 0; i < currentToken.length(); i++) {
        char c = currentToken.charAt(i);
        if (('a' <= c && c <= 'z') ||
            ('A' <= c && c <= 'Z') ||
            ('0' <= c && c <= '9') ||
            (c == '_') || (c == '.')) {
          // OK
        } else {
          throw parseException("Expected identifier.");
        }
      }

      String result = currentToken;
      nextToken();
      return result;
    }

    /**
     * If the next token is a 32-bit signed integer, consume it and return its
     * value.  Otherwise, throw a {@link ParseException}.
     */
    public int consumeInt32() throws ParseException {
      try {
        int result = parseInt32(currentToken);
        nextToken();
        return result;
      } catch (NumberFormatException e) {
        throw integerParseException(e);
      }
    }

    /**
     * If the next token is a 32-bit unsigned integer, consume it and return its
     * value.  Otherwise, throw a {@link ParseException}.
     */
    public int consumeUInt32() throws ParseException {
      try {
        int result = parseUInt32(currentToken);
        nextToken();
        return result;
      } catch (NumberFormatException e) {
        throw integerParseException(e);
      }
    }

    /**
     * If the next token is a 64-bit signed integer, consume it and return its
     * value.  Otherwise, throw a {@link ParseException}.
     */
    public long consumeInt64() throws ParseException {
      try {
        long result = parseInt64(currentToken);
        nextToken();
        return result;
      } catch (NumberFormatException e) {
        throw integerParseException(e);
      }
    }

    /**
     * If the next token is a 64-bit unsigned integer, consume it and return its
     * value.  Otherwise, throw a {@link ParseException}.
     */
    public long consumeUInt64() throws ParseException {
      try {
        long result = parseUInt64(currentToken);
        nextToken();
        return result;
      } catch (NumberFormatException e) {
        throw integerParseException(e);
      }
    }

    /**
     * If the next token is a double, consume it and return its value.
     * Otherwise, throw a {@link ParseException}.
     */
    public double consumeDouble() throws ParseException {
      // We need to parse infinity and nan separately because
      // Double.parseDouble() does not accept "inf", "infinity", or "nan".
      if (DOUBLE_INFINITY.matcher(currentToken).matches()) {
        boolean negative = currentToken.startsWith("-");
        nextToken();
        return negative ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
      }
      if (currentToken.equalsIgnoreCase("nan")) {
        nextToken();
        return Double.NaN;
      }
      try {
        double result = Double.parseDouble(currentToken);
        nextToken();
        return result;
      } catch (NumberFormatException e) {
        throw floatParseException(e);
      }
    }

    /**
     * If the next token is a float, consume it and return its value.
     * Otherwise, throw a {@link ParseException}.
     */
    public float consumeFloat() throws ParseException {
      // We need to parse infinity and nan separately because
      // Float.parseFloat() does not accept "inf", "infinity", or "nan".
      if (FLOAT_INFINITY.matcher(currentToken).matches()) {
        boolean negative = currentToken.startsWith("-");
        nextToken();
        return negative ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
      }
      if (FLOAT_NAN.matcher(currentToken).matches()) {
        nextToken();
        return Float.NaN;
      }
      try {
        float result = Float.parseFloat(currentToken);
        nextToken();
        return result;
      } catch (NumberFormatException e) {
        throw floatParseException(e);
      }
    }

    /**
     * If the next token is a boolean, consume it and return its value.
     * Otherwise, throw a {@link ParseException}.
     */
    public boolean consumeBoolean() throws ParseException {
      if (currentToken.equals("true")) {
        nextToken();
        return true;
      } else if (currentToken.equals("false")) {
        nextToken();
        return false;
      } else {
        throw parseException("Expected \"true\" or \"false\".");
      }
    }

    /**
     * If the next token is a string, consume it and return its (unescaped)
     * value.  Otherwise, throw a {@link ParseException}.
     */
    public String consumeString() throws ParseException {
      return new UTF8Buffer(consumeBuffer()).toString();
    }

    /**
     * If the next token is a string, consume it, unescape it as a
     * {@link Buffer}, and return it.  Otherwise, throw a
     * {@link ParseException}.
     */
    public Buffer consumeBuffer() throws ParseException {
      char quote = currentToken.length() > 0 ? currentToken.charAt(0) : '\0';
      if (quote != '\"' && quote != '\'') {
        throw parseException("Expected string.");
      }

      if (currentToken.length() < 2 ||
          currentToken.charAt(currentToken.length() - 1) != quote) {
        throw parseException("String missing ending quote.");
      }

      try {
        String escaped = currentToken.substring(1, currentToken.length() - 1);
        Buffer result = unescapeBytes(escaped);
        nextToken();
        return result;
      } catch (InvalidEscapeSequence e) {
        throw parseException(e.getMessage());
      }
    }

    /**
     * Returns a {@link ParseException} with the current line and column
     * numbers in the description, suitable for throwing.
     */
    public ParseException parseException(String description) {
      // Note:  People generally prefer one-based line and column numbers.
      return new ParseException(
        (line + 1) + ":" + (column + 1) + ": " + description);
    }

    /**
     * Returns a {@link ParseException} with the line and column numbers of
     * the previous token in the description, suitable for throwing.
     */
    public ParseException parseExceptionPreviousToken(String description) {
      // Note:  People generally prefer one-based line and column numbers.
      return new ParseException(
        (previousLine + 1) + ":" + (previousColumn + 1) + ": " + description);
    }

    /**
     * Constructs an appropriate {@link ParseException} for the given
     * {@code NumberFormatException} when trying to parse an integer.
     */
    private ParseException integerParseException(NumberFormatException e) {
      return parseException("Couldn't parse integer: " + e.getMessage());
    }

    /**
     * Constructs an appropriate {@link ParseException} for the given
     * {@code NumberFormatException} when trying to parse a float or double.
     */
    private ParseException floatParseException(NumberFormatException e) {
      return parseException("Couldn't parse number: " + e.getMessage());
    }
  }

  /** Thrown when parsing an invalid text format message. */
  public static class ParseException extends IOException {
    public ParseException(String message) {
      super(message);
    }
  }

  private static final int BUFFER_SIZE = 4096;

  // TODO(chrisn): See if working around java.io.Reader#read(CharBuffer)
  // overhead is worthwhile
  private static StringBuilder toStringBuilder(Readable input)
      throws IOException {
    StringBuilder text = new StringBuilder();
    CharBuffer buffer = CharBuffer.allocate(BUFFER_SIZE);
    while (true) {
      int n = input.read(buffer);
      if (n == -1) {
        break;
      }
      buffer.flip();
      text.append(buffer, 0, n);
    }
    return text;
  }

  // =================================================================
  // Utility functions
  //
  // Some of these methods are package-private because Descriptors.java uses
  // them.

  /**
   * Escapes bytes in the format used in protocol buffer text format, which
   * is the same as the format used for C string literals.  All bytes
   * that are not printable 7-bit ASCII characters are escaped, as well as
   * backslash, single-quote, and double-quote characters.  Characters for
   * which no defined short-hand escape sequence is defined will be escaped
   * using 3-digit octal sequences.
   */
  static String escapeBytes(Buffer input) {
    StringBuilder builder = new StringBuilder(input.getLength());
    for (int i = 0; i < input.getLength(); i++) {
      byte b = input.byteAt(i);
      switch (b) {
        // Java does not recognize \a or \v, apparently.
        case 0x07: builder.append("\\a" ); break;
        case '\b': builder.append("\\b" ); break;
        case '\f': builder.append("\\f" ); break;
        case '\n': builder.append("\\n" ); break;
        case '\r': builder.append("\\r" ); break;
        case '\t': builder.append("\\t" ); break;
        case 0x0b: builder.append("\\v" ); break;
        case '\\': builder.append("\\\\"); break;
        case '\'': builder.append("\\\'"); break;
        case '"' : builder.append("\\\""); break;
        default:
          if (b >= 0x20) {
            builder.append((char) b);
          } else {
            builder.append('\\');
            builder.append((char) ('0' + ((b >>> 6) & 3)));
            builder.append((char) ('0' + ((b >>> 3) & 7)));
            builder.append((char) ('0' + (b & 7)));
          }
          break;
      }
    }
    return builder.toString();
  }

  /**
   * Un-escape a byte sequence as escaped using
   * {@link #escapeBytes(Buffer)}.  Two-digit hex escapes (starting with
   * "\x") are also recognized.
   */
  static Buffer unescapeBytes(CharSequence input)
      throws InvalidEscapeSequence {
    byte[] result = new byte[input.length()];
    int pos = 0;
    for (int i = 0; i < input.length(); i++) {
      char c = input.charAt(i);
      if (c == '\\') {
        if (i + 1 < input.length()) {
          ++i;
          c = input.charAt(i);
          if (isOctal(c)) {
            // Octal escape.
            int code = digitValue(c);
            if (i + 1 < input.length() && isOctal(input.charAt(i + 1))) {
              ++i;
              code = code * 8 + digitValue(input.charAt(i));
            }
            if (i + 1 < input.length() && isOctal(input.charAt(i + 1))) {
              ++i;
              code = code * 8 + digitValue(input.charAt(i));
            }
            result[pos++] = (byte)code;
          } else {
            switch (c) {
              case 'a' : result[pos++] = 0x07; break;
              case 'b' : result[pos++] = '\b'; break;
              case 'f' : result[pos++] = '\f'; break;
              case 'n' : result[pos++] = '\n'; break;
              case 'r' : result[pos++] = '\r'; break;
              case 't' : result[pos++] = '\t'; break;
              case 'v' : result[pos++] = 0x0b; break;
              case '\\': result[pos++] = '\\'; break;
              case '\'': result[pos++] = '\''; break;
              case '"' : result[pos++] = '\"'; break;

              case 'x':
                // hex escape
                int code = 0;
                if (i + 1 < input.length() && isHex(input.charAt(i + 1))) {
                  ++i;
                  code = digitValue(input.charAt(i));
                } else {
                  throw new InvalidEscapeSequence(
                    "Invalid escape sequence: '\\x' with no digits");
                }
                if (i + 1 < input.length() && isHex(input.charAt(i + 1))) {
                  ++i;
                  code = code * 16 + digitValue(input.charAt(i));
                }
                result[pos++] = (byte)code;
                break;

              default:
                throw new InvalidEscapeSequence(
                  "Invalid escape sequence: '\\" + c + "'");
            }
          }
        } else {
          throw new InvalidEscapeSequence(
            "Invalid escape sequence: '\\' at end of string.");
        }
      } else {
        result[pos++] = (byte)c;
      }
    }

    return new Buffer(result, 0, pos);
  }

  /**
   * Thrown by {@link TextFormat#unescapeBytes} and
   * {@link TextFormat#unescapeText} when an invalid escape sequence is seen.
   */
  static class InvalidEscapeSequence extends IOException {
    public InvalidEscapeSequence(String description) {
      super(description);
    }
  }

  /**
   * Like {@link #escapeBytes(Buffer)}, but escapes a text string.
   * Non-ASCII characters are first encoded as UTF-8, then each byte is escaped
   * individually as a 3-digit octal escape.  Yes, it's weird.
   */
  static String escapeText(String input) {
    return escapeBytes(new UTF8Buffer(input));
  }

  /**
   * Un-escape a text string as escaped using {@link #escapeText(String)}.
   * Two-digit hex escapes (starting with "\x") are also recognized.
   */
  static String unescapeText(String input) throws InvalidEscapeSequence {
    return new UTF8Buffer(unescapeBytes(input)).toString();
  }

  /** Is this an octal digit? */
  private static boolean isOctal(char c) {
    return '0' <= c && c <= '7';
  }

  /** Is this a hex digit? */
  private static boolean isHex(char c) {
    return ('0' <= c && c <= '9') ||
           ('a' <= c && c <= 'f') ||
           ('A' <= c && c <= 'F');
  }

  /**
   * Interpret a character as a digit (in any base up to 36) and return the
   * numeric value.  This is like {@code Character.digit()} but we don't accept
   * non-ASCII digits.
   */
  private static int digitValue(char c) {
    if ('0' <= c && c <= '9') {
      return c - '0';
    } else if ('a' <= c && c <= 'z') {
      return c - 'a' + 10;
    } else {
      return c - 'A' + 10;
    }
  }

  /**
   * Parse a 32-bit signed integer from the text.  Unlike the Java standard
   * {@code Integer.parseInt()}, this function recognizes the prefixes "0x"
   * and "0" to signify hexidecimal and octal numbers, respectively.
   */
  static int parseInt32(String text) throws NumberFormatException {
    return (int) parseInteger(text, true, false);
  }

  /**
   * Parse a 32-bit unsigned integer from the text.  Unlike the Java standard
   * {@code Integer.parseInt()}, this function recognizes the prefixes "0x"
   * and "0" to signify hexidecimal and octal numbers, respectively.  The
   * result is coerced to a (signed) {@code int} when returned since Java has
   * no unsigned integer type.
   */
  static int parseUInt32(String text) throws NumberFormatException {
    return (int) parseInteger(text, false, false);
  }

  /**
   * Parse a 64-bit signed integer from the text.  Unlike the Java standard
   * {@code Integer.parseInt()}, this function recognizes the prefixes "0x"
   * and "0" to signify hexidecimal and octal numbers, respectively.
   */
  static long parseInt64(String text) throws NumberFormatException {
    return parseInteger(text, true, true);
  }

  /**
   * Parse a 64-bit unsigned integer from the text.  Unlike the Java standard
   * {@code Integer.parseInt()}, this function recognizes the prefixes "0x"
   * and "0" to signify hexidecimal and octal numbers, respectively.  The
   * result is coerced to a (signed) {@code long} when returned since Java has
   * no unsigned long type.
   */
  static long parseUInt64(String text) throws NumberFormatException {
    return parseInteger(text, false, true);
  }

  private static long parseInteger(String text,
                                   boolean isSigned,
                                   boolean isLong)
                                   throws NumberFormatException {
    int pos = 0;

    boolean negative = false;
    if (text.startsWith("-", pos)) {
      if (!isSigned) {
        throw new NumberFormatException("Number must be positive: " + text);
      }
      ++pos;
      negative = true;
    }

    int radix = 10;
    if (text.startsWith("0x", pos)) {
      pos += 2;
      radix = 16;
    } else if (text.startsWith("0", pos)) {
      radix = 8;
    }

    String numberText = text.substring(pos);

    long result = 0;
    if (numberText.length() < 16) {
      // Can safely assume no overflow.
      result = Long.parseLong(numberText, radix);
      if (negative) {
        result = -result;
      }

      // Check bounds.
      // No need to check for 64-bit numbers since they'd have to be 16 chars
      // or longer to overflow.
      if (!isLong) {
        if (isSigned) {
          if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
            throw new NumberFormatException(
              "Number out of range for 32-bit signed integer: " + text);
          }
        } else {
          if (result >= (1L << 32) || result < 0) {
            throw new NumberFormatException(
              "Number out of range for 32-bit unsigned integer: " + text);
          }
        }
      }
    } else {
      BigInteger bigValue = new BigInteger(numberText, radix);
      if (negative) {
        bigValue = bigValue.negate();
      }

      // Check bounds.
      if (!isLong) {
        if (isSigned) {
          if (bigValue.bitLength() > 31) {
            throw new NumberFormatException(
              "Number out of range for 32-bit signed integer: " + text);
          }
        } else {
          if (bigValue.bitLength() > 32) {
            throw new NumberFormatException(
              "Number out of range for 32-bit unsigned integer: " + text);
          }
        }
      } else {
        if (isSigned) {
          if (bigValue.bitLength() > 63) {
            throw new NumberFormatException(
              "Number out of range for 64-bit signed integer: " + text);
          }
        } else {
          if (bigValue.bitLength() > 64) {
            throw new NumberFormatException(
              "Number out of range for 64-bit unsigned integer: " + text);
          }
        }
      }

      result = bigValue.longValue();
    }

    return result;
  }
}


text:
// https://github.com/apache/cordova-plugin-globalization/

var languages = [
    'English',
    'English (Canadian)',
    'French',
    'French (Canadian)',
    'German',
    'Русский'
];

var daysOfTheWeek = [
    'Sunday',
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday'
];

function initialize () {
    var localeList = document.querySelector('#locale-list');
    var dayList = document.querySelector('#day-list');

    languages.forEach(function (locale) {
        var option = document.createElement('option');
        option.value = locale;
        var caption = document.createTextNode(locale);
        option.appendChild(caption);
        localeList.appendChild(option);
    });

    daysOfTheWeek.forEach(function (day) {
        var option = document.createElement('option');
        option.value = day;
        var caption = document.createTextNode(day);
        option.appendChild(caption);
        dayList.appendChild(option);
    });
}

module.exports = {
    initialize: initialize
};


text:
<?php

namespace Fedeisas\LaravelMailCssInliner;

use DOMDocument;
use Illuminate\Mail\Events\MessageSending;
use Symfony\Component\Mime\Message;
use Symfony\Component\Mailer\Event\MessageEvent;
use Symfony\Component\Mime\Part\AbstractPart;
use Symfony\Component\Mime\Part\Multipart\AlternativePart;
use Symfony\Component\Mime\Part\TextPart;
use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;

class CssInlinerPlugin
{
    private CssToInlineStyles $converter;

    private string $cssToAlwaysInclude;

    public function __construct(array $filesToInline = [], CssToInlineStyles $converter = null)
    {
        $this->cssToAlwaysInclude = $this->loadCssFromFiles($filesToInline);

        $this->converter = $converter ?? new CssToInlineStyles;
    }

    public function handle(MessageSending $event): void
    {
        $message = $event->message;

        if (!$message instanceof Message) {
            return;
        }

        $this->handleSymfonyMessage($message);
    }

    public function handleSymfonyEvent(MessageEvent $event): void
    {
        $message = $event->getMessage();

        if (!$message instanceof Message) {
            return;
        }

        $this->handleSymfonyMessage($message);
    }

    private function processPart(AbstractPart $part): AbstractPart
    {
        if ($part instanceof TextPart && $part->getMediaType() === 'text' && $part->getMediaSubtype() === 'html') {
            return $this->processHtmlTextPart($part);
        }

        return $part;
    }

    private function loadCssFromFiles(array $cssFiles): string
    {
        $css = '';

        foreach ($cssFiles as $file) {
            $css .= file_get_contents($file);
        }

        return $css;
    }

    private function processHtmlTextPart(TextPart $part): TextPart
    {
        [$cssFiles, $bodyString] = $this->extractCssFilesFromMailBody($part->getBody());

        $bodyString = $this->converter->convert($bodyString, $this->cssToAlwaysInclude . "\n" . $this->loadCssFromFiles($cssFiles));

        return new TextPart($bodyString, $part->getPreparedHeaders()->getHeaderParameter('Content-Type', 'charset') ?: 'utf-8', 'html');
    }

    private function handleSymfonyMessage(Message $message): void
    {
        $body = $message->getBody();

        if ($body === null) {
            return;
        }

        if ($body instanceof TextPart) {
            $message->setBody($this->processPart($body));
        } elseif ($body instanceof AlternativePart) {
            $message->setBody(new AlternativePart(
                ...array_map(
                    fn (AbstractPart $part) => $this->processPart($part),
                    $body->getParts()
                )
            ));
        }
    }

    private function extractCssFilesFromMailBody(string $message): array
    {
        $document = new DOMDocument;

        $previousUseInternalErrors = libxml_use_internal_errors(true);

        $document->loadHTML($message);

        libxml_use_internal_errors($previousUseInternalErrors);

        $cssLinkTags = [];

        foreach ($document->getElementsByTagName('link') as $linkTag) {
            if ($linkTag->getAttribute('rel') === 'stylesheet') {
                $cssLinkTags[] = $linkTag;
            }
        }

        $cssFiles = [];

        foreach ($cssLinkTags as $linkTag) {
            $cssFiles[] = $linkTag->getAttribute('href');

            $linkTag->parentNode->removeChild($linkTag);
        }

        // If we found CSS files in the document we load them and return the document without the link tags
        if (!empty($cssFiles)) {
            /** @noinspection PhpExpressionResultUnusedInspection */
            $this->loadCssFromFiles($cssFiles);

            return [$cssFiles, $document->saveHTML()];
        }

        return [$cssFiles, $message];
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <title></title>

    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <meta name="description" content="">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="">
    <meta name="twitter:description" content="">

    <meta property="og:type" content="article">
    <meta property="og:title" content="">
    <meta property="og:description" content="">

    <link href="/favicon.ico" rel="shortcut icon" type="image/x-icon">
    <link href="/apple-touch-icon-precomposed.png" rel="apple-touch-icon">

    <link href="//fonts.googleapis.com/" rel="dns-prefetch">
    <link href="//fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic|Open+Sans:700,400&subset=latin,latin-ext" rel="stylesheet">

    <link rel="stylesheet" href="//pramodjg.github.io/articles/themes/ghostium/assets/css/main.min.css?v=1476623537946"/>
    <link rel="stylesheet" href="//pramodjg.github.io/articles/themes/ghostium/assets/css/custom.css?v=1476623537946"/>
    <link rel="stylesheet" href="//pramodjg.github.io/articles/themes/ghostium/assets/css/asciidoctor-foundation.css?v=1476623537946"/>

    <link rel="canonical" href="https://pramodjg.github.io/articles/" />
    <meta name="referrer" content="origin" />

    <meta property="og:type" content="website" />
    <meta property="og:title" content="" />
    <meta property="og:url" content="https://pramodjg.github.io/articles/" />
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="" />
    <meta name="twitter:url" content="https://pramodjg.github.io/articles/" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="" href="https://pramodjg.github.io/articles/rss/" />

    <button data-action="open-drawer" id="drawer-button" class="drawer-button"></button>

              Home

              Subscribe to Feed

            Follow me

                communicating between components in react-native

React-Native is a javascript a library by facebook for developing user interfaces. To say it is a painless way to create user interfaces for mobile applications. It is very flexible language and can be used…

                <time datetime="2016-10-16" itemprop="datePublished">
                  19 hours ago
                </time>

                      react-native,  android,  communication,  react-component

                Comments

                Blockchain for healthcare industry

The healthcare providers in the entire world offers high-end technologies for analysing and determining a particular disease. But there are certain key problems which are need to be rectified in the healthcare industry. Poor data…

                <time datetime="2016-10-06" itemprop="datePublished">
                  11 days ago
                </time>

                      Blockchain,  Healthcare,  Disruption

                Comments

                Blockchain - Rebranding Industries

Simply stating, Blockchain is a technology based on distributed computing and cryptography that enables peoples, to transact with previously unknown persons, and record transactions in a ledger. Its a new technology introduced mainly for financ…

                <time datetime="2016-10-06" itemprop="datePublished">
                  11 days ago
                </time>

                      Blockchain,  Industries,  Disruption

                Comments

  Page 1 of 1

Copyright © . 2016. All Rights Reserved.

Ghostium Theme by @oswaldoacauan

Adapted by Maxime Gréau

Published with HubPress


text:
package br.com.objectos.core.array;

import br.com.objectos.core.object.Checks;

/**
 *

 * This class provides {@code static} methods for operating on {@code double}
 * arrays.
 *
 * @since 2
 */
public final class DoubleArrays {

  static final double[] EMPTY = new double[0];

  private DoubleArrays() {}

  /**
   * Copies the values of the array into a larger one (if necessary) so that a
   * value can be inserted at the required index. More formally:
   *
   *

   * If the {@code requiredIndex} is smaller than {@code 0} then an
   * {@link java.lang.IllegalArgumentException} is thrown.
   *
   *

   * If the {@code requiredIndex} is smaller than {@code array.length} then the
   * array is not copied and is returned unchanged.
   *
   *

   * If the {@code requiredIndex} is equal to or is greater than
   * {@code array.length} then:
   *
   *

   *
a new {@code double} array instance is created. The length of the new
   * array is guaranteed to be greater than {@code requiredIndex};

   *
all values from the original array are copied into the new array so
   * that, for all valid indices in the original array, the new array contains
   * an identical value for the same index; and

   *
the new array instance is returned.

   *

   *
   *

   * A typical usage is:
   *
   *

   * double d = computeDouble();
   * array = DoubleArrays.copyIfNecessary(array, currentIndex);
   * array[currentIndex++] = d;

   *
   * @param array
   *        the array instance to be copied if necessary
   * @param requiredIndex
   *        the index where a value is to be inserted
   *
   * @return the {@code array} instance itself or a larger copy of the
   *         original
   *
   * @throws IllegalArgumentException
   *         if {@code requiredIndex < 0}
   */
  public static double[] copyIfNecessary(double[] array, int requiredIndex) {
    Checks.checkArgument(requiredIndex >= 0, "requiredIndex cannot be negative");

    int length;
    length = array.length;

    if (requiredIndex < length) {
      return array;
    }

    int newLength;
    newLength = MoreArrays.growArrayLength(length, requiredIndex);

    double[] result;
    result = new double[newLength];

    System.arraycopy(array, 0, result, 0, length);

    return result;
  }

  /**
   * Returns the empty zero-length {@code double} array instance. Since it is a
   * zero-length instance, values cannot be inserted nor removed from it.
   *
   * @return an empty {@code double} array
   */
  public static double[] empty() {
    return EMPTY;
  }

}


text:
import json
import os
import threading
import time
import logging

from pyMusicSync import utils

class Record:
    """ Class representing a record file to keep track of converted and synced file """
    threadLock = threading.Lock()
    filePath = ""
    record = {}  # <trackID>:<filePath>

    def __init__(self, filePath, interval):
        self.filePath = filePath
        if not (os.path.isfile(self.filePath)):
            self.write()
        self.read()
        self.killed = False
        self.hasUnsavedChanges = False
        self.autosaveInterval = interval
        self.autosaveThread = threading.Thread(target=self.__autosave)

    def read(self):
        with open(self.filePath) as f:
            self.record = json.load(f)

    def add(self, track):
        # Not thread-safe
        with self.threadLock:
            self.record[track.trackID] = track.syncedFilePath
            self.hasUnsavedChanges = True

    def remove(self, item):
        with self.threadLock:
            del self.record[item]
            self.hasUnsavedChanges = True

    def __contains__(self, item):
        with self.threadLock:
            trackID = utils.genID(item)
            return trackID in self.record

    def get(self, item):
        return self.record[item]

    def write(self):
        with self.threadLock:
            with open(self.filePath, "w") as f:
                json.dump(self.record, f, indent=4)

    def idList(self):
        return list(self.record.keys())

    def __autosave(self):
        lastTime = time.monotonic()
        while True:
            if self.killed:
                return
            currTime = time.monotonic()
            if self.hasUnsavedChanges and (currTime - lastTime >= self.autosaveInterval):
                logging.debug("writing changes")
                self.write()
                self.hasUnsavedChanges = False
                lastTime = currTime
            time.sleep(0.1)

    def startAutosave(self):
        self.autosaveThread.start()

    def killAutosave(self):
        self.killed = True


text:
layout: organization
category: local

title: Camp HorseAbility Inc.
impact_area: Human Rights
keywords:
  - Animals
  - The Disabled
  - Health and Wellness
location_services: Long Island
location_offices:
website: www.HorseAbility.Org

description: |
  HorseAbility takes in horses as therapy animals, and uses them to improve the lives of people with special needs as young as 2 1/2 years old, all the way through seniors in their 90's! People come to HorseAbility and learn how to ride, learn about horses and how to care for them, and also how to care for themselves.
mission: |
  HorseAbility's mission is to improve the lives of children and adults with special needs through facilitated interaction with horses.

cash_grants: Yes
grants:
  - |
    Hungry Hungry Horses Campaign- Feed our herd of 20 horses for a day, week or month: Hay: $30 a day, $200 a week, $800 a month Grain: $60 a day, $400 a week, $1600 a month
  - |
    Sponsor a rider: $55 a lesson
service_opp: Yes
services:
  - |
    Our age to volunteer in the ring is 13 years old. However we offer service projects to help clean up the property often.
  - |
    Project based- gardening; interaction with our senior groups...

learn:
  - Give students a tour of our office and facilities
  - Make a presentation about our organization
  - Speak over the phone about our work
cont_relationship:

salutation:
first_name: Annie
last_name: Follansbee
title_contact_person:

city: Old Westbury
state: NY
address: |
  223 Store Hill Road/PO Box 410-1
  Old Westbury NY 11568
lat: 37.191062
lng: -82.648162
phone: 516-333-6151
ext:
fax:
email: ProgramDirector@HorseAbility.Org
preferred_contact:
contact_person_intro:
---
HorseAbility takes in horses as therapy animals, and uses them to improve the lives of people with special needs as young as 2 1/2 years old, all the way through seniors in their 90's! People come to HorseAbility and learn how to ride, learn about horses and how to care for them, and also how to care for themselves.


text:
package stonehorse.grit.test;

import stonehorse.grit.tools.Util;

import java.io.Serializable;

public class A implements Serializable, Comparable<A>{

    private static final long serialVersionUID = 1L;
    final int num;
    final String text;
    final boolean isText;

    A(int num) {
        this.num = num;
        text = null;
        isText = false;
    }

    public static A a(){
        return new A("a");
    }
    public static A a(String text){
        return new A(text);
    }

    public static A a(int num){
        return new A(num);
    }

    A(String text) {
        this.text = text;
        num = 0;
        isText = true;
    }

    @Override
    public String toString() {
        if (isText)
            return "A:" + text;
        return "A:" + num;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null)
            return false;
        if (!(obj instanceof A))
            return false;
        A a = (A) obj;
        if (a.isText != isText)
            return false;
        if (isText) {
            return Util.equal(a.text, text);
        } else {
            return a.num == num;
        }
    }

    @Override
    public int hashCode() {
        if (isText) {
            return Util.hashCode(text);
        }
        else return num;

    }

	@Override public int compareTo(A o) {
		if(o.equals(this))
			return 0;
		return 1;
	}
}


text:
%&mex --translate-file=il2-pl

% Zaznaczyæ, ¿e "host ip" oraz "host ipv4" to to samo i ¿e to jest
% rozszerzenie i przygotowanie do ipv6.

% zastanowiæ siê nad pomys³em implementacji komendy "iface" ³±cz±cej
% interfejsy urz±dzeñ.

\input colordvi
\nopagenumbers

% Czcionki pomocnicze
\font\tfont=plr10 scaled \magstep3
\font\chfont=plb10 scaled \magstep2
\font\subchfont=plb10 scaled \magstep1

% Makro odpowiedzalne za rozdzia³
\def\chap#1{\bigskip\noindent{\chfont #1}\smallskip}
\def\subchap#1{\bigskip\noindent{\subchfont #1}\smallskip}
\def\propchap#1{\bigskip\noindent{\subchfont #1}\smallskip}
\def\mytt#1;#2.{
\noindent\hfil\hbox to 2.5in{\strut\hfill#2\hfil}\hskip20pt{\tt #1}\hfill\break
}

% Nag³ówek
\centerline{\tfont Koszek-Matyja Network Simulator}
\medskip
\centerline{\it Wojciech A. Koszek}
\centerline{\tt wkoszek@FreeBSD.czest.pl}
\smallskip
\centerline{\it Piotr Matyja}
\centerline{\tt peter.matyja@gmail.com}
\bigskip
\bigskip

% -- Tre¶æ --

\chap{Wprowadzenie}
\noindent
G³ównym powodem do stworzenia programu {\tt KMNSIM} by³a chêæ wiarygodnego
odtworzenia zachowania sieci {\tt Ethernet} w sposób wirtualny, bez
konieczno¶ci faktycznej ingerencji w strukturê i konfiguracjê jakiejkolwiek
fizycznej sieci.

Dziêki programowej emulacji zachowania sieci Ethernet, mo¿liwe
jest symulowanie po³±czeñ miêdzy komputerami-hostami, koncentratorami,
prze³±cznikami oraz routerami.

\smallskip
\Red{2009-06-16: funkcjonalno¶æ dot. routerów nie jest jeszcze
zaimplementowana}
\smallskip

\chap{Architektura symulatora}
\noindent
Symulator stworzony zosta³ w modu³owy sposób. Taka architektura niesie za
sob± wiele zalet, od choæby ³atwej mo¿lwo¶ci testowania oprogramowania, a na
rozszerzalno¶ci koñcz±c. W pocz±tkowej fazie projektowania problemem sta³a
siê sama z³o¿ono¶æ mo¿liwej do zasymulowania sieci oraz ilo¶æ mo¿liwych do
wykonania po³±czeñ.

Naszym zdaniem niemo¿liwe by³oby dok³adne przetestowanie programu, gdyby
zosta³ wykonany on w sposób typowy dla aplikacji z graficznym interfejsem
u¿ytkownika. Zdecydowali¶my siê tote¿ na skorzystanie z architektury
oprogramowania znanego z systemów rodziny {\tt UNIX}, gdzie g³ówn±
funkcjonalno¶æ realizuje aplikacja tekstowa, uruchamiania w trybie
wstadowym. Wynik dzia³ania programu zapisywany jest do plik (b±d¼ plików),
których poprawno¶æ mo¿na ³atwo zweryfikowaæ. Na podstawie generowanego pliku
interfejs graficzny, uruchamiany jako osobny, niezale¿ny program, jest w
stanie zwizualizowaæ u¿ytkownikowi poszczególne kroki czasowe symulacji.

\smallskip
\Red{Natywny graficzny interfejs u¿ytkownika nie jest jeszcze
zaimplementowany; istnieje jednak¿e mo¿liwo¶æ wykorzystania pakietu
in¿ynierskiego Graphviz to podejrzenia w postaci graficznej plików DOT,
które reprezentuj± graf po³±czeñ miêdzy elementami sieciowymi}.
\smallskip

\chap{Zasada dzia³ania}
\noindent
Sposób w jaki dzia³a program jest do¶æ prosty. U¿ytkownik tworzy opis sieci
w pliku tekstowym przy pomocy zdefiniowanego jêzyka opisu sieci.  Jêzyk ten
zastêpuje typowe, graficzne metody konfiguracji. Jest jednocze¶nie formatem
s³u¿±cym do zachowywania struktury symulowanej sieci.

Proces konfiguracji--tworzenia pliku wej¶ciowego--rozpoczynamy od
specyfikacji wszystkich elementów sieci. Nastêpnie dokonujemy po³±czeñ
miêdzy nimi w kontek¶cie spinania "wirtualnego" kabla. Poprawna konfiguracja
poszczególnych urz±dzeñ oraz posiadania choæ jednego aktywnego po³±czenia
umo¿liwiaj± rozpoczêcie procesu symulacji.

Ka¿de urz±dzenie sieciowe do którego mo¿na siê pod³±czyæ (host, hub, switch,
router) posiada pewn± ilo¶æ interfejsów.

Podstawow± jednostk± nadawania jest {\tt host}.  Posiada on mo¿liwo¶æ
nadawania i odbioru danych z sieci, które skierowane zosta³y do niego.
Minimaln± ilo¶ci± hostów nadaj±cych jest 1.  Host posiada jeden interfejs,
który w celu aktywacji musi zostaæ skonfigurowany adresem fizycznym MAC,
adresem IP oraz mask± sieciow±.

Hub jest po¶rednikiem w wymianie pakietów miêdzy hostami/routerami.  Hub
posiada pewn± z góry okre¶lon± ilo¶æ interfejsów. Owe interfejsy nie mog±
ulec konfiguracji. S± one tylko przeka¼nikiem nap³ywaj±cych ramek.

\smallskip
\Red{Obecna implementacja zak³ada, ¿e zarówno hub jak i switch ma 8 portów;
Specyfikacja dowolnej ilo¶ci portów wymaga kosmetycznych zmian w kodzie
symulatora.}
\smallskip

\noindent
Rola switcha jest analogiczna do roli huba, z jedyn± funkcjonaln± ró¿nic±,
¿e zamiast przekazywaæ odebrany pakiet na wszystkie porty, switch dokonuje
routingu w warstwie drugiej przekazuj±c pakiet tylko na port, z którego
host/router docelowy bêd± w stanie odebraæ dane.

Po³±czenie miêdzy dwoma urz±dzeniami mo¿liwe jest po specyfikacji 4
parametrów: nazwy i numeru interfejsu miejsca ¼ród³owego po³±czenia oraz
nazwy i numeru interfejsu miejsca przeznaczenia.

Na tym etapie proces tworzenia pliku konfiguracyjnego jest ukoñczony.

Program interpretuje ów plik oraz sprawdza jego poprawno¶æ. W przypadku
b³êdnej sk³adni pliku konfiguracyjnego, program przerywa dzia³anie oraz
informuje u¿ytkownika o pope³nionych b³êdach. W przeciwnym razie program
rozpoczyna symulacjê. Symulacja polega na wykonaniu wyspecyfikowanej przez
u¿ytkonika ilo¶ci kroków, po którym nast±pi koniec symulacji.

Ostateczn± faz± dzia³ania jest wypisanie wyników symulacji na ekran. Program
wspiera kilka formatów wyj¶ciowych -- wcze¶niej wspomniany format Dot
pakietu Graphviz, format tekstowy u¿yteczny do obserwacji faktycznej
{\bf~implementacji} symulatora lub, najbardziej u¿yteczny, plik tekstowy
obrazuj±cy zachowanie sieci w poszczególnych krokach symulacji.

% Host.
\chap{Opis jêzyka konfiguracyjnego: {\tt host}}
\noindent
Pierwszym elementem potrzebnym do symulacji jest host.  Ka¿dy {\bf host}
posiada kolejkê nadawczo-odbiorcz±. W przypadku wysy³ania danych umieszcza w
buforze nadawczym dane dot. miejsca ¼ród³owego i przeznaczenia, po czym
oznacza dane jako gotowe do wys³ania. Automatycznie wraz ze stworzeniem
hosta {\tt NAZWA} stworzony zostanie interfejs o nazwie {\tt NAZWA} i
numerze {\tt 0} (analogicznie do nazewnictwa interfejsów w wiêkszo¶ci
systemów operacyjnych).

\smallskip
\Blue{
Okre¶lenie miejsca docelowego, a co za tym idzie, pó¼niejsza decyzja o
akceptacji do przetwarzania pakietu dokonywana jest na bazie tre¶ci pakietu.
}
\smallskip

\propchap{Proponowana sk³adnia dla dodawania hosta}
\mytt host newhost1 create; Spowoduje dodanie hosta do sieci.
\mytt host mojhost1 remove; Usuwa host z sieci.

\chap{Opis jêzyka konfiguracyjnego: iface}
\noindent
Konfiguracja interfejsu mo¿e odbywaæ siê w przypadku, gdy dany interfejs
nale¿y do hosta b±d¼ routera.

\mytt iface NAZWA NUMER mac AA:BB:CC:DD:EE:FF; Konfiguruje ustawienia warstwy fizycznej.
\mytt iface NAZWA NUMER ip IP; Konfiguruje adres IP hosta.
\mytt iface NAZWA NUMER netmask NETMASK; Konfiguruje maskê sieciow± hosta.

W przypadku hosta {\tt NUMER} musi byæ równy 0 -- host posiada tylko jeden
interfejs. Z kolei w przypadku huba/switcha mo¿liwe jest wyspecyfikowanie
innych interfejsów w obrêbie dostêpnych portów.  Przyk³adowo, dla hosta {\tt
h1} mo¿liwymi komendami s±:

\medskip
\mytt iface h1 0 mac 11:22:33:44:55:66; Konfiguruje ustawienia warstwy fizycznej.
\mytt iface h1 0 ip 192.168.1.1; Konfiguruje adres IP hosta.
\mytt iface h1 0 netmask 255.255.255.0; Konfiguruje maskê sieciow± hosta.
\medskip

% Hub.
\chap{Opis jêzyka konfiguracyjnego: hub}
\noindent
Pierwszym elementem styczno¶ci hosta z sieci± jest {\bf hub}. Hub jest
urz±dzeniem, które posiada wiele portów Ethernet. Ruch odebrany na jednym z
portów jest przekierowywany na wszystkie inne dostêpne porty.  W celu
stworzenia huba w sieci korzystamy z polecenia:
\medskip
\mytt hub NAZWA create; Spowoduje dodanie huba do sieci.
\mytt hub NAZWA remove; Usuwa huba z sieci.
\medskip

\noindent
Na przyk³ad stworzenie hub'a {\tt hu1} mo¿liwe jest dziêki poleceniom:

\medskip
\mytt hub hu1 create; Spowoduje dodanie huba {\tt hu1} do sieci.
\mytt hub hu1 remove; Usuwa huba {\tt hu1} z sieci.
\medskip

% Switch.
\chap{Opis jêzyka konfiguracyjnego: switch}
\noindent
W celu stworzenia switcha w sieci korzystamy z polecenia:

\medskip
\mytt switch NAZWA create; Spowoduje dodanie huba do sieci.
\mytt switch NAZWA remove; Usuwa huba z sieci.
\medskip

\noindent
Stworzenie switchaa {\tt sw1} mo¿liwe jest dziêki poleceniom:

\medskip
\mytt switch sw1 create; Spowoduje dodanie switcha {\tt sw1} do sieci.
\mytt switch sw1 remove; Usuwa switch {\tt sw1} z sieci.
\medskip

\chap{Opis jêzyka konfiguracyjnego: router}
\noindent
Router to host posiadaj±cy wiele interfejsów sieciowych o ró¿nych adresach
IP. Router posiada równie¿ tablicê routingu czyli spis miejsc osi±galnych
poprzez okre¶lony interfejs sieciowy.  Router posiada mo¿liwo¶æ
przekierowania danych z jednego interfejsu do drugiego -- dzieje siê tak w
przypadku, w którym miejsce przeznaczenia wys³anego z hosta pakietu znajduje
siê w tablicy routingu routera.  Oznacza to, ¿e router wie, na który
interfejs przekierowaæ pakiet i w³a¶nie to dokonuje.

\propchap{Proponowana sk³adnia dla dodawania routera}
\mytt router NAZWA create; Stworzenie routera.
\mytt router NAZWA remove; Usuniêcie routera.
\mytt router NAZWA route IP NETMASK NUMER-INTERFEJSU; Ustala trasê routingu.

\smallskip
\Red{
Ta czê¶æ jest jeszcze niezaimplementowana.
}
\smallskip

\noindent
Aktywne elementy sieci, które posiadaj± mo¿liwo¶æ nadawania danych mog±
posiadaæ przypisane do siebie zadanie. Zadanie s³u¿y do wymuszenia pewnego
ustalonego ruchu danych w strukturze sieci i jest zasadnicz± w³a¶ciwo¶ci±
pracy symulatora. Zadanie zostanie wykonane po rozpoczêciu symulacji.

% Reszta.
\chap{Jêzyk konfiguracyjny: pozosta³e po³±czenia}
\noindent
Na koniec pozosta³a nam najbardziej u¿yteczna grupa instrukcji, a mianowicie
ta specyfikuj±ca poszczególne parametry dotycz±ce procesu symulacji. Zmiany
parametrów mo¿emy dokonaæ poprzez:

\mytt set NAZWA WARTOSC; Ustawia zmienn± NAZWA na warto¶æ WARTOSC.

\noindent
Zaimplementowana funkcjonalno¶æ to:

\mytt set simtime ILE-KROKOW; Ustawia ilo¶æ kroków symulacji (domy¶lnie:10).

\chap{Notki implementacyjne}
\noindent
Symulator zosta³ napisany w jêzyku ANSI C. Wybór na tê technologiê pad³ z
powodu ³atwej dostêpno¶ci nag³ówków, implementuj±cych struktury pakietów
sieci Ethernet oraz najlepsz± z dostêpnych dróg na zapewnienie modularno¶ci
(biblioteki dzielone) naszego projektu.

\Blue{
Architektura symulatora w chwili obecnej u¿ywa uproszczonych nag³ówków
Ethernet, IP oraz ICMP.
Mo¿liwe jest jednak uzyskanie PE£NEJ zgodno¶ci ze struktur± rzeczywistych
pakietów i wykorzystanie replik w symulatorze.
}

\Red{
Faktem jest, ¿e symulator rzeczywi¶cie pracuje w kontek¶cie "wysy³ania",
"odbierania", "analizy" i "przetwarzania" rzeczywistych pakietów. Wiadomo¶æ
ICMP REQUEST jest faktyczn± porcj± danych docieraj±c± do interfejsu hosta,
któr± ten musi przeanalizowaæ.
}

Plik nag³ówkowy {\tt queue.h} zosta³ zapo¿yczony z projektu FreeBSD i s³u¿y
do wygodnego zarz±dzania strukturami danych (listy, kolejki) wykorzystanymi
w projekcie.

{\Red{Do gruntownego rozszerzenia!}}

\chap{Zakoñczenie}
\noindent ¯yczymy mi³ego u¿ytkowania i czekamy na uwagi.
\bigskip
\bigskip
\rightline{Wojciech A. Koszek}
\rightline{\tt wkoszek@FreeBSD.czest.pl}
\smallskip
\rightline{Piotr Matyja}
\rightline{\tt peter.matyja@gmail.com}

\bye


text:
<?php

namespace Vinelab\Auth\Contracts;

interface ProfileInterface
{
    public function instantiate($profile, $provider);

    public function info();

    public function provider();
}


text:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Santiago.Infrastructure.Repositories.DataProviding.DbEntities
{
    [Table("dbo.PhotographCategory")]
    public class DbPhotographCategory
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        public string Name { get; set; }

        public string Alias { get; set; }

        public int Order { get; set; }

        public DateTime CreationDate { get; set; }

        public DateTime LastModifiedDate { get; set; }
    }
}


text:
package io.reactivex.internal.operators.completable;

import static org.junit.Assert.*;
import org.junit.Test;
import org.reactivestreams.Publisher;

import io.reactivex.*;
import io.reactivex.functions.*;

public class CompletableRepeatWhenTest {
    @Test
    public void whenCounted() {

        final int[] counter = { 0 };

        Completable.fromAction(new Action() {
            @Override
            public void run() throws Exception {
                counter[0]++;
            }
        })
        .repeatWhen(new Function<Flowable<Object>, Publisher<Object>>() {
            @Override
            public Publisher<Object> apply(Flowable<Object> f) throws Exception {
                final int[] j = { 3 };
                return f.takeWhile(new Predicate<Object>() {
                    @Override
                    public boolean test(Object v) throws Exception {
                        return j[0]-- != 0;
                    }
                });
            }
        })
        .subscribe();

        assertEquals(4, counter[0]);
    }
}


text:
package org.keycloak.models.map.authorization.entity;

import org.keycloak.models.map.common.AbstractEntity;

import org.keycloak.models.map.common.UpdatableEntity;
import java.util.Objects;

public class MapScopeEntity extends UpdatableEntity.Impl implements AbstractEntity {

    private String id;
    private String name;
    private String displayName;
    private String iconUri;
    private String resourceServerId;

    public MapScopeEntity(String id) {
        this.id = id;
    }

    public MapScopeEntity() {}

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void setId(String id) {
        if (this.id != null) throw new IllegalStateException("Id cannot be changed");
        this.id = id;
        this.updated |= id != null;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.updated |= !Objects.equals(this.name, name);
        this.name = name;
    }

    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.updated |= !Objects.equals(this.displayName, displayName);
        this.displayName = displayName;
    }

    public String getIconUri() {
        return iconUri;
    }

    public void setIconUri(String iconUri) {
        this.updated |= !Objects.equals(this.iconUri, iconUri);
        this.iconUri = iconUri;
    }

    public String getResourceServerId() {
        return resourceServerId;
    }

    public void setResourceServerId(String resourceServerId) {
        this.updated |= !Objects.equals(this.resourceServerId, resourceServerId);
        this.resourceServerId = resourceServerId;
    }

    @Override
    public String toString() {
        return String.format("%s@%08x", getId(), System.identityHashCode(this));
    }
}