text:
import os
import datetime

import unittest
from unittest.mock import patch
from metadoc.domain import Domaintools

class MetadocDomaintoolsTest(unittest.TestCase):

  def setUp(self):
    article_path = "tests/fixtures/theintercept.com/laura-ingraham-lifezette.html"
    self.title = "Some Fake News Publishers Just Happen to Be Donald Trump's Cronies"
    self.url = "https://theintercept.com/2016/11/26/laura-ingraham-lifezette/"
    self.date_registered = datetime.datetime(2008, 10, 1, 0, 0)
    self.domaintools = Domaintools(url=self.url)

    with open(article_path, 'r') as article:
      self.article_html=article.read()

  def test_init(self):
    assert self.domaintools.url == self.url
    assert self.domaintools.domain == "theintercept.com"

  @patch('metadoc.domain.domaintools.whois_date_registered')
  def test_get_all_local(self, _mocked_func):
    _mocked_func.return_value = self.date_registered
    self.domaintools.get_all()#self.loop)
    assert self.domaintools.date_registered == self.date_registered

    credibility_resp = {
      "is_blacklisted": False,
      "fake_confidence": "0.00"
    }

    assert self.domaintools.credibility == credibility_resp
    assert self.domaintools.date_registered == self.date_registered

  def test_get_all_remote(self):
    self.domaintools.get_all()
    assert self.domaintools.date_registered is not self.date_registered

  def test_new_domain(self):
    today = datetime.datetime.now()
    self.domaintools.date_registered = today
    self.domaintools.check_credibility()
    self.domaintools.recalculate_fake_confidence()

    assert self.domaintools.credibility["fake_confidence"] == 0.2


text:
package com.sqap.api.config.resource.processor;

import com.sqap.api.controllers.rest.audio.test.group.TestGroupController;
import com.sqap.api.domain.audio.test.base.TestGroupEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.rest.webmvc.RepositorySearchesResource;
import org.springframework.hateoas.ResourceProcessor;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.stereotype.Component;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

@Component
@Slf4j
public class SearchResourcesProcessor implements ResourceProcessor<RepositorySearchesResource>{
    @Override
    public RepositorySearchesResource process(RepositorySearchesResource repositorySearchesResource) {
        final String search = repositorySearchesResource.getId().getHref();
        if (search == null) {
            // todonext
        }
        else {
            if (repositorySearchesResource.getDomainType().equals(TestGroupEntity.class)) {
                repositorySearchesResource.add(ControllerLinkBuilder.linkTo(methodOn(TestGroupController.class).findOwn(null, null)).withRel("findOwn"));
                repositorySearchesResource.add(linkTo(methodOn(TestGroupController.class).findNotParticipated(null, null)).withRel("findNotParticipated"));
            }
        }
//        final Link findOwn = new Link(search + "/findOwn").withRel("findOwn");
//        repositorySearchesResource.add(findOwn);

        return repositorySearchesResource;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Mautic\CoreBundle\Exception;

class DatabaseConnectionException extends \Exception
{
    public function __construct($message = 'Unable to connect to the database.', $code = 0, \Exception $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }
}


text:
package org.raidenjpa.query.parser;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class GroupByElements {

	private List<String> path = new ArrayList<String>();

	public GroupByElements(String element) {
		path = new ArrayList<String>(Arrays.asList(element.split("\\.")));
	}

	public List<String> getPath() {
		return path;
	}

	public String toString() {
		return "GroupByElement [path=" + path + "]";
	}

}


text:
using OpenZWave;
using OpenZWave.NetworkManager;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace OZWAppx.Views
{
    public sealed partial class ControllerView : Page
    {
        public ControllerView()
        {
            this.InitializeComponent();
        }

        public Controller Controller
        {
            get { return (Controller)GetValue(ControllerProperty); }
            set { SetValue(ControllerProperty, value); }
        }

        public static readonly DependencyProperty ControllerProperty =
            DependencyProperty.Register("Controller", typeof(Controller), typeof(ControllerView), new PropertyMetadata(null, OnControllerPropertyChanged));

        private static void OnControllerPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            (d as ControllerView).VM.UpdateController(e.NewValue as Controller);
        }

        public ControllerViewVM VM { get; private set; } = new ControllerViewVM();

        private void SaveConfiguration_Click(object sender, RoutedEventArgs e)
        {
            Controller.WriteConfiguration();
        }

        private void ResetSoft_Click(object sender, RoutedEventArgs e)
        {
            Controller.SoftReset();
        }

        private void ResetHard_Click(object sender, RoutedEventArgs e)
        {
            var dlg = new MessageDialog("Reset all connected controllers? This can't be undone", "Confirm");
            dlg.Commands.Add(new UICommand("OK", (s) =>
            {
                Controller.ResetController();
            }));
            dlg.Commands.Add(new UICommand("Cancel"));
            var _ = dlg.ShowAsync();
        }

        private void ReceiveConfig_Click(object sender, RoutedEventArgs e)
        {
            Controller.ReceiveConfiguration();
        }

        private void RemoveNode_Click(object sender, RoutedEventArgs e)
        {
            Controller.RemoveNode();
            var dlg = new MessageDialog("Please follow the manufacturer's instructions to remove the Z-Wave device from the controller", "Remove mode enabled");
            var _ = dlg.ShowAsync();
        }

        private void AddDevice_Click(object sender, RoutedEventArgs e)
        {
            Controller.AddNode(false);

            var dlg = new MessageDialog("Please follow the manufacturer's instructions to add the Z-Wave device from the controller", "Add mode enabled");
            var _ = dlg.ShowAsync();
        }

        private void AddSecureDevice_Click(object sender, RoutedEventArgs e)
        {
            Controller.AddNode(true);

            var dlg = new MessageDialog("Please follow the manufacturer's instructions to add the Z-Wave device from the controller", "Add mode enabled");
            var _ = dlg.ShowAsync();
        }

        private void NewPrimary_Click(object sender, RoutedEventArgs e)
        {
            Controller.CreateNewPrimary();
        }

        private void TransferPrimary_Click(object sender, RoutedEventArgs e)
        {
            Controller.TransferPrimaryRole();
        }
    }

    public class ControllerViewVM : INotifyPropertyChanged
    {
        public ControllerViewVM()
        {
        }

        public void UpdateController(Controller controller)
        {
            Controller = controller;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Controller)));
        }
        public Controller Controller { get; private set; }

        public event PropertyChangedEventHandler PropertyChanged;

    }
}


text:
import os
import logging
from pilot.info import infosys
import subprocess
import re

try:
    from google.cloud import storage
except Exception:
    pass
try:
    import pathlib  # Python 3
except Exception:
    pathlib = None

from .common import resolve_common_transfer_errors
from pilot.common.errorcodes import ErrorCodes
from pilot.common.exception import PilotException
from pilot.util.config import config

logger = logging.getLogger(__name__)
errors = ErrorCodes()

require_replicas = False    ## indicates if given copytool requires input replicas to be resolved
require_input_protocols = True    ## indicates if given copytool requires input protocols and manual generation of input replicas
require_protocols = True  ## indicates if given copytool requires protocols to be resolved first for stage-out

allowed_schemas = ['gs', 'srm', 'gsiftp', 'https', 'davs', 'root']

def is_valid_for_copy_in(files):
    return True  ## FIX ME LATER

def is_valid_for_copy_out(files):
    return True  ## FIX ME LATER

def resolve_surl(fspec, protocol, ddmconf, **kwargs):
    """
        Get final destination SURL for file to be transferred to Objectstore
        Can be customized at the level of specific copytool

        :param protocol: suggested protocol
        :param ddmconf: full ddm storage data
        :param fspec: file spec data
        :return: dictionary {'surl': surl}
    """

    try:
        pandaqueue = infosys.pandaqueue
    except Exception:
        pandaqueue = ""
    if pandaqueue is None:
        pandaqueue = ""

    ddm = ddmconf.get(fspec.ddmendpoint)
    if not ddm:
        raise PilotException('failed to resolve ddmendpoint by name=%s' % fspec.ddmendpoint)

    dataset = fspec.dataset
    if dataset:
        dataset = dataset.replace("#{pandaid}", os.environ['PANDAID'])
    else:
        dataset = ""

    remote_path = os.path.join(protocol.get('path', ''), pandaqueue, dataset)
    surl = protocol.get('endpoint', '') + remote_path
    logger.info('For GCS bucket, set surl=%s', surl)

    # example:
    #   protocol = {u'path': u'/atlas-eventservice', u'endpoint': u's3://s3.cern.ch:443/', u'flavour': u'AWS-S3-SSL', u'id': 175}
    #   surl = 's3://s3.cern.ch:443//atlas-eventservice/EventService_premerge_24706191-5013009653-24039149400-322-5.tar'
    return {'surl': surl}

def copy_in(files, **kwargs):
    """
    Download given files from a GCS bucket.

    :param files: list of `FileSpec` objects
    :raise: PilotException in case of controlled error
    """

    for fspec in files:

        dst = fspec.workdir or kwargs.get('workdir') or '.'
        path = os.path.join(dst, fspec.lfn)
        logger.info('downloading surl=%s to local file %s', fspec.surl, path)
        status, diagnostics = download_file(path, fspec.surl, object_name=fspec.lfn)

        if not status:  ## an error occurred
            error = resolve_common_transfer_errors(diagnostics, is_stagein=True)
            fspec.status = 'failed'
            fspec.status_code = error.get('rcode')
            raise PilotException(error.get('error'), code=error.get('rcode'), state=error.get('state'))

        fspec.status_code = 0
        fspec.status = 'transferred'

    return files

def download_file(path, surl, object_name=None):
    """
    Download a file from a GS bucket.

    :param path: Path to local file after download (string).
    :param surl: remote path (string).
    :param object_name: GCS object name. If not specified then file_name from path is used.
    :return: True if file was uploaded (else False), diagnostics (string).
    """

    # if object_name was not specified, use file name from path
    if object_name is None:
        object_name = os.path.basename(path)

    try:
        client = storage.Client()
        target = pathlib.Path(object_name)
        with target.open(mode="wb") as downloaded_file:
            client.download_blob_to_file(surl, downloaded_file)
    except Exception as error:
        diagnostics = 'exception caught in gs client: %s' % error
        logger.critical(diagnostics)
        return False, diagnostics

    return True, ""

