text:
const assert = require('assert');
const fs = require('fs');
const path = require('path');

const { S3 } = require('aws-sdk');

const conf = require('../../../../../lib/Config').config;
const getConfig = require('../support/config');
const { WebsiteConfigTester } = require('../../lib/utility/website-util');

const config = getConfig('default', { signatureVersion: 'v4' });
const s3 = new S3(config);

// Note: To run these tests locally, you may need to edit the machine's
// /etc/hosts file to include the following line:
// `127.0.0.1 bucketwebsitetester.s3-website-us-east-1.amazonaws.com`

const transport = conf.https ? 'https' : 'http';
const bucket = process.env.AWS_ON_AIR ? `awsbucketwebsitetester-${Date.now()}` :
    'bucketwebsitetester';
const hostname = `${bucket}.s3-website-us-east-1.amazonaws.com`;
const endpoint = process.env.AWS_ON_AIR ? `${transport}://${hostname}` :
    `${transport}://${hostname}:8000`;
const redirectEndpoint = conf.https ? 'https://www.google.com/' :
    'http://www.google.com/';

const indexDocETag = '"95a589c37a2df74b062fb4d5a6f64197"';
const indexExpectedHeaders = {
    'etag': indexDocETag,
    'x-amz-meta-test': 'value',
};

// Basic Expected Behavior:

// 1) If error, respond with error headers:

// HTTP/1.1 403 Forbidden
// Date: Wed, 21 Dec 2016 20:33:00 GMT
// Server: AmazonS3
// Transfer-Encoding: chunked
// x-amz-error-code: AccessDenied
// x-amz-error-message: Access Denied
// x-amz-id-2: HteVr4cPi9iddwUdAifVTxLZcidlh
// e1yxO6mtr1lqaGRSW/lZlQMGLbIztWOTUcDP3vMA6PwpNE=
// x-amz-request-id: FD4EA11DD16537F5

// 2) If redirect rule, redirect with 301 status code.

// 3) If success, respond with object's headers:

// HTTP/1.1 200 OK
// Content-Length: 314
// Content-Type: text/html
// Date: Wed, 21 Dec 2016 20:32:52 GMT
// ETag: "6af6552e24eb4bdcc83f1b227dfc3dda"
// Last-Modified: Fri, 02 Dec 2016 18:06:55 GMT
// Server: AmazonS3
// x-amz-id-2: o2wNnLjNiRhiL83ji34IeV5vLV/kXoIN+nzh41XE/cz7+
// 8C5P3O3SIRj7PYNmhhJqE2NyDA2h5g=
// x-amz-meta-somekey: mymetadata!!!
// x-amz-request-id: 89BBCC95D4738024

// 4) If there is a redirect rule for an error, and get such error,
// redirect in accordance with rule:

// Called head with prefix zzz and got 403 so satisfied conditions for redirect
// HTTP/1.1 301 Moved Permanently
// Content-Length: 0
// Date: Thu, 22 Dec 2016 02:47:48 GMT
// Location: http://whatever.com.s3-website-us-east-1.amazonaws.com/zzz
// Server: AmazonS3
// x-amz-id-2: 5HXWYfdLQS8ZRBZJcKV1cxqxgKMTJzg74rGl61kRLA
// KX/MgqE4dZCJ4d9eF59Wbg/kza40cWcoA=
// x-amz-request-id: 0073330F58C7137C

describe('Head request on bucket website endpoint', () => {
    it('should return 404 when no such bucket', done => {
        const expectedHeaders = {
            'x-amz-error-code': 'NoSuchBucket',
            // Need arsenal fixed to remove period at the end
            // so compatible with aws
            'x-amz-error-message': 'The specified bucket does not exist.',
        };
        WebsiteConfigTester.makeHeadRequest(undefined, endpoint, 404,
            expectedHeaders, done);
    });

    describe('with existing bucket', () => {
        beforeEach(done => s3.createBucket({ Bucket: bucket }, done));

        afterEach(done => s3.deleteBucket({ Bucket: bucket }, done));

        it('should return 404 when no website configuration', done => {
            const expectedHeaders = {
                'x-amz-error-code': 'NoSuchWebsiteConfiguration',
                'x-amz-error-message': 'The specified bucket does not ' +
                    'have a website configuration',
            };
            WebsiteConfigTester.makeHeadRequest(undefined, endpoint, 404,
                expectedHeaders, done);
        });

        describe('with existing configuration', () => {
            beforeEach(done => {
                const webConfig = new WebsiteConfigTester('index.html');
                s3.putBucketWebsite({ Bucket: bucket,
                    WebsiteConfiguration: webConfig }, err => {
                    assert.strictEqual(err,
                        null, `Found unexpected err ${err}`);
                    s3.putObject({ Bucket: bucket, Key: 'index.html',
                        ACL: 'public-read',
                        Body: fs.readFileSync(path.join(__dirname,
                            '/websiteFiles/index.html')),
                        ContentType: 'text/html',
                        Metadata: {
                            test: 'value',
                        },
                    },
                        err => {
                            assert.strictEqual(err, null);
                            done();
                        });
                });
            });

            afterEach(done => {
                s3.deleteObject({ Bucket: bucket, Key: 'index.html' },
                err => done(err));
            });

            it('should return indexDocument headers if no key ' +
                'requested', done => {
                WebsiteConfigTester.makeHeadRequest(undefined, endpoint,
                    200, indexExpectedHeaders, done);
            });

            it('should return indexDocument headers if key requested', done => {
                WebsiteConfigTester.makeHeadRequest(undefined,
                    `${endpoint}/index.html`, 200, indexExpectedHeaders, done);
            });
        });

        describe('with path prefix in request with/without key', () => {
            beforeEach(done => {
                const webConfig = new WebsiteConfigTester('index.html');
                s3.putBucketWebsite({ Bucket: bucket,
                    WebsiteConfiguration: webConfig }, err => {
                    assert.strictEqual(err,
                        null, `Found unexpected err ${err}`);
                    s3.putObject({ Bucket: bucket,
                        Key: 'pathprefix/index.html',
                        ACL: 'public-read',
                        Body: fs.readFileSync(path.join(__dirname,
                            '/websiteFiles/index.html')),
                        ContentType: 'text/html',
                        Metadata: {
                            test: 'value',
                        },
                    }, done);
                });
            });

            afterEach(done => {
                s3.deleteObject({ Bucket: bucket, Key:
                    'pathprefix/index.html' },
                done);
            });

            it('should serve indexDocument if path request without key',
            done => {
                WebsiteConfigTester.makeHeadRequest(undefined,
                    `${endpoint}/pathprefix/`, 200, indexExpectedHeaders, done);
            });

            it('should serve indexDocument if path request with key',
            done => {
                WebsiteConfigTester.makeHeadRequest(undefined,
                    `${endpoint}/pathprefix/index.html`, 200,
                    indexExpectedHeaders, done);
            });
        });

        describe('with private key', () => {
            beforeEach(done => {
                const webConfig = new WebsiteConfigTester('index.html');
                s3.putBucketWebsite({ Bucket: bucket,
                    WebsiteConfiguration: webConfig }, err => {
                    assert.strictEqual(err,
                        null, `Found unexpected err ${err}`);
                    s3.putObject({ Bucket: bucket,
                        Key: 'index.html',
                        ACL: 'private',
                        Body: fs.readFileSync(path.join(__dirname,
                            '/websiteFiles/index.html')),
                        ContentType: 'text/html' }, done);
                });
            });

            afterEach(done => {
                s3.deleteObject({ Bucket: bucket, Key: 'index.html' }, done);
            });

            it('should return 403 if key is private', done => {
                const expectedHeaders = {
                    'x-amz-error-code': 'AccessDenied',
                    'x-amz-error-message': 'Access Denied',
                };
                WebsiteConfigTester.makeHeadRequest(undefined, endpoint, 403,
                    expectedHeaders, done);
            });
        });

        describe('with nonexisting index document key', () => {
            beforeEach(done => {
                const webConfig = new WebsiteConfigTester('index.html');
                s3.putBucketWebsite({ Bucket: bucket,
                    WebsiteConfiguration: webConfig }, done);
            });

            it('should return 403 if nonexisting index document key', done => {
                const expectedHeaders = {
                    'x-amz-error-code': 'AccessDenied',
                    'x-amz-error-message': 'Access Denied',
                };
                WebsiteConfigTester.makeHeadRequest(undefined, endpoint, 403,
                    expectedHeaders, done);
            });
        });

        describe(`redirect all requests to ${redirectEndpoint}`, () => {
            beforeEach(done => {
                const redirectAllTo = {
                    HostName: 'www.google.com',
                };
                const webConfig = new WebsiteConfigTester(null, null,
                  redirectAllTo);
                s3.putBucketWebsite({ Bucket: bucket,
                    WebsiteConfiguration: webConfig }, done);
            });

            it(`should redirect to ${redirectEndpoint}`, done => {
                const expectedHeaders = {
                    location: redirectEndpoint,
                };
                WebsiteConfigTester.makeHeadRequest(undefined,
                    endpoint, 301, expectedHeaders, done);
            });

            it(`should redirect to ${redirectEndpoint}about`, done => {
                const expectedHeaders = {
                    location: `${redirectEndpoint}about/`,
                };
                WebsiteConfigTester.makeHeadRequest(undefined,
                    `${endpoint}/about/`, 301, expectedHeaders, done);
            });
        });

        describe('redirect all requests to https://www.google.com ' +
            'since https protocol set in website config', () => {
            // Note: these tests will all redirect to https even if
            // conf does not have https since protocol in website config
            // specifies https
            beforeEach(done => {
                const redirectAllTo = {
                    HostName: 'www.google.com',
                    Protocol: 'https',
                };
                const webConfig = new WebsiteConfigTester(null, null,
                  redirectAllTo);
                s3.putBucketWebsite({ Bucket: bucket,
                    WebsiteConfiguration: webConfig }, done);
            });

            it('should redirect to https://google.com', done => {
                const expectedHeaders = {
                    location: 'https://www.google.com/',
                };
                WebsiteConfigTester.makeHeadRequest(undefined, endpoint,
                    301, expectedHeaders, done);
            });

            it('should redirect to https://google.com/about', done => {
                const expectedHeaders = {
                    location: 'https://www.google.com/about/',
                };
                WebsiteConfigTester.makeHeadRequest(undefined,
                    `${endpoint}/about/`, 301, expectedHeaders, done);
            });
        });

        describe('with custom error document', () => {
            beforeEach(done => {
                const webConfig = new WebsiteConfigTester('index.html',
                'error.html');
                s3.putBucketWebsite({ Bucket: bucket,
                    WebsiteConfiguration: webConfig }, err => {
                    assert.strictEqual(err,
                        null, `Found unexpected err ${err}`);
                    s3.putObject({ Bucket: bucket,
                        Key: 'error.html',
                        ACL: 'public-read',
                        Body: fs.readFileSync(path.join(__dirname,
                            '/websiteFiles/error.html')),
                        ContentType: 'text/html' }, done);
                });
            });

            afterEach(done => {
                s3.deleteObject({ Bucket: bucket, Key: 'error.html' }, done);
            });

            it('should return regular error headers regardless of whether ' +
                'custom error document', done => {
                const expectedHeaders = {
                    'x-amz-error-code': 'AccessDenied',
                    'x-amz-error-message': 'Access Denied',
                };
                WebsiteConfigTester.makeHeadRequest(undefined,
                    `${endpoint}/madeup`, 403, expectedHeaders, done);
            });
        });

        describe('redirect to hostname with error code condition', () => {
            beforeEach(done => {
                const webConfig = new WebsiteConfigTester('index.html');
                const condition = {
                    HttpErrorCodeReturnedEquals: '403',
                };
                const redirect = {
                    HostName: 'www.google.com',
                };
                webConfig.addRoutingRule(redirect, condition);
                s3.putBucketWebsite({ Bucket: bucket,
                    WebsiteConfiguration: webConfig }, done);
            });

            it(`should redirect to ${redirectEndpoint} if error 403` +
            ' occured', done => {
                const expectedHeaders = {
                    location: redirectEndpoint,
                };
                WebsiteConfigTester.makeHeadRequest(undefined, endpoint, 301,
                    expectedHeaders, done);
            });
        });

        describe('redirect to hostname with prefix condition', () => {
            beforeEach(done => {
                const webConfig = new WebsiteConfigTester('index.html');
                const condition = {
                    KeyPrefixEquals: 'about/',
                };
                const redirect = {
                    HostName: 'www.google.com',
                };
                webConfig.addRoutingRule(redirect, condition);
                s3.putBucketWebsite({ Bucket: bucket,
                    WebsiteConfiguration: webConfig }, done);
            });

            it(`should redirect to ${redirectEndpoint}about if ` +
            'key prefix is equal to "about"', done => {
                const expectedHeaders = {
                    location: `${redirectEndpoint}about/`,
                };
                WebsiteConfigTester.makeHeadRequest(undefined,
                    `${endpoint}/about/`, 301, expectedHeaders, done);
            });
        });

        describe('redirect to hostname with prefix and error condition',
        () => {
            beforeEach(done => {
                const webConfig = new WebsiteConfigTester('index.html');
                const condition = {
                    KeyPrefixEquals: 'about/',
                    HttpErrorCodeReturnedEquals: '403',
                };
                const redirect = {
                    HostName: 'www.google.com',
                };
                webConfig.addRoutingRule(redirect, condition);
                s3.putBucketWebsite({ Bucket: bucket,
                    WebsiteConfiguration: webConfig }, done);
            });

            it(`should redirect to ${redirectEndpoint} if ` +
            'key prefix is equal to "about" AND error code 403', done => {
                const expectedHeaders = {
                    location: `${redirectEndpoint}about/`,
                };
                WebsiteConfigTester.makeHeadRequest(undefined,
                    `${endpoint}/about/`, 301, expectedHeaders, done);
            });
        });

        describe('redirect with multiple redirect rules', () => {
            beforeEach(done => {
                const webConfig = new WebsiteConfigTester('index.html');
                const conditions = {
                    KeyPrefixEquals: 'about/',
                };
                const redirectOne = {
                    HostName: 'www.google.com',
                };
                const redirectTwo = {
                    HostName: 's3.google.com',
                };
                webConfig.addRoutingRule(redirectOne, conditions);
                webConfig.addRoutingRule(redirectTwo, conditions);
                s3.putBucketWebsite({ Bucket: bucket,
                    WebsiteConfiguration: webConfig }, done);
            });

            it('should redirect based on first rule', done => {
                const expectedHeaders = {
                    location: `${redirectEndpoint}about/`,
                };
                WebsiteConfigTester.makeHeadRequest(undefined,
                    `${endpoint}/about/`, 301, expectedHeaders, done);
            });
        });

        describe('redirect with protocol',
        () => {
            beforeEach(done => {
                const webConfig = new WebsiteConfigTester('index.html');
                const condition = {
                    KeyPrefixEquals: 'about/',
                };
                const redirect = {
                    Protocol: 'https',
                    HostName: 'www.google.com',
                };
                webConfig.addRoutingRule(redirect, condition);
                s3.putBucketWebsite({ Bucket: bucket,
                    WebsiteConfiguration: webConfig }, done);
            });

            it('should redirect to https://www.google.com/about if ' +
            'https protocol specified', done => {
                const expectedHeaders = {
                    location: 'https://www.google.com/about/',
                };
                WebsiteConfigTester.makeHeadRequest(undefined,
                    `${endpoint}/about/`, 301, expectedHeaders, done);
            });
        });

        describe('redirect to key using ReplaceKeyWith', () => {
            beforeEach(done => {
                const webConfig = new WebsiteConfigTester('index.html');
                const condition = {
                    HttpErrorCodeReturnedEquals: '403',
                };
                const redirect = {
                    ReplaceKeyWith: 'redirect.html',
                };
                webConfig.addRoutingRule(redirect, condition);
                s3.putBucketWebsite({ Bucket: bucket,
                    WebsiteConfiguration: webConfig }, done);
            });

            afterEach(done => {
                s3.deleteObject({ Bucket: bucket, Key: 'redirect.html' },
                err => done(err));
            });

            it('should redirect to specified file if 403 error ' +
                'error occured', done => {
                const expectedHeaders = {
                    location: `${endpoint}/redirect.html`,
                };
                WebsiteConfigTester.makeHeadRequest(undefined, endpoint, 301,
                    expectedHeaders, done);
            });
        });

        describe('redirect using ReplaceKeyPrefixWith', () => {
            beforeEach(done => {
                const webConfig = new WebsiteConfigTester('index.html');
                const condition = {
                    HttpErrorCodeReturnedEquals: '403',
                };
                const redirect = {
                    HostName: 'www.google.com',
                    ReplaceKeyPrefixWith: 'about',
                };
                webConfig.addRoutingRule(redirect, condition);
                s3.putBucketWebsite({ Bucket: bucket,
                    WebsiteConfiguration: webConfig }, done);
            });

            it(`should redirect to ${redirectEndpoint}about if ` +
            'ReplaceKeyPrefixWith equals "about"', done => {
                const expectedHeaders = {
                    location: `${redirectEndpoint}about`,
                };
                WebsiteConfigTester.makeHeadRequest(undefined, endpoint, 301,
                    expectedHeaders, done);
            });
        });

        describe('redirect requests with prefix /about to redirect/',
        () => {
            beforeEach(done => {
                const webConfig = new WebsiteConfigTester('index.html');
                const condition = {
                    KeyPrefixEquals: 'about/',
                };
                const redirect = {
                    ReplaceKeyPrefixWith: 'redirect/',
                };
                webConfig.addRoutingRule(redirect, condition);
                s3.putBucketWebsite({ Bucket: bucket,
                    WebsiteConfiguration: webConfig }, done);
            });

            afterEach(done => {
                s3.deleteObject({ Bucket: bucket, Key: 'redirect/index.html' },
                err => done(err));
            });

            it('should redirect to "redirect/" object if key prefix is equal ' +
                'to "about/"', done => {
                const expectedHeaders = {
                    location: `${endpoint}/redirect/`,
                };
                WebsiteConfigTester.makeHeadRequest(undefined,
                    `${endpoint}/about/`, 301, expectedHeaders, done);
            });
        });

        describe('redirect requests, with both prefix and error code ' +
            'condition', () => {
            beforeEach(done => {
                const webConfig = new WebsiteConfigTester('index.html');
                const condition = {
                    KeyPrefixEquals: 'about/',
                    HttpErrorCodeReturnedEquals: '403',
                };
                const redirect = {
                    ReplaceKeyPrefixWith: 'redirect/',
                };
                webConfig.addRoutingRule(redirect, condition);
                s3.putBucketWebsite({ Bucket: bucket,
                    WebsiteConfiguration: webConfig }, done);
            });

            afterEach(done => {
                s3.deleteObject({ Bucket: bucket, Key: 'redirect/index.html' },
                err => done(err));
            });

            it('should redirect to "redirect" object if key prefix is equal ' +
                'to "about/" and there is a 403 error satisfying the ' +
                'condition in the redirect rule',
            done => {
                const expectedHeaders = {
                    location: `${endpoint}/redirect/`,
                };
                WebsiteConfigTester.makeHeadRequest(undefined,
                    `${endpoint}/about/`, 301, expectedHeaders, done);
            });
        });
    });
});


text:
package org.locationtech.geowave.core.store.data;

import java.util.Map;

public interface PersistentDataset<T> {

  /**
   * Add the field ID/value pair to this data set. Do not overwrite.
   *
   * @param value the field ID/value pair to add
   */
  void addValue(String fieldName, T value);

  /** Add several values to the data set. */
  void addValues(Map<String, T> values);

  /**
   * Given a field ID, get the associated value
   *
   * @param fieldName the field ID
   * @return the stored field value, null if this does not contain a value for the ID
   */
  T getValue(String fieldName);

  /**
   * Get all of the values from this persistent data set
   *
   * @return all of the value
   */
  Map<String, T> getValues();
}

redpajama_set_name: RedPajamaGithub


text:
import time
import os
from twisted.python import log
from twisted.internet import defer, utils

from buildbot import config
from buildbot.util import deferredLocked
from buildbot.changes import base
from buildbot.util import epoch2datetime