def copy_out(files, **kwargs):
    """
    Upload given files to GS storage.

    :param files: list of `FileSpec` objects
    :raise: PilotException in case of controlled error
    """

    workdir = kwargs.pop('workdir')

    if len(files) > 0:
        fspec = files[0]
        # bucket = re.sub(r'gs://(.*?)/.*', r'\1', fspec.turl)
        reobj = re.match(r'gs://([^/]*)/(.*)', fspec.turl)
        (bucket, remote_path) = reobj.groups()

    for fspec in files:
        logger.info('Going to process fspec.turl=%s', fspec.turl)

        logfiles = []
        lfn = fspec.lfn.strip(' ')
        dataset = fspec.dataset
        if lfn == '/' or dataset.endswith('/'):
            # ["pilotlog.txt", "payload.stdout", "payload.stderr"]:
            logfiles = os.listdir(workdir)
        else:
            logfiles = [lfn]

        for logfile in logfiles:
            path = os.path.join(workdir, logfile)
            if os.path.exists(path):
                if logfile == config.Pilot.pilotlog or logfile == config.Payload.payloadstdout or logfile == config.Payload.payloadstderr:
                    content_type = "text/plain"
                    logger.info('Change the file=%s content-type to text/plain', logfile)
                else:
                    content_type = None
                    try:
                        result = subprocess.check_output(["/bin/file", "-i", "-b", "-L", path])
                        if not isinstance(result, str):
                            result = result.decode('utf-8')
                        if result.find(';') > 0:
                            content_type = result.split(';')[0]
                            logger.info('Change the file=%s content-type to %s', logfile, content_type)
                    except Exception:
                        pass

                object_name = os.path.join(remote_path, logfile)
                logger.info('uploading %s to bucket=%s using object name=%s', path, bucket, object_name)
                status, diagnostics = upload_file(path, bucket, object_name=object_name, content_type=content_type)

                if not status:  ## an error occurred
                    # create new error code(s) in ErrorCodes.py and set it/them in resolve_common_transfer_errors()
                    error = resolve_common_transfer_errors(diagnostics, is_stagein=False)
                    fspec.status = 'failed'
                    fspec.status_code = error.get('rcode')
                    raise PilotException(error.get('error'), code=error.get('rcode'), state=error.get('state'))
            else:
                diagnostics = 'local output file does not exist: %s' % path
                logger.warning(diagnostics)
                fspec.status = 'failed'
                fspec.status_code = errors.STAGEOUTFAILED
                raise PilotException(diagnostics, code=fspec.status_code, state=fspec.status)

        fspec.status = 'transferred'
        fspec.status_code = 0

    return files

def upload_file(file_name, bucket, object_name=None, content_type=None):
    """
    Upload a file to a GCS bucket.

    :param file_name: File to upload.
    :param bucket: Bucket to upload to (string).
    :param object_name: GCS object name. If not specified then file_name is used.
    :return: True if file was uploaded (else False), diagnostics (string).
    """

    # if GCS object_name was not specified, use file_name
    if object_name is None:
        object_name = file_name

    # upload the file
    try:
        client = storage.Client()
        gs_bucket = client.get_bucket(bucket)
        # remove any leading slash(es) in object_name
        object_name = object_name.lstrip('/')
        logger.info('uploading a file to bucket=%s in full path=%s in content_type=%s', bucket, object_name, content_type)
        blob = gs_bucket.blob(object_name)
        blob.upload_from_filename(filename=file_name, content_type=content_type)
        if file_name.endswith(config.Pilot.pilotlog):
            url_pilotlog = blob.public_url
            os.environ['GTAG'] = url_pilotlog
            logger.debug("Set envvar GTAG with the pilotLot URL=%s", url_pilotlog)
    except Exception as error:
        diagnostics = 'exception caught in gs client: %s' % error
        logger.critical(diagnostics)
        return False, diagnostics

    return True, ""


text:
<?php
/**
 * File storage on server local disk
 *
 * @class LocalFileStorage
 * @namespace common\components\FileStorage
 */

namespace common\components\FileStorage;

use Yii;

class LocalFileStorage extends FileStorageBase
{
    const STORAGES_TABLE_NAME = 'local_storage_storages';

    const FILES_TABLE_NAME = 'local_storage_files';

    const PROTECTED_STORAGES_DIR_NAME = 'file_storages';

    /**
     * @var string public storages directory name
     */
    protected $_publicStoragesDirectory;

    /**
     * @var string protected storages directory name
     */
    protected $_protectedStoragesDirectory;

    /**
     * @var string storage directory name
     */
    protected $_storageName;

    /**
     * @var integer storageId
     */
    protected $_storageId;

    /**
     * @var \yii\db\Connection
     */
    protected $_dbConnection;

    /**
     * @param array $storageName
     * @param array $options
     * @throws \ErrorException
     */
    public function __construct($storageName, array $options = [])
    {
        $this->_storageName = $storageName;

        if(isset($option['dbConnection']) && $option['dbConnection'] instanceof \yii\db\Connection) {

            $this->_dbConnection = $option['dbConnection'];
        } else {
            $this->_dbConnection = Yii::$app->db;
        }

        if($option['publicStoragesDirectory'] && is_string($option['publicStoragesDirectory'])) {
            $this->_publicStoragesDirectory = $option['publicStoragesDirectory'];
        } else {
            $this->_publicStoragesDirectory = Yii::getAlias('@web') . DIRECTORY_SEPARATOR;
        }

        if($option['protectedStoragesDirectory'] && is_string($option['protectedStoragesDirectory'])) {
            $this->_protectedStoragesDirectory = $option['protectedStoragesDirectory'];
        } else {
            $this->_protectedStoragesDirectory = Yii::getAlias('@common') .
                                                 DIRECTORY_SEPARATOR .
                                                 self::PROTECTED_STORAGES_DIR_NAME .
                                                 DIRECTORY_SEPARATOR;
        }
        if( ! $this->storageExists($storageName)) {
            $this->createNewStorage($storageName);
        }

    }

    /**
     * Getters and Setters
     */

    /**
     * @param string $directoryName
     * @return null|string
     */
    public function setDirectoryName($directoryName)
    {
        if(is_string($directoryName))
        {
            $this->$_directoryName = $directoryName;

            return $this->$_directoryName;
        }

        return null;
    }

    /**
     * @return string
     */
    public function getDirectoryName()
    {
        return $this->$_directoryName;
    }

    /**
     * Abstract class methods realization
     */

    /**
     * @inheritdoc
     */
    protected function storageExists($storageName)
    {
        $tableName = self::STORAGES_TABLE_NAME;
        //checking of db record existence - there should be at least one record with given parameters
        $sql = "SELECT id, public FROM {$tableName} WHERE storage = :storage LIMIT 1";

        $queryResult = $this->_dbConnection->createCommand($sql, [':storage' => $storageName])->queryOne();

        if( $results = ( false !== $queryResult)) {
            $this->_storageId = (int)$queryResult['id'];
            $this->_public = (bool)$queryResult['public'];

            $this->checkStorageDirectory($storageName);

        }

        return $result;
    }

    /**
     * @param string $storageName
     * @return bool
     */
    protected function checkStorageDirectory($storageName)
    {
        // in existed storage should exist at least subFolder with index 0
        $dirName = $this->_directoryName. $storageName . DIRECTORY_SEPARATOR . $this->cipherSubDirectory($storageName, 0);

        return file_exists($dirName);
    }

    /**
     * Generates subFolder name
     *
     * @param  string $storageName
     * @param string|integer $id
     * @return string
     */
    public function cipherSubDirectory($storageName, $id)
    {
        return md5($storageName . $id);
    }

    /**
     * @inheritdoc
     */
    protected function createNewStorage($storageName)
    {

    }

    /**
     * @inheritdoc
     */
    function getFilePath($fileId)
    {

    }

    /**
     * @inheritdoc
     */
    function addFile( $filePath)
    {

    }

    /**
     * @inheritdoc
     */
    function uploadFile( \yii\web\UploadedFile $file)
    {

    }

    /**
     * @inheritdoc
     */
    function setFileTemporal($fileId, $deleteTime)
    {

    }

    /**
     * @inheritdoc
     */
    function setFilePermanent($fileId)
    {

    }
}


text:
const fs = require('fs');
const oneLine = require('common-tags').oneLine;
const Command = require('../base');

module.exports = class LoadCommandCommand extends Command {
	constructor(client) {
		super(client, {
			name: 'load',
			aliases: ['load-command'],
			group: 'commands',
			memberName: 'load',
			description: 'Loads a new command.',
			details: oneLine`
				The argument must be full name of the command in the format of \`group:memberName\`.
				Only the bot owner(s) may use this command.
			`,
			examples: ['load some-command'],
			guarded: true,

			args: [
				{
					key: 'command',
					prompt: 'Which command would you like to load?',
					validate: val => new Promise(resolve => {
						if(!val) return resolve(false);
						const split = val.split(':');
						if(split.length !== 2) return resolve(false);
						if(this.client.registry.findCommands(val).length > 0) {
							return resolve('That command is already registered.');
						}
						const cmdPath = this.client.registry.resolveCommandPath(split[0], split[1]);
						fs.access(cmdPath, fs.constants.R_OK, err => err ? resolve(false) : resolve(true));
						return null;
					}),
					parse: val => {
						const split = val.split(':');
						const cmdPath = this.client.registry.resolveCommandPath(split[0], split[1]);
						delete require.cache[cmdPath];
						return require(cmdPath);
					}
				}
			]
		});
	}

	hasPermission(msg) {
		return this.client.isOwner(msg.author);
	}

	async run(msg, args) {
		this.client.registry.registerCommand(args.command);
		msg.reply(`Loaded \`${this.client.registry.commands.last().name}\` command.`);
		return null;
	}
};


text:
<!DOCTYPE html>

	<title>todo.tab</title>
	<link href='http://fonts.googleapis.com/css?family=Radley:400,400italic' rel='stylesheet' type='text/css'>
  	<link href='http://fonts.googleapis.com/css?family=Noto+Sans:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
  	<link rel="stylesheet" href="style/style.css">
  	<link rel="stylesheet" ng-href="themes/css/{{theme}}.css">

		<input class="modal-state" id="modal-1" type="checkbox" />

Settings

For additional help and information please visit todo.tab on GitHub.

					Color Theme:
					<select name="theme" id="theme-selection" ng-model="theme" ng-change="themeChanged()">
						<option value="default">Default</option>
						<option value="inverted">Inverted</option>
						<option value="sticky">Sticky</option>
						<option value="terminal">Terminal</option>
						<option value="ocean">Ocean</option>
					</select>

					Bullet Type:
					<select name="bullet" id="bullet-selection" ng-model="bullet" ng-change="bulletChanged()">
						<option value="bullet-default">></option>
						<option value="bullet-dash">-</option>
						<option value="bullet-slash">\</option>
						<option value="bullet-none">None</option>
					</select>

Created by Blend88.

			<input type="text" id="title-edit" ng-model="title" ng-change="titleChanged()">

				<input ng-hide="preview" class="todo" id="{{todo.id}}" type="text" value="{{todo.name}}" ng-model="todo.name" ng-change="todosChanged()" todo>

{{markdown}}

			Display Markdown

			Markdown Preview


text:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from tastypie.api import Api
from sxsw.api import PresenterResource, EventResource, TagResource
from django.views.generic import RedirectView, TemplateView
import settings

# API resources
v1_api = Api(api_name='v1')
v1_api.register(PresenterResource())
v1_api.register(EventResource())
v1_api.register(TagResource())

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'sxswtweets.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^api/', include(v1_api.urls)),

    url(r'^sxsw/', include('sxsw.urls')),

    url(r'^admin/', include(admin.site.urls)),

    url(r'^favicon\.ico$', RedirectView.as_view(url='http://' + settings.CLOUDFRONT_DOMAIN + settings.STATIC_DIRECTORY+ 'favicon.ico')),

    url(r'^$', TemplateView.as_view(template_name='index.html')),
)