class HgPoller(base.PollingChangeSource):
    """This source will poll a remote hg repo for changes and submit
    them to the change master."""

    compare_attrs = ["repourl", "branch", "workdir",
                     "pollInterval", "hgpoller", "usetimestamps",
                     "category", "project"]

    db_class_name = 'HgPoller'

    def __init__(self, repourl, branch='default',
                 workdir=None, pollInterval=10*60,
                 hgbin='hg', usetimestamps=True,
                 category=None, project='', pollinterval=-2,
                 encoding='utf-8'):

        # for backward compatibility; the parameter used to be spelled with 'i'
        if pollinterval != -2:
            pollInterval = pollinterval

        self.repourl = repourl
        self.branch = branch
        base.PollingChangeSource.__init__(
            self, name=repourl, pollInterval=pollInterval)
        self.encoding = encoding
        self.lastChange = time.time()
        self.lastPoll = time.time()
        self.hgbin = hgbin
        self.workdir = workdir
        self.usetimestamps = usetimestamps
        self.category = category
        self.project = project
        self.commitInfo  = {}
        self.initLock = defer.DeferredLock()

        if self.workdir == None:
            config.error("workdir is mandatory for now in HgPoller")

    def describe(self):
        status = ""
        if not self.master:
            status = "[STOPPED - check log]"
        return ("HgPoller watching the remote Mercurial repository %r, "
                "branch: %r, in workdir %r %s") % (self.repourl, self.branch,
                                                   self.workdir, status)

    @deferredLocked('initLock')
    def poll(self):
        d = self._getChanges()
        d.addCallback(self._processChanges)
        d.addErrback(self._processChangesFailure)
        return d

    def _absWorkdir(self):
        workdir = self.workdir
        if os.path.isabs(workdir):
            return workdir
        return os.path.join(self.master.basedir, workdir)

    def _getRevDetails(self, rev):
        """Return a deferred for (date, author, files, comments) of given rev.

        Deferred will be in error if rev is unknown.
        """
        args = ['log', '-r', rev, os.linesep.join((
            '--template={date|hgdate}',
            '{author}',
            '{files}',
            '{desc|strip}'))]
        # Mercurial fails with status 255 if rev is unknown
        d = utils.getProcessOutput(self.hgbin, args, path=self._absWorkdir(),
                                   env=os.environ, errortoo=False )
        def process(output):
            # fortunately, Mercurial issues all filenames one one line
            date, author, files, comments = output.decode(self.encoding, "replace").split(
                os.linesep, 3)

            if not self.usetimestamps:
                stamp = None
            else:
                try:
                    stamp = float(date.split()[0])
                except:
                    log.msg('hgpoller: caught exception converting output %r '
                            'to timestamp' % date)
                    raise
            return stamp, author.strip(), files.split(), comments.strip()

        d.addCallback(process)
        return d

    def _isRepositoryReady(self):
        """Easy to patch in tests."""
        return os.path.exists(os.path.join(self._absWorkdir(), '.hg'))

    def _initRepository(self):
        """Have mercurial init the workdir as a repository (hg init) if needed.

        hg init will also create all needed intermediate directories.
        """
        if self._isRepositoryReady():
            return defer.succeed(None)
        log.msg('hgpoller: initializing working dir from %s' % self.repourl)
        d = utils.getProcessOutputAndValue(self.hgbin,
                                           ['init', self._absWorkdir()],
                                           env=os.environ)
        d.addCallback(self._convertNonZeroToFailure)
        d.addErrback(self._stopOnFailure)
        d.addCallback(lambda _ : log.msg(
            "hgpoller: finished initializing working dir %r" % self.workdir))
        return d

    def _getChanges(self):
        self.lastPoll = time.time()

        d = self._initRepository()
        d.addCallback(lambda _ : log.msg(
            "hgpoller: polling hg repo at %s" % self.repourl))

        # get a deferred object that performs the fetch
        args = ['pull', '-b', self.branch, self.repourl]

        # This command always produces data on stderr, but we actually do not
        # care about the stderr or stdout from this command.
        # We set errortoo=True to avoid an errback from the deferred.
        # The callback which will be added to this
        # deferred will not use the response.
        d.addCallback(lambda _: utils.getProcessOutput(
            self.hgbin, args, path=self._absWorkdir(),
            env=os.environ, errortoo=True))

        return d

    def _getStateObjectId(self):
        """Return a deferred for object id in state db.

        Being unique among pollers, workdir is used with branch as instance
        name for db.
        """
        return self.master.db.state.getObjectId(
            '#'.join((self.workdir, self.branch)), self.db_class_name)

    def _getCurrentRev(self):
        """Return a deferred for object id in state db and current numeric rev.

        If never has been set, current rev is None.
        """
        d = self._getStateObjectId()
        def oid_cb(oid):
            d = self.master.db.state.getState(oid, 'current_rev', None)
            def addOid(cur):
                if cur is not None:
                    return  oid, int(cur)
                return oid, cur
            d.addCallback(addOid)
            return d
        d.addCallback(oid_cb)
        return d

    def _setCurrentRev(self, rev, oid=None):
        """Return a deferred to set current revision in persistent state.

        oid is self's id for state db. It can be passed to avoid a db lookup."""
        if oid is None:
            d = self._getStateObjectId()
        else:
            d = defer.succeed(oid)

        def set_in_state(obj_id):
            return self.master.db.state.setState(obj_id, 'current_rev', rev)
        d.addCallback(set_in_state)

        return d

    def _getHead(self):
        """Return a deferred for branch head revision or None.

        We'll get an error if there is no head for this branch, which is
        proabably a good thing, since it's probably a mispelling
        (if really buildbotting a branch that does not have any changeset
        yet, one shouldn't be surprised to get errors)
        """
        d = utils.getProcessOutput(self.hgbin,
                    ['heads', self.branch, '--template={rev}' + os.linesep],
                    path=self._absWorkdir(), env=os.environ, errortoo=False)

        def no_head_err(exc):
            log.err("hgpoller: could not find branch %r in repository %r" % (
                self.branch, self.repourl))
        d.addErrback(no_head_err)

        def results(heads):
            if not heads:
                return

            if len(heads.split()) > 1:
                log.err(("hgpoller: caught several heads in branch %r "
                         "from repository %r. Staying at previous revision"
                         "You should wait until the situation is normal again "
                         "due to a merge or directly strip if remote repo "
                         "gets stripped later.") % (self.branch, self.repourl))
                return

            # in case of whole reconstruction, are we sure that we'll get the
            # same node -> rev assignations ?
            return int(heads.strip())

        d.addCallback(results)
        return d

    @defer.inlineCallbacks
    def _processChanges(self, unused_output):
        """Send info about pulled changes to the master and record current.

        GitPoller does the recording by moving the working dir to the head
        of the branch.
        We don't update the tree (unnecessary treatment and waste of space)
        instead, we simply store the current rev number in a file.
        Recall that hg rev numbers are local and incremental.
        """
        oid, current = yield self._getCurrentRev()
        # hg log on a range of revisions is never empty
        # also, if a numeric revision does not exist, a node may match.
        # Therefore, we have to check explicitely that branch head > current.
        head = yield self._getHead()
        if head <= current:
            return
        if current is None:
            # we could have used current = -1 convention as well (as hg does)
            revrange = '%d:%d' % (head, head)
        else:
            revrange = '%d:%s' % (current + 1, head)

        # two passes for hg log makes parsing simpler (comments is multi-lines)
        revListArgs = ['log', '-b', self.branch, '-r', revrange,
                       r'--template={rev}:{node}\n']
        results = yield utils.getProcessOutput(self.hgbin, revListArgs,
                    path=self._absWorkdir(), env=os.environ, errortoo=False )

        revNodeList = [rn.split(':', 1) for rn in results.strip().split()]

        log.msg('hgpoller: processing %d changes: %r in %r'
                % (len(revNodeList), revNodeList, self._absWorkdir()))
        for rev, node in revNodeList:
            timestamp, author, files, comments = yield self._getRevDetails(
                node)
            yield self.master.addChange(
                   author=author,
                   revision=node,
                   files=files,
                   comments=comments,
                   when_timestamp=epoch2datetime(timestamp),
                   branch=self.branch,
                   category=self.category,
                   project=self.project,
                   repository=self.repourl,
                   src='hg')
            # writing after addChange so that a rev is never missed,
            # but at once to avoid impact from later errors
            yield self._setCurrentRev(rev, oid=oid)

    def _processChangesFailure(self, f):
        log.msg('hgpoller: repo poll failed')
        log.err(f)
        # eat the failure to continue along the defered chain - we still want to catch up
        return None

    def _convertNonZeroToFailure(self, res):
        "utility method to handle the result of getProcessOutputAndValue"
        (stdout, stderr, code) = res
        if code != 0:
            raise EnvironmentError('command failed with exit code %d: %s' % (code, stderr))
        return (stdout, stderr, code)

    def _stopOnFailure(self, f):
        "utility method to stop the service when a failure occurs"
        if self.running:
            d = defer.maybeDeferred(lambda : self.stopService())
            d.addErrback(log.err, 'while stopping broken HgPoller service')
        return f


text:
package io.botcoin.task;

import io.botcoin.global.Global;
import io.botcoin.global.Settings;
import io.botcoin.utils.Utils;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.NoRouteToHostException;
import java.net.URL;
import java.net.UnknownHostException;

/**
 *
 * @author Nicolò Paternoster <paternoster.nicolo at gmail.com>
 */

public class ConnectionThread implements Runnable
{
        public static final String ONLINE_CHECK_MTGOX = "http://data.mtgox.com";
        public static final String ONLINE_CHECK_BTCE ="http://btc-e.com";
        public static final String ONLINE_CHECK_BITSTAMP ="https://www.bitstamp.net";
	private Thread th = null;

	public ConnectionThread(){
		start();
	}

	public void start(){
		if(th==null){
			th = new Thread(this);
			th.start();
		}
	}

	public void run()
	{
		while(th!=null){
			Global.connectionDetection = false;
                        checkConnection();

		}
	 }

        public void forceCheck()
        {
            checkConnection();
        }

    private void checkConnection() {
            //Test for conections

           //TODO ... not sure whether this is always necessary
           Global.MtgoxMarket.setConnected(isConnectedTo(ONLINE_CHECK_MTGOX));
           Global.BtceMarket.setConnected(isConnectedTo(ONLINE_CHECK_BTCE));
           Global.BitstampMarket.setConnected(isConnectedTo(ONLINE_CHECK_BITSTAMP));

            Global.connectionDetection = true;

            try {
                  th.sleep(Settings.PING_TIME);
            }
            catch (InterruptedException e) {
                  e.printStackTrace();
           }
    }

    private boolean isConnectedTo(String url)
    {
        boolean connected = false;
        HttpURLConnection connection=null;
        URL query = null;
        try {
               query = new URL(url);
        } catch (MalformedURLException ex) {
               Utils.log(ex,Utils.LOG_ERR);
        }
        try{
               connection = (HttpURLConnection)query.openConnection();
               connection.setRequestMethod("POST");
               connection.setDoOutput(true);
               connection.setDoInput(true);
               connection.getOutputStream();
               connected=true;
        }
        catch( NoRouteToHostException | UnknownHostException ex){
               connected = false;
               //TODO I suspect here I should reset the connection somehow (?=null?)
               }
        catch(IOException ex){
               Utils.log(ex,Utils.LOG_ERR);
                }
        return connected;
    }
}


text:
package org.testobject.matching.image;

import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;

import org.opencv.core.CvType;
import org.opencv.core.Mat;

/**
 *
 * @author enijkamp, lbielski
 *
 */
public class OpenCV {

	public static BufferedImage createBufferedImage(int w, int h)
	{
		ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
		int[] nBits = { 8, 8, 8, 8 };
		ColorModel cm = new ComponentColorModel(cs, nBits,
				true, false,
				Transparency.TRANSLUCENT,
				DataBuffer.TYPE_BYTE);

		SampleModel sm = cm.createCompatibleSampleModel(w, h);
		DataBufferByte db = new DataBufferByte(w * h * 4); //4 channels buffer
		WritableRaster r = WritableRaster.createWritableRaster(sm, db, new Point(0, 0));
		BufferedImage bm = new BufferedImage(cm, r, false, null);
		return bm;
	}

	public static byte[] convertBufferedImageToByteArray(BufferedImage img) {
		BufferedImage cvImg = createBufferedImage(img.getWidth(), img.getHeight());
		Graphics2D g = cvImg.createGraphics();
		g.drawImage(img, 0, 0, null);
		g.dispose();
		return ((DataBufferByte) cvImg.getRaster().getDataBuffer()).getData();
	}

	public static Mat convertBufferedImageToMat(BufferedImage img) {
		byte[] data = convertBufferedImageToByteArray(img);

		Mat mat = new Mat(img.getHeight(), img.getWidth(), CvType.CV_8UC4);
		mat.put(0, 0, data);

		return mat;
	}

	public static BufferedImage matToBufferedImage(Mat bgr) {
		int width = bgr.width();
		int height = bgr.height();
		BufferedImage image;
		WritableRaster raster;

		if (bgr.channels() == 1) {
			image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
			raster = image.getRaster();

			byte[] px = new byte[1];

			for (int y = 0; y < height; y++) {
				for (int x = 0; x < width; x++) {
					bgr.get(y, x, px);
					raster.setSample(x, y, 0, px[0]);
				}
			}
		} else if(bgr.channels() == 3){
			image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			raster = image.getRaster();

			byte[] px = new byte[3];
			int[] rgb = new int[3];

			for (int y = 0; y < height; y++) {
				for (int x = 0; x < width; x++) {
					bgr.get(y, x, px);
					rgb[0] = px[2];
					rgb[1] = px[1];
					rgb[2] = px[0];
					raster.setPixel(x, y, rgb);
				}
			}
		} else {
			image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			raster = image.getRaster();

			byte[] px = new byte[4];
			int[] rgb = new int[4];

			for (int y = 0; y < height; y++) {
				for (int x = 0; x < width; x++) {
					bgr.get(y, x, px);
					rgb[0] = px[0];
					rgb[1] = px[1];
					rgb[2] = px[2];
					rgb[3] = px[3];
					raster.setPixel(x, y, rgb);
				}
			}
		}

		return image;
	}

}


text:
{{ formatted_date($date) }}

        @forelse($incidents as $incidentID => $incident)

status }}" data-toggle="tooltip" title="{{ $incident->humanStatus }}" data-placement="left">
                        icon }}">

                            @if($loggedUser)

                                id }}/edit" class="btn btn-default">{{ trans('forms.edit') }}
                                id }}/delete" class="btn btn-danger confirm-action" data-method='DELETE'>{{ trans('forms.delete') }}

                            @endif
                            {{ $incident->name }}{{ $incident->isScheduled ? trans("cachet.incidents.scheduled_at", ["timestamp" => $incident->scheduled_at_diff]) : null }}

                                created_at_formatted }}" data-timeago="{{ $incident->created_at_iso }}">

                            {!! $incident->formattedMessage !!}

        @empty

{{ trans('cachet.incidents.none') }}

        @endforelse


text:
package com.zhy.authproject.module.login;

import dagger.Subcomponent;

/**
 * Created by zhanghaoye on 10/21/16.
 */
@Subcomponent(modules = LoginModule.class)
public interface LoginComponent {
    LoginActivity inject(LoginActivity loginActivity);
}


text:
PHP-Survey-System
=================

Basic form driven survey system.

Just a simple PHP survey system developed using PEAR, FPDF, and a couple other libraries.

Developed back in early 2008.


text:
package org.apache.pulsar.admin.cli.utils;

import java.nio.charset.StandardCharsets;
import org.apache.pulsar.client.api.Schema;
import org.apache.pulsar.client.api.schema.SchemaDefinition;

public class SchemaExtractor {

    public static String getJsonSchemaInfo(SchemaDefinition schemaDefinition) {

        return new String(Schema.JSON(schemaDefinition).getSchemaInfo().getSchema(),
                          StandardCharsets.UTF_8);
    }

    public static String getAvroSchemaInfo(SchemaDefinition schemaDefinition) {

        return new String(Schema.AVRO(schemaDefinition).getSchemaInfo().getSchema(),
                          StandardCharsets.UTF_8);
    }

}


text:
package grid;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import point.Grid;
import point.Point;

public class AnalyzeGridMapper extends
		Mapper<LongWritable, Text, IntWritable, IntWritable> {

	@Override
	public void map(LongWritable key, Text value, Context context)
			throws IOException, InterruptedException {
		String valueAsString = value.toString();
		String keyAsString = valueAsString.substring(0,valueAsString
				.indexOf("\t"));
		int oKey = Integer.parseInt(keyAsString);
		IntWritable outValue = new IntWritable(1);
		IntWritable outKey = new IntWritable(oKey);
		context.write(outKey, outValue);

	}
}


text:
import { createQueue, Queue } from "./queue";
import { } from "./pump";

export const tee = (source: AsyncIterableIterator<any>): [AsyncIterableIterator<any>, AsyncIterableIterator<any>] => {

  const inputs: Queue<any>[] = [];
  let _running: boolean;

  const start = () => {
    if (_running) {
      return;
    }
    _running = true;

    const next = () => {
      source.next().then(({ value, done }) => {
        for (const input of inputs) {
          if (done) {
            input.return();
          } else {
            input.unshift(value);
          }
        }
        if (!done) {
          next();
        }
      });
    };
    next();
  }

  const createSpare = () => {
    const input = createQueue();
    inputs.push(input);

    return {
      [Symbol.asyncIterator]: () => this,
      next(value) {
        start();
        return input.next();
      }
    }
  }

  return [
    createSpare(),
    createSpare()
  ];
};


text:
<!DOCTYPE html>
{% load i18n %}

		<meta charset="utf-8">
		<title>{{ settings.SITE_NAME }}{% block title %}{% endblock %}</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta name="author" content="{{ settings.AUTHOR_NAME }}">
		{% block extra_meta %}{% endblock %}
		{% block rss %}
		{% endblock %}
		<link rel="alternate" type="application/rss+xml" title="{% trans "Comments-Feed" %}" href="/feeds/comments/" />
		{% if settings.ENABLE_LIVESTREAMS %}
		<link rel="alternate" type="application/rss+xml" title="{% trans "Upcoming Events" %}" href="/feeds/stream/upcoming/" />
		{% endif %}

		<link href="{{ STATIC_URL }}bootstrap/css/bootstrap.min.css" rel="stylesheet">
		<link href="{{ STATIC_URL }}bootstrap/css/custom_style.css" rel="stylesheet">

		{% block head %}
		{% endblock %}

				<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-nav-collapse">

				</button>
				{{ settings.SITE_NAME }}

 {% trans "Portal" %}

					{% if settings.ENABLE_LIVESTREAMS %}

{% trans "Live" %}

					{% endif %}
					{% for page in page_list %}

						{% if page.display == "body" %}
						 {{ page.title }}
						{% else %}
						 {{ page.title }}
						{% endif %}

					{% endfor %}

				<form class="navbar-form navbar-left" role="search" method="GET" action="/search/">

						<input type="text" class="form-control" placeholder="{% trans "Search" %}" name="q">

				</form>

					{% include "nav.html" %}

			{% block body %}{% endblock %}

		{% block javascript %}{% endblock %}


text:
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Reader (ReaderT, runReaderT)
import Data.Maybe (listToMaybe)
import Data.Text (unpack)
import Data.Time.Clock (getCurrentTime)
import Twitter.Action
import Twitter.OAuth
import Web.Authenticate.OAuth (Credential)

-- Autorespond to the last person that mentioned the user
-- Tweets if that hasn't happened
autorespondToFirstMention :: ReaderT Credential IO ()
autorespondToFirstMention = do
    eMentions <- mentions
    case eMentions of
         Left err -> do
             liftIO $ putStrLn "There was an error when getting the mentions"
             liftIO $ putStrLn err
         Right m  -> do
             let mLatest = listToMaybe m -- Last person to mention the user
             case mLatest of
                  Nothing -> do
                      liftIO $ putStrLn $ "No one has mentioned me! " ++
                          "Gotta let the world know"
                      eTweet <- sendTweet "No one has mentioned me!!"
                      liftIO $ print eTweet
                  Just tweet -> do
                      currentTime <- liftIO getCurrentTime
                      let username = (unpack . screen_name . user) tweet
                          tweetID = Twitter.Action.id tweet
                          msg = "oh yeah? " ++ show currentTime ++ "!"
                      liftIO $ putStrLn $ "Replying to " ++ username ++ "!"
                      eReply <- replyTweet tweetID msg
                      liftIO $ print eReply

main :: IO ()
main = login >>= \accessToken -> flip runReaderT accessToken $ do
    friends <- friendList "McCain"
    liftIO $ putStrLn "My friend list:"
    liftIO $ print friends
    followers <- followerList "McCain"
    liftIO $ putStrLn "My followers:"
    liftIO $ print followers
    liftIO $ putStrLn "Time to tweet!"
    autorespondToFirstMention


text:
Public Class AddThisControl
    Inherits Literal
#Else
    <ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never), ComponentModel.ToolboxItem(False)> _
    Public Class AddThisControl
        Inherits Literal
#End If
        Public DefaultButtonIcons As New List(Of String)

        Private _username As String = "xa-4b944e241ce5319f"

        '''
        ''' Property to get/set the Username
        '''
        ''' <value>
        ''' Username string passed to the set method
        ''' </value>
        ''' <returns>
        ''' Username string returned by the get method
        ''' </returns>
        ''' <remarks></remarks>
        <System.ComponentModel.Description("Property to get/set the Username")> _
        Public Property Username() As String
            Get
                Return _username
            End Get
            Set(ByVal value As String)
                _username = value
            End Set
        End Property

        Private _text_insturction As String = "Share"

        '''
        ''' Property to get/set the Text Instruction
        '''
        ''' <value>
        ''' Text instruction string passed to the set method
        ''' </value>
        ''' <returns>
        ''' Text instruction string returned by the get method
        ''' </returns>
        ''' <remarks></remarks>
        <System.ComponentModel.Description("Property to get/set the Text Instruction")> _
        Public Property TextInstruction() As String
            Get
                Return _text_insturction
            End Get
            Set(ByVal value As String)
                _text_insturction = value
            End Set
        End Property

        Private Sub AddThisControl_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
            DefaultButtonIcons.Add("email")
            DefaultButtonIcons.Add("print")
            DefaultButtonIcons.Add("facebook")
            DefaultButtonIcons.Add("twitter")
        End Sub

        Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
            Me.Text = " " & vbCrLf & _
                "
 " & vbCrLf & _
                "" & TextInstruction & " " & vbCrLf & _
                "| " & vbCrLf

            For Each service As String In DefaultButtonIcons
                Me.Text &= " " & vbCrLf
            Next

            Me.Text &= "
 " & vbCrLf & " " & vbCrLf
            '_
            '    " " & _
            '    vbCrLf &
            MyBase.Render(writer)
        End Sub

        Private Sub AddThisControl_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Page.ClientScript.RegisterClientScriptInclude("addthis", "http://s7.addthis.com/js/250/addthis_widget.js#username=xa-4b944e241ce5319f")
        End Sub

    End Class