# if settings.DEBUG:
urlpatterns += patterns('',
    url(r'^search/', include('haystack.urls')),
    url(r'^autocomplete/', TemplateView.as_view(template_name='search/autocomplete.html'))
)

print settings.STATIC_URL + 'favicon.ico'


text:
This is the source for for my personal website [(bhritchie.github.io)](https://bhritchie.github.io/). Or rather, the source is in the source branch.

The site is built with [Jekyll](http://jekyllrb.com) and [Hyde](https://github.com/poole/hyde).

The written content is copyright Brendan Ritchie.


text:
using UnityEngine;
using System.Collections;

public class CubeExplode : MonoBehaviour {
    public GameObject Particle;
    private bool _explode;

    private float _startTime;
    private bool _worked;

    void Awake() {
        _explode = false;
        _worked = false;
    }

    void Update() {
        if (_explode) {
            if (_startTime == 0) {
                _startTime = Time.time;
            }
            var rate = 1 - (Time.time - _startTime);
            //Debug.Log(Mathf.Lerp(0, 1, rate));
            GetComponent<MeshRenderer>().material.SetColor("_Color", new Color(1, Mathf.Lerp(0, 1, rate), Mathf.Lerp(0, 1, rate), 1));
            if (rate < 0) {
                Instantiate(Particle, transform.position, Quaternion.identity);
                gameObject.SetActive(false);
                //Destroy(gameObject);
            }
        }
    }

    public void Work() {
        _worked = true;
    }

    void OnTriggerEnter(Collider collision) {
        if (_worked && collision.gameObject.tag.Equals("Player")) {
            _explode = true;
        }
    }

}


text:
<?php

namespace Eloquent\Phuri\SchemeSpecific\Mailto\Encoding;

use Eloquent\Liberator\Liberator;
use PHPUnit_Framework_TestCase;

/**
 * @covers \Eloquent\Phuri\SchemeSpecific\Mailto\Encoding\MailtoUriHeaderFieldEncoder
 * @covers \Eloquent\Phuri\Encoding\UriEncoder
 */
class MailtoUriHeaderFieldEncoderTest extends PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        parent::setUp();

        $this->encoder = new MailtoUriHeaderFieldEncoder;
    }

    public function encodeData()
    {
        //                           decoded                   encoded
        return array(
            'Basic example' => array('foo bar',                'foo%20bar'),
            'Unreserved'    => array('abcxyzABCXYZ012789-._~', 'abcxyzABCXYZ012789-._~'),
            'Reserved'      => array(':/?#[]@!$&\'()*+,;=',    '%3A%2F%3F%23%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D'),
            'UTF-8'         => array("\xC3\xB6",               '%C3%B6'),
        );
    }

    /**
     * @dataProvider encodeData
     */
    public function testEncodeDecode($decoded, $encoded)
    {
        $this->assertSame($encoded, $this->encoder->encode($decoded));
        $this->assertSame($decoded, $this->encoder->decode($encoded));
    }

    public function encodeNameData()
    {
        //                                decoded                               encoded
        return array(
            'No encoding needed' => array('foo',                                'foo'),
            'Simple example'     => array('foo bar',                            'foo%20bar'),
            'All permissable'    => array('abcxyzABCXYZ012789-._~!$\'()*+,;:@', 'abcxyzABCXYZ012789-._~!$\'()*+,;:@'),
            'Delimiters'         => array('foo?bar&baz=qux',                    'foo%3Fbar%26baz%3Dqux'),
            'Forbidden'          => array('/?#[]&=` ',                          '%2F%3F%23%5B%5D%26%3D%60%20'),
            'UTF-8'              => array("\xC3\xB6",                           '%C3%B6'),
        );
    }

    /**
     * @dataProvider encodeNameData
     */
    public function testEncodeName($decoded, $encoded)
    {
        $this->assertSame($encoded, $this->encoder->encodeName($decoded));
        $this->assertSame($decoded, $this->encoder->decode($encoded));
    }

    public function encodeValueData()
    {
        return $this->encodeNameData();
    }

    /**
     * @dataProvider encodeValueData
     */
    public function testEncodeValue($decoded, $encoded)
    {
        $this->assertSame($encoded, $this->encoder->encodeValue($decoded));
        $this->assertSame($decoded, $this->encoder->decode($encoded));
    }

    public function testInstance()
    {
        $class = Liberator::liberateClass(__NAMESPACE__ . '\MailtoUriHeaderFieldEncoder');
        $class->instance = null;
        $actual = MailtoUriHeaderFieldEncoder::instance();

        $this->assertInstanceOf(__NAMESPACE__ . '\MailtoUriHeaderFieldEncoder', $actual);
        $this->assertSame($actual, MailtoUriHeaderFieldEncoder::instance());
    }
}


text:
"use strict";