text:
#ifndef __PRINTER_MAIN_H
#define __PRINTER_MAIN_H

#include <freerdp/channels/rdpdr.h>

typedef struct rdp_printer_driver rdpPrinterDriver;
typedef struct rdp_printer rdpPrinter;
typedef struct rdp_print_job rdpPrintJob;

typedef rdpPrinter** (*pcEnumPrinters) (rdpPrinterDriver* driver);
typedef rdpPrinter* (*pcGetPrinter) (rdpPrinterDriver* driver, const char* name, const char* driverName);

struct rdp_printer_driver
{
	pcEnumPrinters EnumPrinters;
	pcGetPrinter GetPrinter;
};

typedef rdpPrintJob* (*pcCreatePrintJob) (rdpPrinter* printer, UINT32 id);
typedef rdpPrintJob* (*pcFindPrintJob) (rdpPrinter* printer, UINT32 id);
typedef void (*pcFreePrinter) (rdpPrinter* printer);

struct rdp_printer
{
	int id;
	char* name;
	char* driver;
	BOOL is_default;

	pcCreatePrintJob CreatePrintJob;
	pcFindPrintJob FindPrintJob;
	pcFreePrinter Free;
};

typedef UINT (*pcWritePrintJob) (rdpPrintJob* printjob, BYTE* data, int size);
typedef void (*pcClosePrintJob) (rdpPrintJob* printjob);

struct rdp_print_job
{
	UINT32 id;
	rdpPrinter* printer;

	pcWritePrintJob Write;
	pcClosePrintJob Close;
};

#endif


text:
package io.github.ddebree.game.ai.tictactoe;

import io.github.ddebree.game.ai.core.executor.gameover.IGameOverTester;
import io.github.ddebree.game.ai.core.player.TwoPlayerKey;

import java.util.Optional;

public class GameOverTester implements IGameOverTester<State, TwoPlayerKey> {

    private static final Move[][] BOARD_LINES = new Move[][]{
            //Crosses:
            { Move.TOP_LEFT, Move.MIDDLE_MIDDLE, Move.BOTTOM_RIGHT },
            { Move.BOTTOM_LEFT, Move.MIDDLE_MIDDLE, Move.TOP_RIGHT },

            //Vertical:
            { Move.TOP_LEFT, Move.MIDDLE_LEFT, Move.BOTTOM_LEFT},
            { Move.TOP_MIDDLE, Move.MIDDLE_MIDDLE, Move.BOTTOM_MIDDLE },
            { Move.TOP_RIGHT, Move.MIDDLE_RIGHT, Move.BOTTOM_RIGHT},

            //Horizontal:
            { Move.TOP_LEFT, Move.TOP_MIDDLE, Move.TOP_RIGHT },
            { Move.MIDDLE_LEFT, Move.MIDDLE_MIDDLE, Move.MIDDLE_RIGHT },
            { Move.BOTTOM_LEFT, Move.BOTTOM_MIDDLE, Move.BOTTOM_RIGHT }
    };

    public boolean isGameOver(State state) {
        return getWinner(state).isPresent() || state.getOccupiedPoints().size() == Move.values().length;
    }

    @Override
    public Optional<TwoPlayerKey> getWinner(State state) {
        for (Move[] boardLine : BOARD_LINES) {
            TwoPlayerKey player0 = state.getOccupiedPoints().get(boardLine[0]);
            if (player0 != null
                    && player0 == state.getOccupiedPoints().get(boardLine[1])
                    && player0 == state.getOccupiedPoints().get(boardLine[2])) {
                return Optional.of(player0);
            }
        }
        return Optional.empty();
    }

}


text:
tx.cms-autologin
================

A component for the Tuxion CMS that creates autologin links.
* Passwords are not revealed through generated links.
* Expiration dates can be set for each link.
* When a link is expired, the regular login screen will be displayed.
* Login links will not be generated nor usable for administrator accounts, to prevent compromised administrator accounts.

Note: this component depends on the Tuxion CMS and the `account` component.

Warning and disclaimer
----------------------

The only reason this component exists is that in some situations it provides more user-friendliness, however we suggest you refrain from using it.
Because a login link generated with this component gives full access to an account it's a security risk that you should take seriously.
A generated link is much less safe than using the built in e-mail/username and password login system of the Tuxion CMS.
If your website deals with any sensitive data at all that your users have access to we highly recommend you do not install this component.
If you are unsure about the risks or whether your website deals with sensitive information, please do not install this component.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. For full details see the `LICENCE` file.


text:
/*
 * Remote Block Device - Storage Daemon
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include "proto.h"
#include "sd.h"

storage_t sd_storage;
pid_t childpid;

void usage(void) {
    printf("Usage: sd [-p PORT] FILE\n\n");
    printf("PORT - device TCP listening port. default: %d\n", SDPORT);
    printf("FILE - storage daemon file\n");
    exit(2);
}

void sigchld_handler(int s)
{
}

int main(int argc, char **argv)
{
    int sockfd, new_fd;
    struct sockaddr_in locaddr;
    struct sockaddr_in remaddr;
    socklen_t sin_size;
    struct sigaction sa;
    int yes=1;
    int sd_port = SDPORT;
    int c;
    int rv = 0;
    int status;
    pid_t pid;

    if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
        perror("SD: error creating socket");
        exit(1);
    }

    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
        perror("SD: error stting socket as reusable");
        exit(1);
    }

    while ((c = getopt(argc, argv, "p:")) != -1)
        switch (c) {
            case 'p':
                sd_port = atoi(optarg);
                break;
            default:
                return 2;
        }

    if (argc == optind)
        usage();

    if (storage_load(&sd_storage, argv[optind])) {
        perror("SD: error loading SD file");
        exit(1);
    } else
        printf("SD: storage file loaded succesfully: %s\n", argv[optind]);

    locaddr.sin_family = AF_INET;
    locaddr.sin_port = htons(sd_port);
    locaddr.sin_addr.s_addr = INADDR_ANY;
    memset(&(locaddr.sin_zero), '\0', 8);

    if (bind(sockfd, (struct sockaddr *)&locaddr, sizeof(struct sockaddr))== -1) {
        perror("SD: bind error");
        exit(1);
    }

    if (listen(sockfd, 1) == -1) {
        perror("SD: listen error");
        exit(1);
    }

    sa.sa_handler = sigchld_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGCHLD, &sa, NULL) == -1) {
        perror("SD: error setting handler for SIGCHLD");
        exit(1);
    }

    while(1) {
        sin_size = sizeof(struct sockaddr_in);
        printf("SD: accept | port=%d\n", sd_port);
        if ((new_fd = accept(sockfd, (struct sockaddr *)&remaddr, &sin_size)) == -1) {
            perror("SD: unable to accept connections");
            continue;
        }
        printf("SD: new connection from: %s\n", inet_ntoa(remaddr.sin_addr));

        pid = waitpid(WAIT_ANY, &status, WNOHANG);
        if (errno != ECHILD)
            kill(childpid, SIGTERM);

        childpid = fork();
        if (!childpid) {
            close(sockfd);
            while(!rv) {
                rv = storage_process(&sd_storage, new_fd);
            }
            printf("SD: closing connection from: %s\n", inet_ntoa(remaddr.sin_addr));
            close(new_fd);
            exit(0);
        }
        close(new_fd);

    }

    storage_free(&sd_storage);
    return 0;
}


text:
<!--
  #%L
  Fuse Patch :: Distro :: Standalone
  %%
  Copyright (C) 2015 Private
  %%
  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.
  #L%
  -->
<assembly
    xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">

    <formats>
        <format>zip</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>

    <fileSets>
        <fileSet>
            <directory>target/fuse-patch-${project.version}</directory>
            <outputDirectory>fuse-patch-${project.version}</outputDirectory>
        </fileSet>
    </fileSets>
</assembly>


text:
package com.opengamma.financial.analytics.parameters;

import java.util.Arrays;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import org.joda.beans.Bean;
import org.joda.beans.BeanDefinition;
import org.joda.beans.ImmutableBean;
import org.joda.beans.ImmutableValidator;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.time.Tenor;

/**
 * Represents a table of volatility entries. An entry
 * generally consists of the volatility between a start
 * tenor (inclusive) and the end tenor (exclusive). This
 * table holds the set of entries and checks they form
 * a coherent definition.
 *

 * Specifically, it checks that:
 *

 *
there is at least one entry in the table

 *
the first entry in the table has a start tenor of 0

 *
the last entry in the table has no end tenor specified

 *
if there is more than one entry, the start tenor of an
 *   entry matches the end tenor of the preceding one

 *

 */
@BeanDefinition
public class HullWhiteOneFactorVolatilityTable implements ImmutableBean {

  /**
   * The set of volatility entries that make up the table. These will
   * be sorted in their natural order (start tenor ascending).
   *

   * Will be validated to ensure that a contiguous range of entries is
   * specified, with the start tenor of the first entry set to zero
   * and the end tenor of the last entry set to null.
   */
  @PropertyDefinition(validate = "notNull")
  private final SortedSet<HullWhiteOneFactorVolatilityEntry> _entries;

  /**
   * Need to validate that:
   *

   *
there is at least one entry in the table

   *
the first entry in the table has a start tenor of 0

   *
the last entry in the table has no end tenor specified

   *
if there is more than one entry, the start tenor of an
   *   entry matches the end tenor of the preceding one

   *

   * Note that there is no need to check for null entries as the Guava
   * ImmutableSortedSet which joda-beans creates will not accept nulls.
   */
  @ImmutableValidator
  private void validate() {
    ArgumentChecker.notEmpty(_entries, "_entries");

    // Convert to list so we have direct element access - by definition
    // the set is already in the correct order
    ImmutableList<HullWhiteOneFactorVolatilityEntry> entryList = ImmutableList.copyOf(_entries);

    for (int i = 0; i < entryList.size(); i++) {

      Tenor start = entryList.get(i).getStartTenor();
      if (i == 0) {
        ArgumentChecker.isTrue(start.equals(Tenor.ofDays(0)),
                               "Start tenor of first entry should be Tenor[P0D] but was [{}]", start);
      } else {
        Tenor previousEnd = entryList.get(i - 1).getEndTenor();
        ArgumentChecker.isTrue(start.equals(previousEnd),
                               "Start tenor [{}] does not equal previous end tenor [{}]", start, previousEnd);
      }

      if (i == entryList.size() - 1) {
        Tenor end = entryList.get(i).getEndTenor();
        ArgumentChecker.isTrue(end == null, "End tenor of last entry should not have a value but was [{}]", end);
      }
    }
  }

  //------------------------- AUTOGENERATED START -------------------------
  ///CLOVER:OFF
  /**
   * The meta-bean for {@code HullWhiteOneFactorVolatilityTable}.
   * @return the meta-bean, not null
   */
  public static HullWhiteOneFactorVolatilityTable.Meta meta() {
    return HullWhiteOneFactorVolatilityTable.Meta.INSTANCE;
  }

  static {
    JodaBeanUtils.registerMetaBean(HullWhiteOneFactorVolatilityTable.Meta.INSTANCE);
  }

  /**
   * Returns a builder used to create an instance of the bean.
   * @return the builder, not null
   */
  public static HullWhiteOneFactorVolatilityTable.Builder builder() {
    return new HullWhiteOneFactorVolatilityTable.Builder();
  }

  /**
   * Restricted constructor.
   * @param builder  the builder to copy from, not null
   */
  protected HullWhiteOneFactorVolatilityTable(HullWhiteOneFactorVolatilityTable.Builder builder) {
    JodaBeanUtils.notNull(builder._entries, "entries");
    this._entries = ImmutableSortedSet.copyOfSorted(builder._entries);
    validate();
  }

  @Override
  public HullWhiteOneFactorVolatilityTable.Meta metaBean() {
    return HullWhiteOneFactorVolatilityTable.Meta.INSTANCE;
  }

  @Override
  public <R> Property<R> property(String propertyName) {
    return metaBean().<R>metaProperty(propertyName).createProperty(this);
  }

  @Override
  public Set<String> propertyNames() {
    return metaBean().metaPropertyMap().keySet();
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the set of volatility entries that make up the table. These will
   * be sorted in their natural order (start tenor ascending).
   *

   * Will be validated to ensure that a contiguous range of entries is
   * specified, with the start tenor of the first entry set to zero
   * and the end tenor of the last entry set to null.
   * @return the value of the property, not null
   */
  public SortedSet<HullWhiteOneFactorVolatilityEntry> getEntries() {
    return _entries;
  }

  //-----------------------------------------------------------------------
  /**
   * Returns a builder that allows this bean to be mutated.
   * @return the mutable builder, not null
   */
  public Builder toBuilder() {
    return new Builder(this);
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj != null && obj.getClass() == this.getClass()) {
      HullWhiteOneFactorVolatilityTable other = (HullWhiteOneFactorVolatilityTable) obj;
      return JodaBeanUtils.equal(getEntries(), other.getEntries());
    }
    return false;
  }

  @Override
  public int hashCode() {
    int hash = getClass().hashCode();
    hash = hash * 31 + JodaBeanUtils.hashCode(getEntries());
    return hash;
  }

  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder(64);
    buf.append("HullWhiteOneFactorVolatilityTable{");
    int len = buf.length();
    toString(buf);
    if (buf.length() > len) {
      buf.setLength(buf.length() - 2);
    }
    buf.append('}');
    return buf.toString();
  }

  protected void toString(StringBuilder buf) {
    buf.append("entries").append('=').append(JodaBeanUtils.toString(getEntries())).append(',').append(' ');
  }

  //-----------------------------------------------------------------------
  /**
   * The meta-bean for {@code HullWhiteOneFactorVolatilityTable}.
   */
  public static class Meta extends DirectMetaBean {
    /**
     * The singleton instance of the meta-bean.
     */
    static final Meta INSTANCE = new Meta();

    /**
     * The meta-property for the {@code entries} property.
     */
    @SuppressWarnings({"unchecked", "rawtypes" })
    private final MetaProperty<SortedSet<HullWhiteOneFactorVolatilityEntry>> _entries = DirectMetaProperty.ofImmutable(
        this, "entries", HullWhiteOneFactorVolatilityTable.class, (Class) SortedSet.class);
    /**
     * The meta-properties.
     */
    private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
        this, null,
        "entries");

    /**
     * Restricted constructor.
     */
    protected Meta() {
    }

    @Override
    protected MetaProperty<?> metaPropertyGet(String propertyName) {
      switch (propertyName.hashCode()) {
        case -1591573360:  // entries
          return _entries;
      }
      return super.metaPropertyGet(propertyName);
    }

    @Override
    public HullWhiteOneFactorVolatilityTable.Builder builder() {
      return new HullWhiteOneFactorVolatilityTable.Builder();
    }

    @Override
    public Class<? extends HullWhiteOneFactorVolatilityTable> beanType() {
      return HullWhiteOneFactorVolatilityTable.class;
    }

    @Override
    public Map<String, MetaProperty<?>> metaPropertyMap() {
      return _metaPropertyMap$;
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-property for the {@code entries} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<SortedSet<HullWhiteOneFactorVolatilityEntry>> entries() {
      return _entries;
    }

    //-----------------------------------------------------------------------
    @Override
    protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
      switch (propertyName.hashCode()) {
        case -1591573360:  // entries
          return ((HullWhiteOneFactorVolatilityTable) bean).getEntries();
      }
      return super.propertyGet(bean, propertyName, quiet);
    }

    @Override
    protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
      metaProperty(propertyName);
      if (quiet) {
        return;
      }
      throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
    }

  }

  //-----------------------------------------------------------------------
  /**
   * The bean-builder for {@code HullWhiteOneFactorVolatilityTable}.
   */
  public static class Builder extends DirectFieldsBeanBuilder<HullWhiteOneFactorVolatilityTable> {

    private SortedSet<HullWhiteOneFactorVolatilityEntry> _entries = new TreeSet<HullWhiteOneFactorVolatilityEntry>();

    /**
     * Restricted constructor.
     */
    protected Builder() {
    }

    /**
     * Restricted copy constructor.
     * @param beanToCopy  the bean to copy from, not null
     */
    protected Builder(HullWhiteOneFactorVolatilityTable beanToCopy) {
      this._entries = new TreeSet<HullWhiteOneFactorVolatilityEntry>(beanToCopy.getEntries());
    }

    //-----------------------------------------------------------------------
    @Override
    public Object get(String propertyName) {
      switch (propertyName.hashCode()) {
        case -1591573360:  // entries
          return _entries;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
    }

    @SuppressWarnings("unchecked")
    @Override
    public Builder set(String propertyName, Object newValue) {
      switch (propertyName.hashCode()) {
        case -1591573360:  // entries
          this._entries = (SortedSet<HullWhiteOneFactorVolatilityEntry>) newValue;
          break;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
      return this;
    }

    @Override
    public Builder set(MetaProperty<?> property, Object value) {
      super.set(property, value);
      return this;
    }

    @Override
    public Builder setString(String propertyName, String value) {
      setString(meta().metaProperty(propertyName), value);
      return this;
    }

    @Override
    public Builder setString(MetaProperty<?> property, String value) {
      super.setString(property, value);
      return this;
    }

    @Override
    public Builder setAll(Map<String, ? extends Object> propertyValueMap) {
      super.setAll(propertyValueMap);
      return this;
    }

    @Override
    public HullWhiteOneFactorVolatilityTable build() {
      return new HullWhiteOneFactorVolatilityTable(this);
    }

    //-----------------------------------------------------------------------
    /**
     * Sets the {@code entries} property in the builder.
     * @param entries  the new value, not null
     * @return this, for chaining, not null
     */
    public Builder entries(SortedSet<HullWhiteOneFactorVolatilityEntry> entries) {
      JodaBeanUtils.notNull(entries, "entries");
      this._entries = entries;
      return this;
    }

    /**
     * Sets the {@code entries} property in the builder
     * from an array of objects.
     * @param entries  the new value, not null
     * @return this, for chaining, not null
     */
    public Builder entries(HullWhiteOneFactorVolatilityEntry... entries) {
      return entries(new TreeSet<HullWhiteOneFactorVolatilityEntry>(Arrays.asList(entries)));
    }

    //-----------------------------------------------------------------------
    @Override
    public String toString() {
      StringBuilder buf = new StringBuilder(64);
      buf.append("HullWhiteOneFactorVolatilityTable.Builder{");
      int len = buf.length();
      toString(buf);
      if (buf.length() > len) {
        buf.setLength(buf.length() - 2);
      }
      buf.append('}');
      return buf.toString();
    }

    protected void toString(StringBuilder buf) {
      buf.append("entries").append('=').append(JodaBeanUtils.toString(_entries)).append(',').append(' ');
    }

  }

  ///CLOVER:ON
  //-------------------------- AUTOGENERATED END --------------------------
}


text:
import onmt.Constants
import onmt.Models
from onmt.Translator import Translator
from onmt.Dataset import Dataset
from onmt.Optim import Optim
from onmt.Dict import Dict
from onmt.Beam import Beam


text:
using LeagueLeak.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AutoMapper.QueryableExtensions;
using LeagueLeak.Web.Models.Guides;
using LeagueLeak.Web.Models.Home;

namespace LeagueLeak.Web.Controllers
{
    public class HomeController : BaseController
    {
        public HomeController(IApplicationData data)
            :base(data)
        {
        }

        public ActionResult Index()
        {
            var indexViewModel = this.Data.Articles.All()
                .Project().To<IndexArticlesViewModel>().ToList();

            return View(indexViewModel);
        }

        public ActionResult Error()
        {
            return View();
        }
    }
}


text:
@interface ThridViewController : BaseUIViewController

@end


text:
{{ Form::bsText('menu','Menu name','Menu name',$menu->menu) }}
{{ Form::bsText('description','Description','Description',$menu->description) }}


text:
using System.Collections.Generic;
using Newtonsoft.Json;
using ONIT.VismaNetApi.Lib;

namespace ONIT.VismaNetApi.Models
{
  public class RotRutDetails : DtoProviderBase, IProvideCustomDto
  {

    public string appartment
    {
      get => Get<string>();
      set => Set(value);
    }

    [JsonProperty]
    public decimal distributedAmount { get; private set; }

    public bool distributedAutomaticaly
    {
      get => Get<bool>();
      set => Set(value);
    }

    public List<RotRutDistribution> distribution
    {
      get => Get(defaultValue: new List<RotRutDistribution>());
      set => Set(value);
    }

    [JsonProperty]
    public string docType { get; private set; }

    public string estate
    {
      get => Get<string>();
      set => Set(value);
    }

    [JsonProperty]
    public decimal materialCost { get; private set; }

    [JsonProperty]
    public string organizationNbr
    {
      get => Get<string>();
      set => Set(value);
    }

    [JsonProperty]
    public decimal otherCost { get; private set; }

    [JsonProperty]
    public string refNbr { get; private set; }

    [JsonProperty]
    public decimal totalDeductableAmount { get; private set; }

    public string type
    {
      get => Get<string>();
      set => Set(value);
    }

    [JsonProperty]
    public decimal workPrice { get; private set; }

    public object ToDto()
    {
      if (type == null)
      {
        return null;
      }

      return ToDto(false);
    }
  }
}


text:
package testclient

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
	clientgotesting "k8s.io/client-go/testing"

	userapi "github.com/openshift/origin/pkg/user/apis/user"
)