(function()
{
    v86util.SyncBuffer = SyncBuffer;
    v86util.AsyncXHRBuffer = AsyncXHRBuffer;
    v86util.AsyncXHRPartfileBuffer = AsyncXHRPartfileBuffer;
    v86util.AsyncFileBuffer = AsyncFileBuffer;
    v86util.SyncFileBuffer = SyncFileBuffer;

    // The smallest size the emulated hardware can emit
    const BLOCK_SIZE = 256;

    const ASYNC_SAFE = false;

    /**
     * Synchronous access to ArrayBuffer
     * @constructor
     */
    function SyncBuffer(buffer)
    {
        dbg_assert(buffer instanceof ArrayBuffer);

        this.buffer = buffer;
        this.byteLength = buffer.byteLength;
        this.onload = undefined;
        this.onprogress = undefined;
    }

    SyncBuffer.prototype.load = function()
    {
        this.onload && this.onload({ buffer: this.buffer });
    };

    /**
     * @this {SyncBuffer|SyncFileBuffer}
     * @param {number} start
     * @param {number} len
     * @param {function(!Uint8Array)} fn
     */
    SyncBuffer.prototype.get = function(start, len, fn)
    {
        dbg_assert(start + len <= this.byteLength);
        fn(new Uint8Array(this.buffer, start, len));
    };

    /**
     * @this {SyncBuffer|SyncFileBuffer}
     * @param {number} start
     * @param {!Uint8Array} slice
     * @param {function()} fn
     */
    SyncBuffer.prototype.set = function(start, slice, fn)
    {
        dbg_assert(start + slice.byteLength <= this.byteLength);

        new Uint8Array(this.buffer, start, slice.byteLength).set(slice);
        fn();
    };

    /**
     * @this {SyncBuffer|SyncFileBuffer}
     * @param {function(!ArrayBuffer)} fn
     */
    SyncBuffer.prototype.get_buffer = function(fn)
    {
        fn(this.buffer);
    };

    /**
     * @this {SyncBuffer|SyncFileBuffer}
     */
    SyncBuffer.prototype.get_state = function()
    {
        const state = [];
        state[0] = this.byteLength;
        state[1] = new Uint8Array(this.buffer);
        return state;
    };

    /**
     * @this {SyncBuffer|SyncFileBuffer}
     */
    SyncBuffer.prototype.set_state = function(state)
    {
        this.byteLength = state[0];
        this.buffer = state[1].slice().buffer;
    };

    /**
     * Asynchronous access to ArrayBuffer, loading blocks lazily as needed,
     * using the `Range: bytes=...` header
     *
     * @constructor
     * @param {string} filename Name of the file to download
     * @param {number|undefined} size
     * @param {number|undefined} fixed_chunk_size
     */
    function AsyncXHRBuffer(filename, size, fixed_chunk_size)
    {
        this.filename = filename;

        this.byteLength = size;

        this.block_cache = new Map();
        this.block_cache_is_write = new Set();

        this.fixed_chunk_size = fixed_chunk_size;
        this.cache_reads = !!fixed_chunk_size; // TODO: could also be useful in other cases (needs testing)

        this.onload = undefined;
        this.onprogress = undefined;
    }

    AsyncXHRBuffer.prototype.load = function()
    {
        if(this.byteLength !== undefined)
        {
            this.onload && this.onload(Object.create(null));
            return;
        }

        // Determine the size using a request

        determine_size(this.filename, (error, size) =>
        {
            if(error)
            {
                throw new Error("Cannot use: " + this.filename + ". " + error);
            }
            else
            {
                dbg_assert(size >= 0);
                this.byteLength = size;
                this.onload && this.onload(Object.create(null));
            }
        });
    };

    /**
     * @param {number} offset
     * @param {number} len
     * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer}
     */
    AsyncXHRBuffer.prototype.get_from_cache = function(offset, len)
    {
        var number_of_blocks = len / BLOCK_SIZE;
        var block_index = offset / BLOCK_SIZE;

        for(var i = 0; i < number_of_blocks; i++)
        {
            var block = this.block_cache.get(block_index + i);

            if(!block)
            {
                return;
            }
        }

        if(number_of_blocks === 1)
        {
            return this.block_cache.get(block_index);
        }
        else
        {
            var result = new Uint8Array(len);
            for(var i = 0; i < number_of_blocks; i++)
            {
                result.set(this.block_cache.get(block_index + i), i * BLOCK_SIZE);
            }
            return result;
        }
    };

    /**
     * @param {number} offset
     * @param {number} len
     * @param {function(!Uint8Array)} fn
     */
    AsyncXHRBuffer.prototype.get = function(offset, len, fn)
    {
        dbg_assert(offset + len <= this.byteLength);
        dbg_assert(offset % BLOCK_SIZE === 0);
        dbg_assert(len % BLOCK_SIZE === 0);
        dbg_assert(len);

        var block = this.get_from_cache(offset, len);
        if(block)
        {
            if(ASYNC_SAFE)
            {
                setTimeout(fn.bind(this, block), 0);
            }
            else
            {
                fn(block);
            }
            return;
        }

        var requested_start = offset;
        var requested_length = len;
        if(this.fixed_chunk_size)
        {
            requested_start = offset - (offset % this.fixed_chunk_size);
            requested_length = Math.ceil((offset - requested_start + len) / this.fixed_chunk_size) * this.fixed_chunk_size;
        }

        v86util.load_file(this.filename, {
            done: function done(buffer)
            {
                var block = new Uint8Array(buffer);
                this.handle_read(requested_start, requested_length, block);
                if(requested_start === offset && requested_length === len)
                {
                    fn(block);
                }
                else
                {
                    fn(block.subarray(offset - requested_start, offset - requested_start + len));
                }
            }.bind(this),
            range: { start: requested_start, length: requested_length },
        });
    };

    /**
     * Relies on this.byteLength and this.block_cache
     *
     * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer}
     *
     * @param {number} start
     * @param {!Uint8Array} data
     * @param {function()} fn
     */
    AsyncXHRBuffer.prototype.set = function(start, data, fn)
    {
        var len = data.length;
        dbg_assert(start + data.byteLength <= this.byteLength);
        dbg_assert(start % BLOCK_SIZE === 0);
        dbg_assert(len % BLOCK_SIZE === 0);
        dbg_assert(len);

        var start_block = start / BLOCK_SIZE;
        var block_count = len / BLOCK_SIZE;

        for(var i = 0; i < block_count; i++)
        {
            var block = this.block_cache.get(start_block + i);

            if(block === undefined)
            {
                const data_slice = data.slice(i * BLOCK_SIZE, (i + 1) * BLOCK_SIZE);
                this.block_cache.set(start_block + i, data_slice);
            }
            else
            {
                const data_slice = data.subarray(i * BLOCK_SIZE, (i + 1) * BLOCK_SIZE);
                dbg_assert(block.byteLength === data_slice.length);
                block.set(data_slice);
            }

            this.block_cache_is_write.add(start_block + i);
        }

        fn();
    };

    /**
     * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer}
     * @param {number} offset
     * @param {number} len
     * @param {!Uint8Array} block
     */
    AsyncXHRBuffer.prototype.handle_read = function(offset, len, block)
    {
        // Used by AsyncXHRBuffer, AsyncXHRPartfileBuffer and AsyncFileBuffer
        // Overwrites blocks from the original source that have been written since

        var start_block = offset / BLOCK_SIZE;
        var block_count = len / BLOCK_SIZE;

        for(var i = 0; i < block_count; i++)
        {
            const cached_block = this.block_cache.get(start_block + i);

            if(cached_block)
            {
                block.set(cached_block, i * BLOCK_SIZE);
            }
            else if(this.cache_reads)
            {
                this.block_cache.set(start_block + i, block.slice(i * BLOCK_SIZE, (i + 1) * BLOCK_SIZE));
            }
        }
    };

    AsyncXHRBuffer.prototype.get_buffer = function(fn)
    {
        // We must download all parts, unlikely a good idea for big files
        fn();
    };

    ///**
    // * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer}
    // */
    //AsyncXHRBuffer.prototype.get_block_cache = function()
    //{
    //    var count = Object.keys(this.block_cache).length;

    //    var buffer = new Uint8Array(count * BLOCK_SIZE);
    //    var indices = [];

    //    var i = 0;
    //    for(var index of Object.keys(this.block_cache))
    //    {
    //        var block = this.block_cache.get(index);
    //        dbg_assert(block.length === BLOCK_SIZE);
    //        index = +index;
    //        indices.push(index);
    //        buffer.set(
    //            block,
    //            i * BLOCK_SIZE
    //        );
    //        i++;
    //    }

    //    return {
    //        buffer,
    //        indices,
    //        block_size: BLOCK_SIZE,
    //    };
    //};

    /**
     * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer}
     */
    AsyncXHRBuffer.prototype.get_state = function()
    {
        const state = [];
        const block_cache = [];

        for(let [index, block] of this.block_cache)
        {
            dbg_assert(isFinite(index));
            if(this.block_cache_is_write.has(index))
            {
                block_cache.push([index, block]);
            }
        }

        state[0] = block_cache;
        return state;
    };

    /**
     * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer}
     */
    AsyncXHRBuffer.prototype.set_state = function(state)
    {
        const block_cache = state[0];
        this.block_cache.clear();
        this.block_cache_is_write.clear();

        for(let [index, block] of block_cache)
        {
            dbg_assert(isFinite(index));
            this.block_cache.set(index, block);
            this.block_cache_is_write.add(index);
        }
    };

    /**
     * Asynchronous access to ArrayBuffer, loading blocks lazily as needed,
     * downloading files named filename-%d-%d.ext (where the %d are start and end offset).
     * Or, if partfile_alt_format is set, filename-%08d.ext (where %d is the part number, compatible with gnu split).
     *
     * @constructor
     * @param {string} filename Name of the file to download
     * @param {number|undefined} size
     * @param {number|undefined} fixed_chunk_size
     * @param {boolean|undefined} partfile_alt_format
     */
    function AsyncXHRPartfileBuffer(filename, size, fixed_chunk_size, partfile_alt_format)
    {
        const parts = filename.match(/(.*)(\..*)/);

        if(parts)
        {
            this.basename = parts[1];
            this.extension = parts[2];
        }
        else
        {
            this.basename = filename;
            this.extension = "";
        }

        if(!this.basename.endsWith("/"))
        {
            this.basename += "-";
        }

        this.block_cache = new Map();
        this.block_cache_is_write = new Set();

        this.byteLength = size;
        this.fixed_chunk_size = fixed_chunk_size;
        this.partfile_alt_format = !!partfile_alt_format;

        this.cache_reads = !!fixed_chunk_size; // TODO: could also be useful in other cases (needs testing)

        this.onload = undefined;
        this.onprogress = undefined;
    }

    AsyncXHRPartfileBuffer.prototype.load = function()
    {
        if(this.byteLength !== undefined)
        {
            this.onload && this.onload(Object.create(null));
            return;
        }
        dbg_assert(false);
        this.onload && this.onload(Object.create(null));
    };

    /**
     * @param {number} offset
     * @param {number} len
     * @param {function(!Uint8Array)} fn
     */
    AsyncXHRPartfileBuffer.prototype.get = function(offset, len, fn)
    {
        dbg_assert(offset + len <= this.byteLength);
        dbg_assert(offset % BLOCK_SIZE === 0);
        dbg_assert(len % BLOCK_SIZE === 0);
        dbg_assert(len);

        const block = this.get_from_cache(offset, len);

        if(block)
        {
            if(ASYNC_SAFE)
            {
                setTimeout(fn.bind(this, block), 0);
            }
            else
            {
                fn(block);
            }
            return;
        }

        if(this.fixed_chunk_size)
        {
            const start_index = Math.floor(offset / this.fixed_chunk_size);
            const m_offset = offset - start_index * this.fixed_chunk_size;
            dbg_assert(m_offset >= 0);
            const total_count = Math.ceil((m_offset + len) / this.fixed_chunk_size);
            const blocks = new Uint8Array(total_count * this.fixed_chunk_size);
            let finished = 0;

            for(let i = 0; i < total_count; i++)
            {
                const offset = (start_index + i) * this.fixed_chunk_size;

                const part_filename =
                    this.partfile_alt_format ?
                        // matches output of gnu split:
                        //   split -b 512 -a8 -d --additional-suffix .img w95.img w95-
                        this.basename + (start_index + i + "").padStart(8, "0") + this.extension
                    :
                        this.basename + offset + "-" + (offset + this.fixed_chunk_size) + this.extension;

                // XXX: unnecessary allocation
                const block = this.get_from_cache(offset, this.fixed_chunk_size);

                if(block)
                {
                    const cur = i * this.fixed_chunk_size;
                    blocks.set(block, cur);
                    finished++;
                    if(finished === total_count)
                    {
                        const tmp_blocks = blocks.subarray(m_offset, m_offset + len);
                        fn(tmp_blocks);
                    }
                }
                else
                {
                    v86util.load_file(part_filename, {
                        done: function done(buffer)
                        {
                            const cur = i * this.fixed_chunk_size;
                            const block = new Uint8Array(buffer);
                            this.handle_read((start_index + i) * this.fixed_chunk_size, this.fixed_chunk_size|0, block);
                            blocks.set(block, cur);
                            finished++;
                            if(finished === total_count)
                            {
                                const tmp_blocks = blocks.subarray(m_offset, m_offset + len);
                                fn(tmp_blocks);
                            }
                        }.bind(this),
                    });
                }
            }
        }
        else
        {
            const part_filename = this.basename + offset + "-" + (offset + len) + this.extension;

            v86util.load_file(part_filename, {
                done: function done(buffer)
                {
                    dbg_assert(buffer.byteLength === len);
                    var block = new Uint8Array(buffer);
                    this.handle_read(offset, len, block);
                    fn(block);
                }.bind(this),
            });
        }
    };

    AsyncXHRPartfileBuffer.prototype.get_from_cache = AsyncXHRBuffer.prototype.get_from_cache;
    AsyncXHRPartfileBuffer.prototype.set = AsyncXHRBuffer.prototype.set;
    AsyncXHRPartfileBuffer.prototype.handle_read = AsyncXHRBuffer.prototype.handle_read;
    //AsyncXHRPartfileBuffer.prototype.get_block_cache = AsyncXHRBuffer.prototype.get_block_cache;
    AsyncXHRPartfileBuffer.prototype.get_state = AsyncXHRBuffer.prototype.get_state;
    AsyncXHRPartfileBuffer.prototype.set_state = AsyncXHRBuffer.prototype.set_state;

    /**
     * Synchronous access to File, loading blocks from the input type=file
     * The whole file is loaded into memory during initialisation
     *
     * @constructor
     */
    function SyncFileBuffer(file)
    {
        this.file = file;
        this.byteLength = file.size;

        if(file.size > (1 << 30))
        {
            console.warn("SyncFileBuffer: Allocating buffer of " + (file.size >> 20) + " MB ...");
        }

        this.buffer = new ArrayBuffer(file.size);

        this.onload = undefined;
        this.onprogress = undefined;
    }

    SyncFileBuffer.prototype.load = function()
    {
        this.load_next(0);
    };

    /**
     * @param {number} start
     */
    SyncFileBuffer.prototype.load_next = function(start)
    {
        /** @const */
        var PART_SIZE = 4 << 20;

        var filereader = new FileReader();

        filereader.onload = function(e)
        {
            var buffer = new Uint8Array(e.target.result);
            new Uint8Array(this.buffer, start).set(buffer);
            this.load_next(start + PART_SIZE);
        }.bind(this);

        if(this.onprogress)
        {
            this.onprogress({
                loaded: start,
                total: this.byteLength,
                lengthComputable: true,
            });
        }

        if(start < this.byteLength)
        {
            var end = Math.min(start + PART_SIZE, this.byteLength);
            var slice = this.file.slice(start, end);
            filereader.readAsArrayBuffer(slice);
        }
        else
        {
            this.file = undefined;
            this.onload && this.onload({ buffer: this.buffer });
        }
    };

    SyncFileBuffer.prototype.get = SyncBuffer.prototype.get;
    SyncFileBuffer.prototype.set = SyncBuffer.prototype.set;
    SyncFileBuffer.prototype.get_buffer = SyncBuffer.prototype.get_buffer;
    SyncFileBuffer.prototype.get_state = SyncBuffer.prototype.get_state;
    SyncFileBuffer.prototype.set_state = SyncBuffer.prototype.set_state;

    /**
     * Asynchronous access to File, loading blocks from the input type=file
     *
     * @constructor
     */
    function AsyncFileBuffer(file)
    {
        this.file = file;
        this.byteLength = file.size;

        this.block_cache = new Map();
        this.block_cache_is_write = new Set();

        this.onload = undefined;
        this.onprogress = undefined;
    }

    AsyncFileBuffer.prototype.load = function()
    {
        this.onload && this.onload(Object.create(null));
    };

    /**
     * @param {number} offset
     * @param {number} len
     * @param {function(!Uint8Array)} fn
     */
    AsyncFileBuffer.prototype.get = function(offset, len, fn)
    {
        dbg_assert(offset % BLOCK_SIZE === 0);
        dbg_assert(len % BLOCK_SIZE === 0);
        dbg_assert(len);

        var block = this.get_from_cache(offset, len);
        if(block)
        {
            fn(block);
            return;
        }

        var fr = new FileReader();

        fr.onload = function(e)
        {
            var buffer = e.target.result;
            var block = new Uint8Array(buffer);

            this.handle_read(offset, len, block);
            fn(block);
        }.bind(this);

        fr.readAsArrayBuffer(this.file.slice(offset, offset + len));
    };
    AsyncFileBuffer.prototype.get_from_cache = AsyncXHRBuffer.prototype.get_from_cache;
    AsyncFileBuffer.prototype.set = AsyncXHRBuffer.prototype.set;
    AsyncFileBuffer.prototype.handle_read = AsyncXHRBuffer.prototype.handle_read;
    AsyncFileBuffer.prototype.get_state = AsyncXHRBuffer.prototype.get_state;
    AsyncFileBuffer.prototype.set_state = AsyncXHRBuffer.prototype.set_state;

    AsyncFileBuffer.prototype.get_buffer = function(fn)
    {
        // We must load all parts, unlikely a good idea for big files
        fn();
    };

    AsyncFileBuffer.prototype.get_as_file = function(name)
    {
        var parts = [];
        var existing_blocks = Array.from(this.block_cache.keys()).sort(function(x, y) { return x - y; });

        var current_offset = 0;

        for(var i = 0; i < existing_blocks.length; i++)
        {
            var block_index = existing_blocks[i];
            var block = this.block_cache.get(block_index);
            var start = block_index * BLOCK_SIZE;
            dbg_assert(start >= current_offset);

            if(start !== current_offset)
            {
                parts.push(this.file.slice(current_offset, start));
                current_offset = start;
            }

            parts.push(block);
            current_offset += block.length;
        }

        if(current_offset !== this.file.size)
        {
            parts.push(this.file.slice(current_offset));
        }

        var file = new File(parts, name);
        dbg_assert(file.size === this.file.size);

        return file;
    };

    if(typeof XMLHttpRequest === "undefined")
    {
        var determine_size = function(path, cb)
        {
            require("fs")["stat"](path, (err, stats) =>
            {
                if(err)
                {
                    cb(err);
                }
                else
                {
                    cb(null, stats.size);
                }
            });
        };
    }
    else
    {
        var determine_size = function(url, cb)
        {
            v86util.load_file(url, {
                done: (buffer, http) =>
                {
                    var header = http.getResponseHeader("Content-Range") || "";
                    var match = header.match(/\/(\d+)\s*$/);

                    if(match)
                    {
                        cb(null, +match[1]);
                    }
                    else
                    {
                        const error = "`Range: bytes=...` header not supported (Got `" + header + "`)";
                        cb(error);
                    }
                },
                headers: {
                    Range: "bytes=0-0",
                }
            });
        };
    }
})();