// FakeIdentities implements IdentitiesInterface. Meant to be embedded into a struct to get a default
// implementation. This makes faking out just the methods you want to test easier.
type FakeIdentities struct {
	Fake *Fake
}

var identitiesResource = schema.GroupVersionResource{Group: "", Version: "", Resource: "identities"}
var identitiesKind = schema.GroupVersionKind{Group: "", Version: "", Kind: "Identity"}

func (c *FakeIdentities) Get(name string, options metav1.GetOptions) (*userapi.Identity, error) {
	obj, err := c.Fake.Invokes(clientgotesting.NewRootGetAction(identitiesResource, name), &userapi.Identity{})
	if obj == nil {
		return nil, err
	}

	return obj.(*userapi.Identity), err
}

func (c *FakeIdentities) List(opts metav1.ListOptions) (*userapi.IdentityList, error) {
	obj, err := c.Fake.Invokes(clientgotesting.NewRootListAction(identitiesResource, identitiesKind, opts), &userapi.IdentityList{})
	if obj == nil {
		return nil, err
	}

	return obj.(*userapi.IdentityList), err
}

func (c *FakeIdentities) Create(inObj *userapi.Identity) (*userapi.Identity, error) {
	obj, err := c.Fake.Invokes(clientgotesting.NewRootCreateAction(identitiesResource, inObj), inObj)
	if obj == nil {
		return nil, err
	}

	return obj.(*userapi.Identity), err
}

func (c *FakeIdentities) Update(inObj *userapi.Identity) (*userapi.Identity, error) {
	obj, err := c.Fake.Invokes(clientgotesting.NewRootUpdateAction(identitiesResource, inObj), inObj)
	if obj == nil {
		return nil, err
	}

	return obj.(*userapi.Identity), err
}

func (c *FakeIdentities) Delete(name string) error {
	_, err := c.Fake.Invokes(clientgotesting.NewRootDeleteAction(identitiesResource, name), nil)
	return err
}


text:
/*
CryptoJS v3.0.2
code.google.com/p/crypto-js
(c) 2009-2012 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
CryptoJS.pad.NoPadding={pad:function(){},unpad:function(){}};


text:
WaveSite [![Packagist](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/TechCavern/WaveSite/blob/master/license.md)
==============
TechCavern Website (Built with BootStrap, Jumbotron and Font Awesome)
=======
A Simple Basic Website


text:
package com.plattysoft.leonids.examples;

import com.plattysoft.leonids.modifiers.AlphaModifier;
import com.plattysoft.leonids.ParticleSystem;
import com.plattysoft.leonids.modifiers.ScaleModifier;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

public class DustExampleActivity extends Activity implements OnClickListener {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dust_example);
		findViewById(R.id.button1).setOnClickListener(this);
	}

	@Override
	public void onClick(View arg0) {
		new ParticleSystem(this, 4, R.drawable.dust, 3000)
		.setSpeedByComponentsRange(-0.025f, 0.025f, -0.06f, -0.08f)
		.setAcceleration(0.00001f, 30)
		.setInitialRotationRange(0, 360)
		.addModifier(new AlphaModifier(255, 0, 1000, 3000))
		.addModifier(new ScaleModifier(0.5f, 2f, 0, 1000))
		.oneShot(findViewById(R.id.emiter_bottom), 4);
	}
}


text:
'use strict';

var Mixin = require('../../utils/mixin'),
    Tokenizer = require('../../tokenizer'),
    PositionTrackingPreprocessorMixin = require('../position_tracking/preprocessor_mixin'),
    inherits = require('util').inherits;

var LocationInfoTokenizerMixin = module.exports = function (tokenizer) {
    Mixin.call(this, tokenizer);

    this.tokenizer = tokenizer;
    this.posTracker = new PositionTrackingPreprocessorMixin(tokenizer.preprocessor);
    this.currentAttrLocation = null;
    this.currentTokenLocation = null;
};

inherits(LocationInfoTokenizerMixin, Mixin);

LocationInfoTokenizerMixin.prototype._getCurrentLocation = function () {
    return {
        line: this.posTracker.line,
        col: this.posTracker.col,
        startOffset: this.posTracker.offset,
        endOffset: -1
    };
};

LocationInfoTokenizerMixin.prototype._attachCurrentAttrLocationInfo = function () {
    this.currentAttrLocation.endOffset = this.posTracker.offset;

    var currentToken = this.tokenizer.currentToken,
        currentAttr = this.tokenizer.currentAttr;

    if (!currentToken.location.attrs)
        currentToken.location.attrs = Object.create(null);

    currentToken.location.attrs[currentAttr.name] = this.currentAttrLocation;
};

LocationInfoTokenizerMixin.prototype._getOverriddenMethods = function (mxn, orig) {
    var methods = {
        _createStartTagToken: function () {
            orig._createStartTagToken.call(this);
            this.currentToken.location = mxn.currentTokenLocation;
        },

        _createEndTagToken: function () {
            orig._createEndTagToken.call(this);
            this.currentToken.location = mxn.currentTokenLocation;
        },

        _createCommentToken: function () {
            orig._createCommentToken.call(this);
            this.currentToken.location = mxn.currentTokenLocation;
        },

        _createDoctypeToken: function (initialName) {
            orig._createDoctypeToken.call(this, initialName);
            this.currentToken.location = mxn.currentTokenLocation;
        },

        _createCharacterToken: function (type, ch) {
            orig._createCharacterToken.call(this, type, ch);
            this.currentCharacterToken.location = mxn.currentTokenLocation;
        },

        _createAttr: function (attrNameFirstCh) {
            orig._createAttr.call(this, attrNameFirstCh);
            mxn.currentAttrLocation = mxn._getCurrentLocation();
        },

        _leaveAttrName: function (toState) {
            orig._leaveAttrName.call(this, toState);
            mxn._attachCurrentAttrLocationInfo();
        },

        _leaveAttrValue: function (toState) {
            orig._leaveAttrValue.call(this, toState);
            mxn._attachCurrentAttrLocationInfo();
        },

        _emitCurrentToken: function () {
            //NOTE: if we have pending character token make it's end location equal to the
            //current token's start location.
            if (this.currentCharacterToken)
                this.currentCharacterToken.location.endOffset = this.currentToken.location.startOffset;

            this.currentToken.location.endOffset = mxn.posTracker.offset + 1;
            orig._emitCurrentToken.call(this);
        },

        _emitCurrentCharacterToken: function () {
            //NOTE: if we have character token and it's location wasn't set in the _emitCurrentToken(),
            //then set it's location at the current preprocessor position.
            //We don't need to increment preprocessor position, since character token
            //emission is always forced by the start of the next character token here.
            //So, we already have advanced position.
            if (this.currentCharacterToken && this.currentCharacterToken.location.endOffset === -1)
                this.currentCharacterToken.location.endOffset = mxn.posTracker.offset;

            orig._emitCurrentCharacterToken.call(this);
        }
    };

    //NOTE: patch initial states for each mode to obtain token start position
    Object.keys(Tokenizer.MODE).forEach(function (modeName) {
        var state = Tokenizer.MODE[modeName];

        methods[state] = function (cp) {
            mxn.currentTokenLocation = mxn._getCurrentLocation();
            orig[state].call(this, cp);
        };
    });

    return methods;
};


text:
/*
 * Bundle.cpp
 *
 *  Created on: Jan 23, 2014
 *      Author: vini
 */

#include "Bundle.h"

namespace gamespice {
namespace android {

Bundle::Bundle() {

}

Bundle Bundle::add(std::string key, std::string value) {
	data[key] = Value(value);
	return *this;
}

Bundle Bundle::add(std::string key, int value) {
	data[key] = Value(value);
	return *this;
}

Bundle Bundle::add(std::string key, bool value) {
	data[key] = Value(value);
	return *this;
}

void Bundle::toJSON(json_t* jsonObject) {
	for (const auto& e : data) {
		const char* key = e.first.c_str();
		Value v = e.second;
		switch (v.getType()) {
		case Value::Type::STRING:
			json_object_set_new(jsonObject, key,
					json_string(v.asString().c_str()));
			break;
		case Value::Type::INTEGER:
			json_object_set_new(jsonObject, key, json_integer(v.asInt()));
			break;

		case Value::Type::BOOLEAN:
			json_object_set_new(jsonObject, key, json_boolean(v.asBool()));
			break;
		}
	}
}

Bundle::~Bundle() {
}

} /* namespace android */
} /* namespace gamespice */


text:
if [ "$(uname)" == "Darwin" ]; then
	DEPENDENCIES=("ansible" "git" "VirtualBox" "vagrant")
else
	DEPENDENCIES=("ansible" "git" "virtual-box" "vagrant")
fi

f_create(){
clear
echo -n "Project name: "
read name

# If folder doesn't exist, create it
if [ ! -d $name ]; then
	mkdir $name && cd $name
	git clone --depth=1 git@github.com:roots/trellis.git && rm -rf trellis/.git
	git clone --depth=1 git@github.com:roots/bedrock.git site && rm -rf site/.git
	git clone --depth=1 git@github.com:roots/sage.git site/web/app/themes/sage && rm -rf site/web/app/themes/sage/.git
else
	echo "$name already exists"
	echo
	echo
	f_ask_update(){
		read -p "Do you want to update to latest roots dependencies (y/n)" choice
		case "$choice" in
		  y|Y ) f_update;;
		  n|N ) exit;;
		  * ) f_error;;
		esac
	}
	while true; do f_ask_update; done
fi

exit
}

f_update(){
echo "TODO: Update existing project"
exit
}

f_error(){
echo "invalid option"
}

f_check_dependency(){

#TODO: Install / update vagrant dependencies (vagrant-bindfs, vagrant-hostmanager)

for i in ${DEPENDENCIES[@]}
do
	if [ ! -f "$(which $i)" ]; then
		echo "$i not found, please install $i"
		exit
	fi

done

}

f_main(){
f_check_dependency
echo -e "\e[1;34mRoots Wordpress scaffolding\e[0m"
echo "1. Create project"
echo "2. Update dependencies"
echo
echo -n "Choice: "
read choice

case $choice in
     1) f_create;;
     2) f_update;;
     3) exit;;
     *) f_error;;
esac
}

# Program
while true; do f_main; done


text:
#region License
//Copyright(c) Paul Biccherai
//Licensed under the MIT license. See LICENSE file in the project root for full license information.
#endregion