text:
package com.thoughtworks.go.server.service;

import com.thoughtworks.go.config.materials.svn.SvnMaterial;
import com.thoughtworks.go.helper.MaterialsMother;
import com.thoughtworks.go.server.domain.ServerMaintenanceMode;
import com.thoughtworks.go.util.SystemEnvironment;
import com.thoughtworks.go.util.TimeProvider;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.Date;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;

public class MaintenanceModeServiceTest {
    private TimeProvider timeProvider;
    private MaintenanceModeService maintenanceModeService;
    private SystemEnvironment systemEnvironment;

    @BeforeEach
    void setUp() {
        System.setProperty(SystemEnvironment.START_IN_MAINTENANCE_MODE.propertyName(), "false");
        timeProvider = new TimeProvider();
        systemEnvironment = new SystemEnvironment();
        maintenanceModeService = new MaintenanceModeService(timeProvider, systemEnvironment);
    }

    @Test
    void shouldSetMaintenanceModeServiceToFalseOnStartup() {
        assertThat(maintenanceModeService.isMaintenanceMode()).isFalse();
    }

    @Test
    void shouldSetMaintenanceModeServiceToTrueWhenServerIsStartedInMaintenanceMode() {
        System.setProperty(SystemEnvironment.START_IN_MAINTENANCE_MODE.propertyName(), "true");
        maintenanceModeService = new MaintenanceModeService(timeProvider, systemEnvironment);

        assertThat(maintenanceModeService.isMaintenanceMode()).isTrue();
        assertThat(maintenanceModeService.updatedBy()).isEqualTo("GoCD");
    }

    @Test
    void shouldUpdateMaintenanceModeSettings() {
        assertThat(maintenanceModeService.isMaintenanceMode()).isFalse();
        maintenanceModeService.update(new ServerMaintenanceMode(true, "admin", new Date()));
        assertThat(maintenanceModeService.isMaintenanceMode()).isTrue();
    }

    @Test
    void shouldGetRunningMDUs() {
        assertThat(maintenanceModeService.getRunningMDUs()).hasSize(0);
        SvnMaterial svnMaterial = MaterialsMother.svnMaterial();

        maintenanceModeService.mduStartedForMaterial(svnMaterial);

        assertThat(maintenanceModeService.getRunningMDUs()).hasSize(1);
    }

    @Test
    void shouldRemoveMDUFromRunningMDUsListOnMDUFinish() {
        SvnMaterial svnMaterial = MaterialsMother.svnMaterial();

        maintenanceModeService.mduStartedForMaterial(svnMaterial);
        assertThat(maintenanceModeService.getRunningMDUs()).hasSize(1);

        maintenanceModeService.mduFinishedForMaterial(svnMaterial);
        assertThat(maintenanceModeService.getRunningMDUs()).hasSize(0);
    }

    @Test
    void shouldReturnUpdatedOnTimeWhenServerIsInMaintenanceMode() {
        DateTime dateTime = new DateTime(2019, 6, 18, 14, 30, 15, DateTimeZone.UTC);
        maintenanceModeService.update(new ServerMaintenanceMode(true, "admin", dateTime.toDate()));
        assertThat(maintenanceModeService.updatedOn()).isEqualTo("2019-06-18T14:30:15Z");
    }

    @Test
    void shouldThrowServerNotInMaintenanceModeExceptionForUpdatedOnWhenServerIsNotInMaintenanceMode() {
        assertThatCode(maintenanceModeService::updatedOn)
                .isInstanceOf(IllegalStateException.class)
                .hasMessage("GoCD server is not in maintenance mode!");
    }

    @Test
    void shouldReturnUsernameWhenServerIsInMaintenanceMode() {
        maintenanceModeService.update(new ServerMaintenanceMode(true, "admin", new Date()));
        assertThat(maintenanceModeService.updatedBy()).isEqualTo("admin");
    }

    @Test
    void shouldThrowServerNotInMaintenanceModeExceptionForUpdatedByWhenServerIsNotInMaintenanceMode() {
        assertThatCode(maintenanceModeService::updatedBy)
                .isInstanceOf(IllegalStateException.class)
                .hasMessage("GoCD server is not in maintenance mode!");
    }
}


text:
'use strict'

const fs = require('fs')

const utils = {
  fstat (file) {
    try {
      return fs.statSync(file)
    } catch (err) {
      return false
    }
  },
  findComments (text) {
    let ranges = []
    let ruleMap = {
      '//': '\n',
      '/*': '*/'
    }
    let startRule = /\/\/|\/\*/g
    let matches

    while (matches = startRule.exec(text)) {  // eslint-disable-line
      let endChars = ruleMap[matches[0]]
      let start = startRule.lastIndex - matches[0].length
      let end = text.indexOf(endChars, startRule.lastIndex)

      if (end < 0) {
        end = Infinity
      }

      ranges.push([ start, end ])

      startRule.lastIndex = end
    }

    return ranges
  }
}

module.exports = utils


text:
<?php include_once('../credentials.php');
// Define Variables
$error      = false;
$message    = array();

$api_key    = $_REQUEST['apiKey'];
$email      = $_REQUEST['email'];
$password   = $_REQUEST['password'];

// Check API Key
if ($api_key != $APIKEY) {
    $error = true;
    $message[] = "Invalid API Key or No API Key Specified!";
}

// Try Database Connection
if (!$error) {
    try {
        $connection = new PDO("mysql:host=$HOST;dbname=$DB", $USER, $PASS);
        $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $connection = null;
    } catch (PDOException $e) {
        $error = true;
        $message[] = $e->getMessage();
    } catch (Exception $e) {
        $error = true;
        $message[] = $e->getMessage();
    }
}

// Test Parameters
if (!$error) {
    if ($email == null || !isset($email)) {
        $error = true;
        $message[] = "[email] was not passed as a parameter!";
    }
    if ($password == null || !isset($password)) {
        $error = true;
        $message[] = "[password] was not passed as a parameter!";
    }
}

// Query Database
if (!$error) {
    try {
        // Create Connection & Query
        $connection = new PDO("mysql:host=$HOST;dbname=$DB", $USER, $PASS);
        $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $statement = $connection->prepare("SELECT customerID, name, joinDate, address, city, state, zipcode, phone FROM customers WHERE email = :email AND password = :password;");
        $statement->bindParam(':email', $email);
        $statement->bindParam(':password', $password);

        // Execute Query & Retrieve Result
        $resultsArray = array();
        $statement->execute();
        $resultsArray = $statement->fetchAll(PDO::FETCH_ASSOC);

        // Convert & Display Result in JSON Format
        header('Content-type: text/javascript');
        echo json_encode((array('Results' => $resultsArray)), JSON_PRETTY_PRINT);
    } catch (PDOException $e) {
        $error = true;
        $message[] = $e->getMessage();
    } catch (Exception $e) {
        $error = true;
        $message[] = $e->getMessage();
    }
}

// Return Error/ Result
if ($error) {
    // Convert & Display Result in JSON Format
    header('Content-type: text/javascript');
    echo json_encode((array('Results' => (array('Valid' => $message)))), JSON_PRETTY_PRINT);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Arthonia rubrofuscescens Vain.

### Remarks
null


text:
from django.apps import AppConfig

class DjangoPPHAppConfig(AppConfig):
    name = 'django_pph'
    verbose_name = "Django Poly Pass Hash"


text:
import {Directive, Inject, InjectionToken, Optional} from '@angular/core';
import {TemplateDrivenErrors} from './template_driven_errors';

/**
 * @description
 * `InjectionToken` to provide to turn off the warning when using 'ngForm' deprecated selector.
 */
export const NG_FORM_SELECTOR_WARNING = new InjectionToken('NgFormSelectorWarning');

/**
 * This directive is solely used to display warnings when the deprecated `ngForm` selector is used.
 *
 * @deprecated in Angular v6 and will be removed in Angular v9.
 * @ngModule FormsModule
 * @publicApi
 */
@Directive({selector: 'ngForm'})
export class NgFormSelectorWarning {
  /**
   * Static property used to track whether the deprecation warning for this selector has been sent.
   * Used to support warning config of "once".
   *
   * @internal
   */
  static _ngFormWarning = false;

  constructor(@Optional() @Inject(NG_FORM_SELECTOR_WARNING) ngFormWarning: string|null) {
    if (((!ngFormWarning || ngFormWarning === 'once') && !NgFormSelectorWarning._ngFormWarning) ||
        ngFormWarning === 'always') {
      TemplateDrivenErrors.ngFormWarning();
      NgFormSelectorWarning._ngFormWarning = true;
    }
  }
}


text:
package com.amazonaws.services.apigateway.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * Represents a unique identifier for a version of a deployed RestApi that is callable by users.
 *

 *
 Deploy an API

 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetStageResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The identifier of the Deployment that the stage points to.
     *

     */
    private String deploymentId;
    /**
     *

     * The identifier of a client certificate for an API stage.
     *

     */
    private String clientCertificateId;
    /**
     *

     * The name of the stage is the first path segment in the Uniform Resource Identifier (URI) of a call to Amazon API
     * Gateway.
     *

     */
    private String stageName;
    /**
     *

     * The stage's description.
     *

     */
    private String description;
    /**
     *

     * Specifies whether a cache cluster is enabled for the stage.
     *

     */
    private Boolean cacheClusterEnabled;
    /**
     *

     * The size of the cache cluster for the stage, if enabled.
     *

     */
    private String cacheClusterSize;
    /**
     *

     * The status of the cache cluster for the stage, if enabled.
     *

     */
    private String cacheClusterStatus;
    /**
     *

     * A map that defines the method settings for a Stage resource. Keys (designated as
     * /{method_setting_key below) are method paths defined as {resource_path}/{http_method}
     * for an individual method override, or /\*/\* for overriding all methods in the stage.
     *

     */
    private java.util.Map<String, MethodSetting> methodSettings;
    /**
     *

     * A map that defines the stage variables for a Stage resource. Variable names can have alphanumeric and
     * underscore characters, and the values must match [A-Za-z0-9-._~:/?#&=,]+.
     *

     */
    private java.util.Map<String, String> variables;
    /**
     *

     * The version of the associated API documentation.
     *

     */
    private String documentationVersion;
    /**
     *

     * The timestamp when the stage was created.
     *

     */
    private java.util.Date createdDate;
    /**
     *

     * The timestamp when the stage last updated.
     *

     */
    private java.util.Date lastUpdatedDate;

    /**
     *

     * The identifier of the Deployment that the stage points to.
     *

     *
     * @param deploymentId
     *        The identifier of the Deployment that the stage points to.
     */

    public void setDeploymentId(String deploymentId) {
        this.deploymentId = deploymentId;
    }

    /**
     *

     * The identifier of the Deployment that the stage points to.
     *

     *
     * @return The identifier of the Deployment that the stage points to.
     */

    public String getDeploymentId() {
        return this.deploymentId;
    }

    /**
     *

     * The identifier of the Deployment that the stage points to.
     *

     *
     * @param deploymentId
     *        The identifier of the Deployment that the stage points to.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetStageResult withDeploymentId(String deploymentId) {
        setDeploymentId(deploymentId);
        return this;
    }

    /**
     *

     * The identifier of a client certificate for an API stage.
     *

     *
     * @param clientCertificateId
     *        The identifier of a client certificate for an API stage.
     */

    public void setClientCertificateId(String clientCertificateId) {
        this.clientCertificateId = clientCertificateId;
    }

    /**
     *

     * The identifier of a client certificate for an API stage.
     *

     *
     * @return The identifier of a client certificate for an API stage.
     */

    public String getClientCertificateId() {
        return this.clientCertificateId;
    }

    /**
     *

     * The identifier of a client certificate for an API stage.
     *

     *
     * @param clientCertificateId
     *        The identifier of a client certificate for an API stage.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetStageResult withClientCertificateId(String clientCertificateId) {
        setClientCertificateId(clientCertificateId);
        return this;
    }

    /**
     *

     * The name of the stage is the first path segment in the Uniform Resource Identifier (URI) of a call to Amazon API
     * Gateway.
     *

     *
     * @param stageName
     *        The name of the stage is the first path segment in the Uniform Resource Identifier (URI) of a call to
     *        Amazon API Gateway.
     */

    public void setStageName(String stageName) {
        this.stageName = stageName;
    }

    /**
     *

     * The name of the stage is the first path segment in the Uniform Resource Identifier (URI) of a call to Amazon API
     * Gateway.
     *

     *
     * @return The name of the stage is the first path segment in the Uniform Resource Identifier (URI) of a call to
     *         Amazon API Gateway.
     */

    public String getStageName() {
        return this.stageName;
    }

    /**
     *

     * The name of the stage is the first path segment in the Uniform Resource Identifier (URI) of a call to Amazon API
     * Gateway.
     *

     *
     * @param stageName
     *        The name of the stage is the first path segment in the Uniform Resource Identifier (URI) of a call to
     *        Amazon API Gateway.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetStageResult withStageName(String stageName) {
        setStageName(stageName);
        return this;
    }

    /**
     *

     * The stage's description.
     *

     *
     * @param description
     *        The stage's description.
     */

    public void setDescription(String description) {
        this.description = description;
    }

    /**
     *

     * The stage's description.
     *

     *
     * @return The stage's description.
     */

    public String getDescription() {
        return this.description;
    }

    /**
     *

     * The stage's description.
     *

     *
     * @param description
     *        The stage's description.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetStageResult withDescription(String description) {
        setDescription(description);
        return this;
    }

    /**
     *

     * Specifies whether a cache cluster is enabled for the stage.
     *

     *
     * @param cacheClusterEnabled
     *        Specifies whether a cache cluster is enabled for the stage.
     */

    public void setCacheClusterEnabled(Boolean cacheClusterEnabled) {
        this.cacheClusterEnabled = cacheClusterEnabled;
    }

    /**
     *

     * Specifies whether a cache cluster is enabled for the stage.
     *

     *
     * @return Specifies whether a cache cluster is enabled for the stage.
     */

    public Boolean getCacheClusterEnabled() {
        return this.cacheClusterEnabled;
    }

    /**
     *

     * Specifies whether a cache cluster is enabled for the stage.
     *

     *
     * @param cacheClusterEnabled
     *        Specifies whether a cache cluster is enabled for the stage.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetStageResult withCacheClusterEnabled(Boolean cacheClusterEnabled) {
        setCacheClusterEnabled(cacheClusterEnabled);
        return this;
    }

    /**
     *

     * Specifies whether a cache cluster is enabled for the stage.
     *

     *
     * @return Specifies whether a cache cluster is enabled for the stage.
     */

    public Boolean isCacheClusterEnabled() {
        return this.cacheClusterEnabled;
    }

    /**
     *

     * The size of the cache cluster for the stage, if enabled.
     *

     *
     * @param cacheClusterSize
     *        The size of the cache cluster for the stage, if enabled.
     */

    public void setCacheClusterSize(String cacheClusterSize) {
        this.cacheClusterSize = cacheClusterSize;
    }

    /**
     *

     * The size of the cache cluster for the stage, if enabled.
     *

     *
     * @return The size of the cache cluster for the stage, if enabled.
     */

    public String getCacheClusterSize() {
        return this.cacheClusterSize;
    }

    /**
     *

     * The size of the cache cluster for the stage, if enabled.
     *

     *
     * @param cacheClusterSize
     *        The size of the cache cluster for the stage, if enabled.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetStageResult withCacheClusterSize(String cacheClusterSize) {
        setCacheClusterSize(cacheClusterSize);
        return this;
    }

    /**
     *

     * The status of the cache cluster for the stage, if enabled.
     *

     *
     * @param cacheClusterStatus
     *        The status of the cache cluster for the stage, if enabled.
     * @see CacheClusterStatus
     */

    public void setCacheClusterStatus(String cacheClusterStatus) {
        this.cacheClusterStatus = cacheClusterStatus;
    }

    /**
     *

     * The status of the cache cluster for the stage, if enabled.
     *

     *
     * @return The status of the cache cluster for the stage, if enabled.
     * @see CacheClusterStatus
     */

    public String getCacheClusterStatus() {
        return this.cacheClusterStatus;
    }

    /**
     *

     * The status of the cache cluster for the stage, if enabled.
     *

     *
     * @param cacheClusterStatus
     *        The status of the cache cluster for the stage, if enabled.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see CacheClusterStatus
     */

    public GetStageResult withCacheClusterStatus(String cacheClusterStatus) {
        setCacheClusterStatus(cacheClusterStatus);
        return this;
    }

    /**
     *

     * The status of the cache cluster for the stage, if enabled.
     *

     *
     * @param cacheClusterStatus
     *        The status of the cache cluster for the stage, if enabled.
     * @see CacheClusterStatus
     */

    public void setCacheClusterStatus(CacheClusterStatus cacheClusterStatus) {
        this.cacheClusterStatus = cacheClusterStatus.toString();
    }

    /**
     *

     * The status of the cache cluster for the stage, if enabled.
     *

     *
     * @param cacheClusterStatus
     *        The status of the cache cluster for the stage, if enabled.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see CacheClusterStatus
     */

    public GetStageResult withCacheClusterStatus(CacheClusterStatus cacheClusterStatus) {
        setCacheClusterStatus(cacheClusterStatus);
        return this;
    }

    /**
     *

     * A map that defines the method settings for a Stage resource. Keys (designated as
     * /{method_setting_key below) are method paths defined as {resource_path}/{http_method}
     * for an individual method override, or /\*/\* for overriding all methods in the stage.
     *

     *
     * @return A map that defines the method settings for a Stage resource. Keys (designated as
     *         /{method_setting_key below) are method paths defined as
     *         {resource_path}/{http_method} for an individual method override, or /\*/\*
     *         for overriding all methods in the stage.
     */

    public java.util.Map<String, MethodSetting> getMethodSettings() {
        return methodSettings;
    }

    /**
     *

     * A map that defines the method settings for a Stage resource. Keys (designated as
     * /{method_setting_key below) are method paths defined as {resource_path}/{http_method}
     * for an individual method override, or /\*/\* for overriding all methods in the stage.
     *

     *
     * @param methodSettings
     *        A map that defines the method settings for a Stage resource. Keys (designated as
     *        /{method_setting_key below) are method paths defined as
     *        {resource_path}/{http_method} for an individual method override, or /\*/\*
     *        for overriding all methods in the stage.
     */

    public void setMethodSettings(java.util.Map<String, MethodSetting> methodSettings) {
        this.methodSettings = methodSettings;
    }

    /**
     *

     * A map that defines the method settings for a Stage resource. Keys (designated as
     * /{method_setting_key below) are method paths defined as {resource_path}/{http_method}
     * for an individual method override, or /\*/\* for overriding all methods in the stage.
     *

     *
     * @param methodSettings
     *        A map that defines the method settings for a Stage resource. Keys (designated as
     *        /{method_setting_key below) are method paths defined as
     *        {resource_path}/{http_method} for an individual method override, or /\*/\*
     *        for overriding all methods in the stage.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetStageResult withMethodSettings(java.util.Map<String, MethodSetting> methodSettings) {
        setMethodSettings(methodSettings);
        return this;
    }

    public GetStageResult addMethodSettingsEntry(String key, MethodSetting value) {
        if (null == this.methodSettings) {
            this.methodSettings = new java.util.HashMap<String, MethodSetting>();
        }
        if (this.methodSettings.containsKey(key))
            throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
        this.methodSettings.put(key, value);
        return this;
    }

    /**
     * Removes all the entries added into MethodSettings.
     *
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetStageResult clearMethodSettingsEntries() {
        this.methodSettings = null;
        return this;
    }

    /**
     *

     * A map that defines the stage variables for a Stage resource. Variable names can have alphanumeric and
     * underscore characters, and the values must match [A-Za-z0-9-._~:/?#&=,]+.
     *

     *
     * @return A map that defines the stage variables for a Stage resource. Variable names can have alphanumeric
     *         and underscore characters, and the values must match [A-Za-z0-9-._~:/?#&=,]+.
     */

    public java.util.Map<String, String> getVariables() {
        return variables;
    }

    /**
     *

     * A map that defines the stage variables for a Stage resource. Variable names can have alphanumeric and
     * underscore characters, and the values must match [A-Za-z0-9-._~:/?#&=,]+.
     *

     *
     * @param variables
     *        A map that defines the stage variables for a Stage resource. Variable names can have alphanumeric
     *        and underscore characters, and the values must match [A-Za-z0-9-._~:/?#&=,]+.
     */

    public void setVariables(java.util.Map<String, String> variables) {
        this.variables = variables;
    }

    /**
     *

     * A map that defines the stage variables for a Stage resource. Variable names can have alphanumeric and
     * underscore characters, and the values must match [A-Za-z0-9-._~:/?#&=,]+.
     *

     *
     * @param variables
     *        A map that defines the stage variables for a Stage resource. Variable names can have alphanumeric
     *        and underscore characters, and the values must match [A-Za-z0-9-._~:/?#&=,]+.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetStageResult withVariables(java.util.Map<String, String> variables) {
        setVariables(variables);
        return this;
    }

    public GetStageResult addVariablesEntry(String key, String value) {
        if (null == this.variables) {
            this.variables = new java.util.HashMap<String, String>();
        }
        if (this.variables.containsKey(key))
            throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
        this.variables.put(key, value);
        return this;
    }

    /**
     * Removes all the entries added into Variables.
     *
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetStageResult clearVariablesEntries() {
        this.variables = null;
        return this;
    }

    /**
     *

     * The version of the associated API documentation.
     *

     *
     * @param documentationVersion
     *        The version of the associated API documentation.
     */

    public void setDocumentationVersion(String documentationVersion) {
        this.documentationVersion = documentationVersion;
    }

    /**
     *

     * The version of the associated API documentation.
     *

     *
     * @return The version of the associated API documentation.
     */

    public String getDocumentationVersion() {
        return this.documentationVersion;
    }

    /**
     *

     * The version of the associated API documentation.
     *

     *
     * @param documentationVersion
     *        The version of the associated API documentation.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetStageResult withDocumentationVersion(String documentationVersion) {
        setDocumentationVersion(documentationVersion);
        return this;
    }

    /**
     *

     * The timestamp when the stage was created.
     *

     *
     * @param createdDate
     *        The timestamp when the stage was created.
     */

    public void setCreatedDate(java.util.Date createdDate) {
        this.createdDate = createdDate;
    }

    /**
     *

     * The timestamp when the stage was created.
     *

     *
     * @return The timestamp when the stage was created.
     */

    public java.util.Date getCreatedDate() {
        return this.createdDate;
    }

    /**
     *

     * The timestamp when the stage was created.
     *

     *
     * @param createdDate
     *        The timestamp when the stage was created.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetStageResult withCreatedDate(java.util.Date createdDate) {
        setCreatedDate(createdDate);
        return this;
    }

    /**
     *

     * The timestamp when the stage last updated.
     *

     *
     * @param lastUpdatedDate
     *        The timestamp when the stage last updated.
     */

    public void setLastUpdatedDate(java.util.Date lastUpdatedDate) {
        this.lastUpdatedDate = lastUpdatedDate;
    }

    /**
     *

     * The timestamp when the stage last updated.
     *

     *
     * @return The timestamp when the stage last updated.
     */

    public java.util.Date getLastUpdatedDate() {
        return this.lastUpdatedDate;
    }

    /**
     *

     * The timestamp when the stage last updated.
     *

     *
     * @param lastUpdatedDate
     *        The timestamp when the stage last updated.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetStageResult withLastUpdatedDate(java.util.Date lastUpdatedDate) {
        setLastUpdatedDate(lastUpdatedDate);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDeploymentId() != null)
            sb.append("DeploymentId: ").append(getDeploymentId()).append(",");
        if (getClientCertificateId() != null)
            sb.append("ClientCertificateId: ").append(getClientCertificateId()).append(",");
        if (getStageName() != null)
            sb.append("StageName: ").append(getStageName()).append(",");
        if (getDescription() != null)
            sb.append("Description: ").append(getDescription()).append(",");
        if (getCacheClusterEnabled() != null)
            sb.append("CacheClusterEnabled: ").append(getCacheClusterEnabled()).append(",");
        if (getCacheClusterSize() != null)
            sb.append("CacheClusterSize: ").append(getCacheClusterSize()).append(",");
        if (getCacheClusterStatus() != null)
            sb.append("CacheClusterStatus: ").append(getCacheClusterStatus()).append(",");
        if (getMethodSettings() != null)
            sb.append("MethodSettings: ").append(getMethodSettings()).append(",");
        if (getVariables() != null)
            sb.append("Variables: ").append(getVariables()).append(",");
        if (getDocumentationVersion() != null)
            sb.append("DocumentationVersion: ").append(getDocumentationVersion()).append(",");
        if (getCreatedDate() != null)
            sb.append("CreatedDate: ").append(getCreatedDate()).append(",");
        if (getLastUpdatedDate() != null)
            sb.append("LastUpdatedDate: ").append(getLastUpdatedDate());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof GetStageResult == false)
            return false;
        GetStageResult other = (GetStageResult) obj;
        if (other.getDeploymentId() == null ^ this.getDeploymentId() == null)
            return false;
        if (other.getDeploymentId() != null && other.getDeploymentId().equals(this.getDeploymentId()) == false)
            return false;
        if (other.getClientCertificateId() == null ^ this.getClientCertificateId() == null)
            return false;
        if (other.getClientCertificateId() != null && other.getClientCertificateId().equals(this.getClientCertificateId()) == false)
            return false;
        if (other.getStageName() == null ^ this.getStageName() == null)
            return false;
        if (other.getStageName() != null && other.getStageName().equals(this.getStageName()) == false)
            return false;
        if (other.getDescription() == null ^ this.getDescription() == null)
            return false;
        if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
            return false;
        if (other.getCacheClusterEnabled() == null ^ this.getCacheClusterEnabled() == null)
            return false;
        if (other.getCacheClusterEnabled() != null && other.getCacheClusterEnabled().equals(this.getCacheClusterEnabled()) == false)
            return false;
        if (other.getCacheClusterSize() == null ^ this.getCacheClusterSize() == null)
            return false;
        if (other.getCacheClusterSize() != null && other.getCacheClusterSize().equals(this.getCacheClusterSize()) == false)
            return false;
        if (other.getCacheClusterStatus() == null ^ this.getCacheClusterStatus() == null)
            return false;
        if (other.getCacheClusterStatus() != null && other.getCacheClusterStatus().equals(this.getCacheClusterStatus()) == false)
            return false;
        if (other.getMethodSettings() == null ^ this.getMethodSettings() == null)
            return false;
        if (other.getMethodSettings() != null && other.getMethodSettings().equals(this.getMethodSettings()) == false)
            return false;
        if (other.getVariables() == null ^ this.getVariables() == null)
            return false;
        if (other.getVariables() != null && other.getVariables().equals(this.getVariables()) == false)
            return false;
        if (other.getDocumentationVersion() == null ^ this.getDocumentationVersion() == null)
            return false;
        if (other.getDocumentationVersion() != null && other.getDocumentationVersion().equals(this.getDocumentationVersion()) == false)
            return false;
        if (other.getCreatedDate() == null ^ this.getCreatedDate() == null)
            return false;
        if (other.getCreatedDate() != null && other.getCreatedDate().equals(this.getCreatedDate()) == false)
            return false;
        if (other.getLastUpdatedDate() == null ^ this.getLastUpdatedDate() == null)
            return false;
        if (other.getLastUpdatedDate() != null && other.getLastUpdatedDate().equals(this.getLastUpdatedDate()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getDeploymentId() == null) ? 0 : getDeploymentId().hashCode());
        hashCode = prime * hashCode + ((getClientCertificateId() == null) ? 0 : getClientCertificateId().hashCode());
        hashCode = prime * hashCode + ((getStageName() == null) ? 0 : getStageName().hashCode());
        hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
        hashCode = prime * hashCode + ((getCacheClusterEnabled() == null) ? 0 : getCacheClusterEnabled().hashCode());
        hashCode = prime * hashCode + ((getCacheClusterSize() == null) ? 0 : getCacheClusterSize().hashCode());
        hashCode = prime * hashCode + ((getCacheClusterStatus() == null) ? 0 : getCacheClusterStatus().hashCode());
        hashCode = prime * hashCode + ((getMethodSettings() == null) ? 0 : getMethodSettings().hashCode());
        hashCode = prime * hashCode + ((getVariables() == null) ? 0 : getVariables().hashCode());
        hashCode = prime * hashCode + ((getDocumentationVersion() == null) ? 0 : getDocumentationVersion().hashCode());
        hashCode = prime * hashCode + ((getCreatedDate() == null) ? 0 : getCreatedDate().hashCode());
        hashCode = prime * hashCode + ((getLastUpdatedDate() == null) ? 0 : getLastUpdatedDate().hashCode());
        return hashCode;
    }

    @Override
    public GetStageResult clone() {
        try {
            return (GetStageResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
module WizardsCastle
  class NullPrinter

    def intro
    end

    def character_creation_header
    end

    def prompt_race
      {}
    end

    def prompt_gender
      {}
    end

    def attributes_header
    end

    def prompt_add_to_strength
    end

    def prompt_add_to_intelligence
    end

    def prompt_add_to_dexterity
    end

    def gold_report1
    end

    def gold_report2
    end

    def gold_report3
    end

    def prompt_armor
      {}
    end

    def prompt_weapon
      {}
    end

    def prompt_lamp
      {}
    end

    def prompt_flares
      {}
    end

    def entering_the_castle
    end

    def you_are_here
    end

    def you_are_here_blind
    end

    def stat_block
    end

    def here_you_find(_symbol)
    end

    def new_gold_count
    end

    def new_flare_count
    end

    def found_orb_of_zot
    end

    def got_a_treasure(_treasure_symbol)
    end

    def player_action_flavor_text
    end

    def cure_blindness
    end

    def cure_stickybook
    end

    def prompt_standard_action
      {}
    end

    def blind_command_error
    end

    def help_message
    end

    def stairs_up_error
    end

    def stairs_down_error
    end

    def drink_effect(effect)
    end

    def no_pool_error
    end

    def display_map
    end

    def flare
    end

    def out_of_flares
    end

    def prompt_shine_lamp
      {}
    end

    def no_lamp_error
    end

    def lamp_shine(_row, _col, _floor)
    end

    def nothing_to_open_error
    end

    def book_effect(_effect)
    end

    def chest_effect(_effect, _gold_gain)
    end

    def gaze_effect(_effect, _effect_location)
    end

    def no_crystal_orb_error
    end

    def no_runestaff_error
    end

    def prompt_teleport_row
      {}
    end

    def prompt_teleport_column
      {}
    end

    def prompt_teleport_floor
      {}
    end

    def prompt_confirm_quit
      {}
    end

    #########################################
    # ENDGAME

    def death
    end

    def quit
    end

    def exit_castle
    end

    def endgame_possessions
    end

    def prompt_play_again
      {}
    end

    def play_again
    end

    def restock
    end

    def shut_down
    end

    #########################################
    # COMBAT

    def you_have_escaped
    end

    def prompt_retreat_direction
      {}
    end

    def youre_facing_a_monster
    end

    def combat_menu(_can_bribe)
    end

    def your_battle_stats
    end

    def combat_selection_error_msg
    end

    def prompt_combat
      {}
    end

    def the_monster_attacks
    end

    def he_hit_you
    end

    def he_missed_you
    end

    def armor_destroyed
    end

    def monster_is_dead
    end

    def unarmed_attack
    end

    def book_attack
    end

    def you_hit_him
    end

    def your_weapon_broke
    end

    def eat_a_monster
    end

    def you_got_the_runestaff
    end

    def you_got_monster_gold(_gp)
    end

    def bribe_refused
    end

    def prompt_bribe_request(_treasure_symbol)
      {}
    end

    def bribe_accepted
    end

    def cant_cast_now
    end

    def prompt_cast
      {}
    end

    def cast_selection_error_msg
    end

    def the_web_broke
    end

    def monster_stuck_in_web
    end

    def fireball_damage_report(damage)
    end

    def deathspell_kills_enemy
    end

    def deathspell_kills_player
    end

    #########################################
    # VENDOR

    def prompt_vendor_encounter
      {}
    end

    def vendor_responds_to_attack
    end

    def vendor_loot
    end

    def prompt_sell_treasure(_treasure_symbol, _amount)
      {}
    end

    def too_poor_to_trade
    end

    def gold_and_armor_report
    end

    def vendor_armors
    end

    def prompt_vendor_armor
      {}
    end

    def cannot_afford_chainmail
    end

    def cannot_afford_plate
    end

    def gold_and_weapon_report
    end

    def vendor_weapons
    end

    def prompt_vendor_weapon
      {}
    end

    def cannot_afford_a_mace
    end

    def cannot_afford_a_sword
    end

    def prompt_vendor_str_potion
      {}
    end

    def str_report
    end

    def prompt_vendor_int_potion
      {}
    end

    def int_report
    end

    def prompt_vendor_dex_potion
      {}
    end

    def dex_report
    end

    def prompt_vendor_buy_lamp
      {}
    end

    def you_bought_a_lamp
    end

  end
end


text:
package hm.edu.pulsebuddy.misc;

import hm.edu.pulsebuddy.R;
import hm.edu.pulsebuddy.data.SportModeWorkoutPlanData;
import hm.edu.pulsebuddy.sportmode.SportModeWorkoutPlanAdapter;

import java.util.Random;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;

/**
 *
 * @author Christoph Friegel
 * @author Tore Offermann
 *
 */
public class SportModeWorkoutPlanFragment extends Fragment {
	/**
	 * The fragment argument representing the section number for this fragment.
	 */
	public static final String ARG_SECTION_NUMBER = "section_number";
	SparseArray<SportModeWorkoutPlanData> groups = new SparseArray<SportModeWorkoutPlanData>();

	public SportModeWorkoutPlanFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_sport_mode_workout_plan,
				container, false);

		createData();
		ExpandableListView listView = (ExpandableListView) view
				.findViewById(R.id.expandableListViewWorkoutPlan);
		SportModeWorkoutPlanAdapter adapter = new SportModeWorkoutPlanAdapter(
				this, groups);
		listView.setAdapter(adapter);

		return view;
	}

	public void createData() {

		for (int j = 0; j < 6; j++) {

			int weekCount = j;
			weekCount++;

			SportModeWorkoutPlanData group = new SportModeWorkoutPlanData(
					weekCount + ". Woche");
			for (int i = 0; i < 7; i++) {
				int dayCount = i;
				dayCount++;

				Random r = new Random();
				int dummyPulseValue = r.nextInt(170 - 30) + 65;

				group.children.add(dayCount + ". Tag: " + dummyPulseValue
						+ " bpm");
			}
			groups.append(j, group);
		}
	}

}


text:
namespace tesseract {

class BLOCK;
class WERD;
struct TWERD;

// Class to hold an array of bounding boxes for an output word and
// the bounding box of the whole word.
class BoxWord {
public:
  BoxWord();
  explicit BoxWord(const BoxWord &src);
  ~BoxWord() = default;

  BoxWord &operator=(const BoxWord &src);

  void CopyFrom(const BoxWord &src);

  // Factory to build a BoxWord from a TWERD using the DENORMs on each blob to
  // switch back to original image coordinates.
  static BoxWord *CopyFromNormalized(TWERD *tessword);

  // Clean up the bounding boxes from the polygonal approximation by
  // expanding slightly, then clipping to the blobs from the original_word
  // that overlap. If not null, the block provides the inverse rotation.
  void ClipToOriginalWord(const BLOCK *block, WERD *original_word);

  // Merges the boxes from start to end, not including end, and deletes
  // the boxes between start and end.
  void MergeBoxes(unsigned start, unsigned end);

  // Inserts a new box before the given index.
  // Recomputes the bounding box.
  void InsertBox(unsigned index, const TBOX &box);

  // Changes the box at the given index to the new box.
  // Recomputes the bounding box.
  void ChangeBox(unsigned index, const TBOX &box);

  // Deletes the box with the given index, and shuffles up the rest.
  // Recomputes the bounding box.
  void DeleteBox(unsigned index);

  // Deletes all the boxes stored in BoxWord.
  void DeleteAllBoxes();

  // This and other putatively are the same, so call the (permanent) callback
  // for each blob index where the bounding boxes match.
  // The callback is deleted on completion.
  void ProcessMatchedBlobs(const TWERD &other,
                           const std::function<void(int)> &cb) const;

  const TBOX &bounding_box() const {
    return bbox_;
  }
  unsigned length() const {
    return length_;
  }
  const TBOX &BlobBox(unsigned index) const {
    return boxes_[index];
  }

private:
  void ComputeBoundingBox();

  TBOX bbox_;
  unsigned length_;
  std::vector<TBOX> boxes_;
};

} // namespace tesseract.

#endif // TESSERACT_CSTRUCT_BOXWORD_H_


text:
package ifce.redes;

import java.io.IOException;

import ifce.redes.servidor.tcp.ServidorTCP;

public class MainServidorTCP {
	public static void main(String[] args) throws IOException, InterruptedException {
		new ServidorTCP();

		while (true)
			Thread.sleep(60000);
	}
}


text:
package com.twitter.scalding.commons.datastores;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.IOException;

public class Utils {

    public static FileSystem getFS(String path) throws IOException {
        return getFS(path, new Configuration());
    }

    public static FileSystem getFS(String path, Configuration conf) throws IOException {
        return new Path(path).getFileSystem(conf);
    }

    /**
     * Return true or false if the input is a long
     * @param input
     * @return boolean
     */
    public static boolean isLong(String input) {
        try {
            Long.parseLong(input);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}


text:
package org.squbs.unicomplex

import akka.actor.ActorSystem
import akka.http.scaladsl.model.HttpEntity.Chunked
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, StatusCodes}
import akka.pattern._
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Keep, Sink, Source}
import akka.testkit.TestKit
import com.typesafe.config.ConfigFactory
import org.scalatest.{AsyncFlatSpecLike, BeforeAndAfterAll, Matchers}
import org.squbs.lifecycle.GracefulStop
import org.squbs.unicomplex.Timeouts._

object JavaFlowSvcSpec {

  val classPaths = Array(getClass.getClassLoader.getResource("classpaths/JavaFlowSvc").getPath)

  val config = ConfigFactory.parseString(
    s"""
       |default-listener.bind-port = 0
       |squbs {
       |  actorsystem-name = JavaFlowSvcSpec
       |  ${JMX.prefixConfig} = true
       |}
    """.stripMargin
  )

  val boot = UnicomplexBoot(config)
    .createUsing {(name, config) => ActorSystem(name, config)}
    .scanComponents(classPaths)
    .initExtensions.start()
}

class JavaFlowSvcSpec extends TestKit(
  JavaFlowSvcSpec.boot.actorSystem) with AsyncFlatSpecLike with BeforeAndAfterAll with Matchers {

  implicit val am = ActorMaterializer()

  val portBindingsF = (Unicomplex(system).uniActor ? PortBindings).mapTo[Map[String, Int]]
  val portF = portBindingsF map { bindings => bindings("default-listener") }

  override def afterAll(): Unit = {
    Unicomplex(system).uniActor ! GracefulStop
  }

  it should "handle a normal request" in {
    for {
      port <- portF
      response <- entityAsString(s"http://127.0.0.1:$port/javaflowsvc/ping")
    } yield {
      response shouldBe "pong"
    }
  }

  it should "handle a chunked request and be able to provide a chunked response" in {
    val requestChunks = Source.single("Hi this is a test")
      .mapConcat { s => s.split(' ').toList }
      .map(HttpEntity.ChunkStreamPart(_))

    for {
      port <- portF
      response <- post(s"http://127.0.0.1:$port/javaflowsvc/chunks",
                       Chunked(ContentTypes.`text/plain(UTF-8)`, requestChunks))
      responseString <- response.entity.dataBytes.map(_.utf8String).toMat(Sink.fold("") { _ + _})(Keep.right).run()
    } yield {
      response.entity shouldBe 'chunked
      responseString should be("Received 5 chunks and 13 bytes.\r\nThis is the last chunk!")
    }
  }

  it should "get an InternalServerError with blank response if Flow collapses" in {
    for {
      port <- portF
      errResp <- get(s"http://127.0.0.1:$port/javaflowsvc/throwit")
      respEntity <- errResp.entity.toStrict(awaitMax)
    } yield {
      errResp.status shouldBe StatusCodes.InternalServerError
      respEntity.data.utf8String shouldBe 'empty
    }
  }
}