using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace PaulMiami.AspNetCore.Identity.Authenticator.EntityFrameworkCore.Test
{
    public class IntergrationTest : IClassFixture<IntegrationTestFixture>
    {
        public IntergrationTest(IntegrationTestFixture fixture)
        {
            Client = fixture.Client;
        }
        public HttpClient Client { get; }

        [Fact]
        public async Task CreateUserAndAddAuthenticator()
        {
            var formParams = new Dictionary<string, string>();
            formParams["username"] = "john";
            formParams["password"] = "P@$$w0rd";
            formParams["code"] = "123456";
            formParams["hashAlgorithm"] = "SHA1";
            formParams["numberOfDigits"] = "6";
            formParams["periodInSeconds"] = "30";
            formParams["secret"] = "$3CR3T";

            var response = await Client.PostAsync("http://localhost/home/login", new FormUrlEncodedContent(formParams));

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal("OK", await response.Content.ReadAsStringAsync());
        }

        [Fact]
        public async Task BadCodeCreateUserAndAddAuthenticator()
        {
            var formParams = new Dictionary<string, string>();
            formParams["username"] = "john2";
            formParams["password"] = "P@$$w0rd";
            formParams["code"] = "875654";
            formParams["hashAlgorithm"] = "SHA1";
            formParams["numberOfDigits"] = "6";
            formParams["periodInSeconds"] = "30";
            formParams["secret"] = "$3CR3T";

            var response = await Client.PostAsync("http://localhost/home/login", new FormUrlEncodedContent(formParams));

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal("BADCODE", await response.Content.ReadAsStringAsync());
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ShadowToast</title>
<meta name="date" content="2017-01-11">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.robolectric.shadows

Class ShadowToast

java.lang.Object

org.robolectric.shadows.ShadowToast

@Implements(value=android.widget.Toast.class)
public class ShadowToast
extends java.lang.Object

Shadow for Toast.

Constructor Summary

Constructors

Constructor and Description

ShadowToast()

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
__constructor__(android.content.Context context)

void
cancel()

int
getDuration()

int
getGravity()

static android.widget.Toast
getLatestToast()

Non-Android accessor that returns the most recently shown Toast

static java.lang.String
getTextOfLatestToast()

Non-Android accessor that returns the text of the most recently shown Toast

android.view.View
getView()

int
getXOffset()

int
getYOffset()

static android.widget.Toast
makeText(android.content.Context context,
        java.lang.CharSequence text,
        int duration)

static android.widget.Toast
makeText(android.content.Context context,
        int resId,
        int duration)

static void
reset()

Non-Android accessor that discards the recorded Toasts

void
setDuration(int duration)

void
setGravity(int gravity,
          int xOffset,
          int yOffset)

void
setText(java.lang.CharSequence text)

void
setText(int resId)

void
setView(android.view.View view)

void
show()

static boolean
showedCustomToast(java.lang.CharSequence message,
                 int layoutResourceIdToCheckForMessage)

Non-Android query method that returns whether or not a particular custom Toast has been shown.

static boolean
showedToast(java.lang.CharSequence message)

query method that returns whether or not a particular Toast has been shown.

static int
shownToastCount()

Non-Android accessor that returns the number of Toast requests that have been made during this test run
 or since reset() has been called.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ShadowToast

public ShadowToast()

Method Detail

__constructor__

public void __constructor__(android.content.Context context)

makeText

@Implementation
public static android.widget.Toast makeText(android.content.Context context,
                                                            int resId,
                                                            int duration)

makeText

@Implementation
public static android.widget.Toast makeText(android.content.Context context,
                                                            java.lang.CharSequence text,
                                                            int duration)

show

@Implementation
public void show()

setText

@Implementation
public void setText(int resId)

setText

@Implementation
public void setText(java.lang.CharSequence text)

setView

@Implementation
public void setView(android.view.View view)

getView

@Implementation
public android.view.View getView()

setGravity

@Implementation
public void setGravity(int gravity,
                                       int xOffset,
                                       int yOffset)

getGravity

@Implementation
public int getGravity()

getXOffset

@Implementation
public int getXOffset()

getYOffset

@Implementation
public int getYOffset()

setDuration

@Implementation
public void setDuration(int duration)

getDuration

@Implementation
public int getDuration()

cancel

@Implementation
public void cancel()

reset

public static void reset()

Non-Android accessor that discards the recorded Toasts

shownToastCount

public static int shownToastCount()

Non-Android accessor that returns the number of Toast requests that have been made during this test run
 or since reset() has been called.

Returns:

the number of Toast requests that have been made during this test run
         or since reset() has been called.

showedCustomToast

public static boolean showedCustomToast(java.lang.CharSequence message,
                                        int layoutResourceIdToCheckForMessage)

Non-Android query method that returns whether or not a particular custom Toast has been shown.

Parameters:

message - the message to search for

layoutResourceIdToCheckForMessage - the id of the resource that contains the toast messages

Returns:

whether the Toast was requested

showedToast

public static boolean showedToast(java.lang.CharSequence message)

query method that returns whether or not a particular Toast has been shown.

Parameters:

message - the message to search for

Returns:

whether the Toast was requested

getTextOfLatestToast

public static java.lang.String getTextOfLatestToast()

Non-Android accessor that returns the text of the most recently shown Toast

Returns:

the text of the most recently shown Toast

getLatestToast

public static android.widget.Toast getLatestToast()

Non-Android accessor that returns the most recently shown Toast

Returns:

the most recently shown Toast

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php

use yii\helpers\Html;
use kartik\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\CustomerOrdersIngredients */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'created_on')->textInput() ?>

    <?= $form->field($model, 'category')->textInput() ?>

    <?= $form->field($model, 'ingredient_id')->textInput() ?>

    <?= $form->field($model, 'ingredient_percent')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'modified_by')->textInput() ?>

    <?= $form->field($model, 'modified_on')->textInput() ?>

    <?= $form->field($model, 'order_id')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

if (isset($_SERVER['REMOTE_ADDR'])) {
    die; // no access from web!
}

// Force OPcache reset if used, we do not want any stale caches
// when preparing test environment.
if (function_exists('opcache_reset')) {
    opcache_reset();
}

define('IGNORE_COMPONENT_CACHE', true);

require_once(__DIR__.'/../../../../lib/clilib.php');
require_once(__DIR__.'/../../../../lib/phpunit/bootstraplib.php');
require_once(__DIR__.'/../../../../lib/testing/lib.php');

echo "Initialising Moodle PHPUnit test environment...\n";

$output = null;
exec('php --version', $output, $code);
if ($code != 0) {
    phpunit_bootstrap_error(1, 'Can not execute \'php\' binary.');
}

chdir(__DIR__);
$output = null;
exec("php util.php --diag", $output, $code);
if ($code == 0) {
    // everything is ready

} else if ($code == PHPUNIT_EXITCODE_INSTALL) {
    passthru("php util.php --install", $code);
    if ($code != 0) {
        exit($code);
    }

} else if ($code == PHPUNIT_EXITCODE_REINSTALL) {
    passthru("php util.php --drop", $code);
    passthru("php util.php --install", $code);
    if ($code != 0) {
        exit($code);
    }

} else {
    echo implode("\n", $output)."\n";
    exit($code);
}

passthru("php util.php --buildconfig", $code);

exit(0);


text:
<?php
/**
 * @author Marian Meres
 */
namespace MM\Model;

require_once __DIR__ . "/_bootstrap.php";
require_once __DIR__ . "/_files/PersistentModelFoo.php";

use MM\Model\AbstractModel;
use MM\Model\AbstractPersistentModel;

/**
 * @group mm-model
 */
class PersistentModelTest extends \PHPUnit_Framework_TestCase
{
    public function testGetIdInfoWorks()
    {
        $m = new \MM_Model_PersistentModelFoo();
        $m->id = 123;
        $this->assertEquals(123, $m->getId());

        $m2 = new \MM_Model_PersistentModelFoo2();
        $m2->some_id = 2;
        $this->assertEquals(['some_id' => 2, 'user_id' => null], $m2->getId());
    }

    public function testSetIdInfoWorks()
    {
        $m2 = new \MM_Model_PersistentModelFoo2();
        $m2->setId([
            'some_id' => 2, 'user_id' => 3
        ]);

        $this->assertEquals(3, $m2->user_id);

        try {
            $m2->setId('asd');
            $this->fail("Should have failed on invalid argument");
        } catch(\InvalidArgumentException $e){}
    }

    public function testSetNullIdWorks()
    {
        //$x = (array) null;
        //prx($x);

        $m = new \MM_Model_PersistentModelFoo();
        $m->id = null;

//        $m = new \MM_Model_PersistentModelFoo([
//            'id' => null
//        ]);
    }
}


text:
import {Directive, ElementRef} from '@angular/core';
import {Router} from '@angular/router';

import {AppService} from '../services';

@Directive({
    selector: '[headerType]'
})
export class HeaderTypeDirective {
	htmlClassName: string = 'app-header--epic';

	constructor(private el: ElementRef, private _router: Router, private _appService: AppService) {}

	ngOnInit() {
		this.setHeaderType();
    this._router.events.subscribe((e) => {
      this.setHeaderType();
    });
	}

	setHeaderType() {
		let ele = this.el.nativeElement;

    if(this._router.url === '/') {
    	//ele.classList.add(this.htmlClassName);
      this._appService.epicHeader = true;
  	} else {
    	//ele.classList.remove(this.htmlClassName);
      this._appService.epicHeader = false;
  	}
	}
}


text:
using System;
using Windows.UI.Xaml.Navigation;
using Caliburn.Micro.State.Views;

namespace Caliburn.Micro.State.ViewModels
{
    public class DebugNavigationViewModel : Screen
    {
        private readonly INavigationService _navigationService;

        public DebugNavigationViewModel(INavigationService navigationService)
        {
            _navigationService = navigationService;
        }

        public void Insert()
        {
            var view = typeof (RepositoryDetailsView);
            var parameter = _navigationService.UriFor<RepositoryDetailsViewModel>()
                .WithParam(v => v.Owner, "caliburn-micro")
                .WithParam(v => v.Name, "caliburn.micro")
                .BuildUri()
                .AbsoluteUri;

            _navigationService.ForwardStack.Add(new PageStackEntry(view, parameter, null));

            NotifyOfPropertyChange(() => CanGoForward);
        }

        public bool CanGoBack
        {
            get { return _navigationService.CanGoBack; }
        }

        public void GoBack()
        {
            _navigationService.GoBack();
        }

        public bool CanGoForward
        {
            get { return _navigationService.CanGoForward; }
        }

        public void GoForward()
        {
            _navigationService.GoForward();
        }

        public void Clear()
        {
            _navigationService.BackStack.Clear();
            _navigationService.ForwardStack.Clear();

            NotifyOfPropertyChange(() => CanGoBack);
            NotifyOfPropertyChange(() => CanGoForward);
        }
    }
}


text:
<?php

namespace Marquine\Iconic;

use Illuminate\Support\ServiceProvider;

class IconicServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        if ($config = $this->app['config']['iconic']) {
            Icon::config($config);
        }

        $this->publishes([
            __DIR__.'/../config/iconic.php' => config_path('iconic.php'),
        ], 'iconic');
    }
}