text:
/*globals describe,it,before,after*/
var DockerizeManager = require('../src/DockerizeManager'),
    BaseManager = require('../src/BaseManager'),
    Logger = require('../src/Logger'),
    fs = require('fs'),
    path = require('path'),
    assert = require('assert'),
    _ = require('lodash'),
    rm_rf = require('rimraf'),
    exists = require('exists-file'),
    utils = require(__dirname + '/res/utils'),
    srcUtils = require('../src/utils'),
    nop = function () {
    };

var logger = new Logger(),
    manager = new DockerizeManager(logger),
    baseManager = new BaseManager(logger);

var WebGMEConfig = 'config.webgme.js',
    SETUP_CONFIG = 'webgme-setup.json';

var PROJECT_DIR,
    TMP_DIR = path.join(__dirname, '..', 'test-tmp');

describe('DockerizeManager', function () {
    'use strict';

    before(function (done) {
        if (!fs.existsSync(TMP_DIR)) {
            fs.mkdir(TMP_DIR, function () {
                process.chdir(TMP_DIR);
                done();
            });
        } else {
            rm_rf(TMP_DIR, function () {
                fs.mkdir(TMP_DIR, function () {
                    process.chdir(TMP_DIR);
                    done();
                });
            });
        }
    });

    // Creating a new item from boilerplate
    describe('dockerize', function () {
        let cnt = 0;

        beforeEach(function (done) {
            PROJECT_DIR = path.join(TMP_DIR, 'DockerizeProj' + cnt);
            fs.mkdirSync(PROJECT_DIR);
            process.chdir(PROJECT_DIR);
            baseManager.init({}, function () {
                var configPath = path.join(PROJECT_DIR, SETUP_CONFIG);
                assert(fs.existsSync(configPath));
                done();
            });
        });

        afterEach(function (done) {
            if (fs.existsSync(PROJECT_DIR)) {
                //rm_rf(PROJECT_DIR, done);
                done();
            } else {
                done();
            }

            cnt += 1;
        });

        it('should update package json with webgme-docker-worker-manager', function () {
            manager.dockerize({});
            var packageJSON = srcUtils.getPackageJSON(PROJECT_DIR);
            assert(typeof packageJSON.dependencies['webgme-docker-worker-manager'] === 'string',
                'Did not update package.json');
        });

        it('should generate the default file when no options given', function () {
            manager.dockerize({});
            [
                'Dockerfile',
                'DockerfilePluginWorker',
                './config/config.docker.js',
                'docker-compose.yml',
            ].forEach((fName) => assert(exists(path.join(PROJECT_DIR, fName)), `Did not generate ${fName}`));
        });

        it('should additionally generate prod files when --production is given', function () {
            manager.dockerize({production: true});
            [
                'Dockerfile',
                'DockerfilePluginWorker',
                './config/config.docker.js',
                'docker-compose.yml',
                // production
                'DockerfileNginx',
                './config/config.dockerprod.js',
                'docker-compose-prod.yml',
                'nginx.conf',
            ].forEach((fName) => assert(exists(path.join(PROJECT_DIR, fName)), `Did not generate ${fName}`));
        });

        it('should not overwrite existing files', function () {
            const fPath = path.join(PROJECT_DIR, 'Dockerfile');
            const dummyContent = 'Already here!';
            fs.writeFileSync(fPath, dummyContent);
            manager.dockerize({});
            assert(fs.readFileSync(fPath, 'utf-8') === dummyContent, 'Overwrote file!');
        });

        it('should overwrite existing files', function () {
            const fPath = path.join(PROJECT_DIR, 'Dockerfile');
            const dummyContent = 'Already here!';
            fs.writeFileSync(fPath, dummyContent);
            manager.dockerize({forceUpdate: true});
            assert(fs.readFileSync(fPath, 'utf-8') !== dummyContent, 'Did not overwrite file!');
        });
    });
});


text:
import React from 'react';
import ReactDOM from 'react-dom';
import classnames from 'classnames';

/**
 * Import Entities.
 */
import {getEntity} from '../../store';

/**
 * Import Reactions.
 */
import {homepage_initialize, something_update, user_update, user_save, comments_range_update} from './reactions';

/**
 * Import Components.
 */
import UserPanel from '../../components/userPanel/userPanel';

/**
 * Import UX components.
 */

/**
 * Import styles.
 */
import style from './style';

/**
 * Import Internationalization.
 */
import {IntlProvider, FormattedMessage} from 'react-intl';

/**
 * The component.
 */
export default class Home extends React.Component {

    // Expected properties.
    static propTypes = {
        children: React.PropTypes.node,
        history: React.PropTypes.object.isRequired,
        location: React.PropTypes.object.isRequired,
        params: React.PropTypes.object.isRequired,
        route: React.PropTypes.object.isRequired,
        routeParams: React.PropTypes.object.isRequired,
        routes: React.PropTypes.array.isRequired,
        state: React.PropTypes.object.isRequired,
        store: React.PropTypes.object.isRequired
    };

    // Expected context properties.
    static contextTypes = {
        store: React.PropTypes.object
    };

    // Initialize the component.
    constructor(props) {
        super(props);
    }

    // Invoked once, both on the client and server, immediately before the initial rendering occurs.
    // If you call setState within this method,
    // render() will see the updated state and will be executed only once despite the state change.
    componentWillMount() {
    }

    // Invoked once, only on the client (not on the server), immediately after the initial rendering occurs.
    // At this point in the lifecycle, you can access any refs to your children
    // (e.g., to access the underlying DOM representation).
    // The componentDidMount() method of child components is invoked before that of parent components.
    // If you want to integrate with other JavaScript frameworks, set timers using setTimeout or setInterval,
    // or send AJAX requests, perform those operations in this method.
    componentDidMount() {
        homepage_initialize();
    }

    // Invoked when a component is receiving new props. This method is not called for the initial render.
    // Use this as an opportunity to react to a prop transition before render() is called
    // by updating the state using this.setState(). The old props can be accessed via this.props.
    // Calling this.setState() within this function will not trigger an additional render.
    componentWillReceiveProps(nextProps) {
    }

    // Invoked before rendering when new props or state are being received.
    // This method is not called for the initial render or when forceUpdate is used.
    // Use this as an opportunity to return false
    // when you're certain that the transition to the new props and state will not require a component update.
    // If shouldComponentUpdate returns false, then render() will be completely skipped until the next state change.
    // In addition, componentWillUpdate and componentDidUpdate will not be called.
    shouldComponentUpdate(nextProps, nextState) {
        // This is not a pure component.
        // Basically the whole store's state is a prop which means
        // we always have to update the component when the store's state changes.
        return true;
    }

    // Invoked immediately before rendering when new props or state are being received.
    // This method is not called for the initial render.
    // Use this as an opportunity to perform preparation before an update occurs.
    // You cannot use this.setState() in this method.
    // If you need to update state in response to a prop change, use componentWillReceiveProps instead.
    componentWillUpdate(nextProps, nextState) {
    }

    // Invoked immediately after the component's updates are flushed to the DOM.
    // This method is not called for the initial render.
    // Use this as an opportunity to operate on the DOM when the component has been updated.
    componentDidUpdate(prevProps, prevState) {
    }

    // Invoked immediately before a component is unmounted from the DOM.
    // Perform any necessary cleanup in this method,
    // such as invalidating timers or cleaning up any DOM elements that were created in componentDidMount.
    componentWillUnmount() {
    }

    // Invoked before requesting data for this component.
    static getQuery() {
        return `viewer {
                    ${UserPanel.getQuery()}
                }`;
    }

    // Render the component.
    render() {
        // Get the properties.
        const {state} = this.props;
        // Get the entities.
        var viewer = getEntity('User', state.app.home.viewer);
        // Calculate the styles.
        const className = classnames(style.root, {[`${style.loading}`]: state.app.home.loading});
        // Return the component UI.
        return (

                        <input type="text" value={state.app.home.something}
                               onChange={(e) => something_update(e.target.value)}/>
                        Reaction Trigger Example

                    {(()=> {
                        if (viewer) {
                            return (

                                    <UserPanel user={viewer} handleUserUpdate={user_update} handleUserSave={user_save}
                                               comments_range_update={comments_range_update}/>

                            );
                        }
                    })()}

        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
class StaticSlice::Application < Merb::Controller
  controller_for_slice
end


text:
package main

import (
	"encoding/json"
	"errors"
	"golang.org/x/net/context"
	"golang.org/x/oauth2"
	"golang.org/x/oauth2/clientcredentials"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"strings"
	"time"
)

const (
	REQUEST_ERROR_TIMEOUT_SECONDS = 10
)

// NOTE: On a fresh Ubuntu (e.g. through docker) ca-certificate is not installed
// and making requests to https urls (like testributor's) is not possible, we
// see this error: https://github.com/zenazn/goji/issues/126
// git though seems to install ca-certificates as a dependency so it is not
// an issue since we always require git to be installed.
var testributorUrl = os.Getenv("TESTRIBUTOR_URL")
var apiUrl string
var appID = os.Getenv("APP_ID")
var appSecret = os.Getenv("APP_SECRET")

// We build only one tokenSource and use it to create new APIClients
// (through NewClient() function) to avoid making multiple requests for
// token generation.
// oauth2.TokenSource is an interface which if implemented in our case by a
// *oauth2.reuseTokenSource (Use fmt.Printf("%T\n", tokenSource) to see that).
// Since this is a pointer, only the first call to
// NewClient() will perform a token request. After that the token will be reused
// since it points to an already initialized TokenSource value (with a valid token).
var tokenSource oauth2.TokenSource

func SetupClientData() error {
	// Default url if environment var is not set
	if testributorUrl == "" {
		testributorUrl = "https://www.testributor.com/"
	}
	apiUrl = testributorUrl + "api/v1/"

	if appID == "" {
		return errors.New("APP_ID environment variable is not set.")
	}

	if appSecret == "" {
		return errors.New("APP_SECRET environment variable is not set.")
	}

	conf := &clientcredentials.Config{
		ClientID:     appID,
		ClientSecret: appSecret,
		//Scopes:       []string{"SCOPE1", "SCOPE2"},
		TokenURL: testributorUrl + "oauth/token",
	}
	tokenSource = conf.TokenSource(context.Background())

	return nil
}

type APIClient struct {
	http.Client
	logger Logger
}

// NewClient should be used to create an APIClient instance. A logger is required
// in order for the client to print the messages with the correct prefix.
func NewClient(logger Logger) *APIClient {
	return &APIClient{
		*oauth2.NewClient(context.Background(), tokenSource),
		logger,
	}
}

// HandleRequest takes an *http.Request, makes the request and returns the
// result as an empty interface.
// https://blog.golang.org/json-and-go
func (c *APIClient) PerformRequest(method string, path string, body string) (interface{}, error) {
	var request *http.Request
	var err error

	if body != "" {
		request, err = http.NewRequest(method, apiUrl+path, strings.NewReader(body))
		if err != nil {
			return nil, err
		}
	} else {
		request, err = http.NewRequest(method, apiUrl+path, nil)
		if err != nil {
			return nil, err
		}
	}

	if method == "POST" || method == "PATCH" {
		// multipart/form-data vs application/x-www-form-urlencoded
		// http://stackoverflow.com/a/4073451/974285
		request.Header.Add("Content-Type", "multipart/form-data")
	}
	request.Header.Add("WORKER_UUID", WorkerUUID)

	requestStart := time.Now()
	resp, err := c.Do(request)
	requestDuration := time.Since(requestStart).String()
	if err != nil {
		c.logger.Log("Error occured: " + err.Error())
		c.logger.Log("Error occured after " + requestDuration)
		c.logger.Log("Retrying in " + strconv.Itoa(REQUEST_ERROR_TIMEOUT_SECONDS) + " seconds")
		time.Sleep(REQUEST_ERROR_TIMEOUT_SECONDS * time.Second)
		return c.PerformRequest(method, path, body)
	}

	if resp.StatusCode == 401 {
		return nil, errors.New("Authentication error")
	}

	defer resp.Body.Close()
	contents, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var result interface{}
	if string(contents) != "" {
		err = json.Unmarshal(contents, &result)
		if err != nil {
			return nil, err
		}
	}

	return result, nil
}

func (c *APIClient) ProjectSetupData() (interface{}, error) {
	return c.PerformRequest("GET", "projects/setup_data", "")
}

func (c *APIClient) FetchJobs() (interface{}, error) {
	return c.PerformRequest("PATCH", "test_jobs/bind_next_batch", "")
}

func (c *APIClient) Beacon() (interface{}, error) {
	return c.PerformRequest("POST", "projects/beacon", "")
}

// http://codefol.io/posts/How-Does-Rack-Parse-Query-Params-With-parse-nested-query
func (c *APIClient) UpdateTestJobs(testJobs []TestJob) (interface{}, error) {
	form := url.Values{}
	for _, job := range testJobs {
		jobData, err := json.Marshal(job)
		if err != nil {
			return new(interface{}), err
		}
		form.Add("jobs["+strconv.Itoa(job.Id)+"]", string(jobData))
	}

	return c.PerformRequest("PATCH", "test_jobs/batch_update", form.Encode())
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Wyam.Common;
using Wyam.Common.Tracing;
using Wyam.Core.Execution;
using Wyam.Core.Modules.Control;
using Wyam.Testing;
using Wyam.Testing.Modules;
using Wyam.Common.Execution;

namespace Wyam.Core.Tests.Execution
{
    [TestFixture]
    [Parallelizable(ParallelScope.Self | ParallelScope.Children)]
    public class PipelineFixture : BaseFixture
    {
        public class ExecuteTests : PipelineFixture
        {
            [Test]
            public void ReprocessesPreviousDocumentsWithDistinctSources()
            {
                // Given
                Engine engine = new Engine();
                CountModule a = new CountModule("A")
                {
                    CloneSource = true,
                    AdditionalOutputs = 1
                };
                CountModule b = new CountModule("B")
                {
                    CloneSource = true,
                    AdditionalOutputs = 2
                };
                CountModule c = new CountModule("C")
                {
                    CloneSource = true,
                    AdditionalOutputs = 3
                };
                engine.Pipelines.Add("Count", a, b, c).WithProcessDocumentsOnce();

                // When
                engine.Execute();
                engine.Execute();

                // Then
                Assert.AreEqual(24, engine.Documents.FromPipeline("Count").Count());
                Assert.AreEqual(2, a.ExecuteCount);
                Assert.AreEqual(2, b.ExecuteCount);
                Assert.AreEqual(2, c.ExecuteCount);
                Assert.AreEqual(2, a.InputCount);
                Assert.AreEqual(4, b.InputCount);
                Assert.AreEqual(12, c.InputCount);
                Assert.AreEqual(4, a.OutputCount);
                Assert.AreEqual(12, b.OutputCount);
                Assert.AreEqual(48, c.OutputCount);
            }

            [Test]
            public void DoesNotProcessPreviousDocumentsWhenSameSource()
            {
                // Given
                Engine engine = new Engine();
                CountModule a = new CountModule("A")
                {
                    CloneSource = true,
                    AdditionalOutputs = 1
                };
                CountModule b = new CountModule("B")
                {
                    AdditionalOutputs = 2
                };
                CountModule c = new CountModule("C")
                {
                    AdditionalOutputs = 3
                };
                engine.Pipelines.Add("Count", a, b, c).WithProcessDocumentsOnce();

                // When
                engine.Execute();
                a.Value = 0; // Reset a.Value so output from a has same content
                engine.Execute();

                // Then
                Assert.AreEqual(24, engine.Documents.FromPipeline("Count").Count());
                Assert.AreEqual(2, a.ExecuteCount);
                Assert.AreEqual(2, b.ExecuteCount);
                Assert.AreEqual(2, c.ExecuteCount);
                Assert.AreEqual(2, a.InputCount);
                Assert.AreEqual(2, b.InputCount);
                Assert.AreEqual(6, c.InputCount);
                Assert.AreEqual(4, a.OutputCount);
                Assert.AreEqual(6, b.OutputCount);
                Assert.AreEqual(24, c.OutputCount);
            }

            [Test]
            public void ReprocessPreviousDocumentsWithDifferentContent()
            {
                // Given
                Engine engine = new Engine();
                CountModule a = new CountModule("A")
                {
                    CloneSource = true,
                    AdditionalOutputs = 1
                };
                CountModule b = new CountModule("B")
                {
                    AdditionalOutputs = 2
                };
                CountModule c = new CountModule("C")
                {
                    AdditionalOutputs = 3
                };
                engine.Pipelines.Add("Count", a, b, c).WithProcessDocumentsOnce();

                // When
                engine.Execute();
                engine.Execute();

                // Then
                Assert.AreEqual(24, engine.Documents.FromPipeline("Count").Count());
                Assert.AreEqual(2, a.ExecuteCount);
                Assert.AreEqual(2, b.ExecuteCount);
                Assert.AreEqual(2, c.ExecuteCount);
                Assert.AreEqual(2, a.InputCount);
                Assert.AreEqual(4, b.InputCount);
                Assert.AreEqual(12, c.InputCount);
                Assert.AreEqual(4, a.OutputCount);
                Assert.AreEqual(12, b.OutputCount);
                Assert.AreEqual(48, c.OutputCount);
            }

            [Test]
            public void SameSourceIsIgnoredIfAlreadySet()
            {
                // Given
                Engine engine = new Engine();
                CountModule a = new CountModule("A")
                {
                    CloneSource = true
                };
                CountModule b = new CountModule("A")
                {
                    CloneSource = true
                };
                engine.Pipelines.Add("Count", a, b);

                // When
                engine.Execute();

                // Then
                Assert.AreEqual(1, engine.Documents.FromPipeline("Count").Count());
                Assert.AreEqual(1, a.ExecuteCount);
                Assert.AreEqual(1, b.ExecuteCount);
                Assert.AreEqual(1, a.InputCount);
                Assert.AreEqual(1, b.InputCount);
                Assert.AreEqual(1, a.OutputCount);
                Assert.AreEqual(1, b.OutputCount);
            }

            [Test]
            public void SameSourceThrowsException()
            {
                // Given
                Engine engine = new Engine();
                CountModule a = new CountModule("A")
                {
                    CloneSource = true
                };
                CountModule b = new CountModule("B");
                CountModule c = new CountModule("A")
                {
                    CloneSource = true
                };
                engine.Pipelines.Add("Count", a, new Concat(b, c));

                // When, Then
                Assert.Throws<Exception>(() => engine.Execute());
            }

            [Test]
            public void DisposingPipelineDisposesModules()
            {
                // Given
                Engine engine = new Engine();
                DisposableCountModule a = new DisposableCountModule("A");
                DisposableCountModule b = new DisposableCountModule("B");
                CountModule c = new CountModule("C");
                engine.Pipelines.Add("Count", a, new Concat(b, c));

                // When
                engine.Dispose();

                // Then
                Assert.IsTrue(a.Disposed);
                Assert.IsTrue(b.Disposed);
            }

            private class DisposableCountModule : CountModule, IDisposable
            {
                public bool Disposed { get; private set; }

                public DisposableCountModule(string valueKey)
                    : base(valueKey)
                {
                }

                public void Dispose()
                {
                    Disposed = true;
                }
            }
        }
    }
}


text:
<?php

namespace Symfony\Component\Intl\Data\Bundle\Reader;

use Symfony\Component\Intl\Exception\ResourceBundleNotFoundException;
use Symfony\Component\Intl\Exception\RuntimeException;

/**
 * Reads .json resource bundles.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 *
 * @internal
 */
class JsonBundleReader implements BundleReaderInterface
{
    /**
     * {@inheritdoc}
     */
    public function read($path, $locale)
    {
        $fileName = $path.'/'.$locale.'.json';

        if (!file_exists($fileName)) {
            throw new ResourceBundleNotFoundException(sprintf(
                'The resource bundle "%s/%s.json" does not exist.',
                $path,
                $locale
            ));
        }

        if (!is_file($fileName)) {
            throw new RuntimeException(sprintf(
                'The resource bundle "%s/%s.json" is not a file.',
                $path,
                $locale
            ));
        }

        $data = json_decode(file_get_contents($fileName), true);

        if (null === $data) {
            throw new RuntimeException(sprintf(
                'The resource bundle "%s/%s.json" contains invalid JSON: %s',
                $path,
                $locale,
                self::getLastJsonError()
            ));
        }

        return $data;
    }

    /**
     * @return string The last error message created by {@link json_decode()}
     *
     * @link http://de2.php.net/manual/en/function.json-last-error-msg.php#113243
     */
    private static function getLastJsonError()
    {
        if (function_exists('json_last_error_msg')) {
            return json_last_error_msg();
        }

        static $errors = array(
            JSON_ERROR_NONE => null,
            JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
            JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch',
            JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
            JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
            JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded',
        );

        $error = json_last_error();

        return array_key_exists($error, $errors)
            ? $errors[$error]
            : sprintf('Unknown error (%s)', $error);
    }
}


text:
  Saint-Gildas-de-Rhuys est
      une ville située dans le département de Morbihan en Bretagne. Elle totalisait 1 601 habitants en 2008.

À Saint-Gildas-de-Rhuys, le prix moyen à l'achat d'un appartement se situe à 3 445 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 3 633 € du m². À la location la valorisation moyenne se situe à 9,07 € du m² mensuel.

À proximité de Saint-Gildas-de-Rhuys sont situées les communes de
Le Hézo à 13 km, 660 habitants,
Saint-Armel située à 12 km, 796 habitants,
Baden à 14 km, 3 899 habitants,
Arradon localisée à 14 km, 5 125 habitants,
Île-d'Arz à 10 km, 254 habitants,
Le Tour-du-Parc localisée à 14 km, 990 habitants,
 entre autres. De plus, Saint-Gildas-de-Rhuys est située à seulement 18 km de Vannes.

Le nombre de logements, à Saint-Gildas-de-Rhuys, se décomposait en 2011 en 225 appartements et 2 990 maisons soit
 un marché plutôt équilibré.

La commune compte de multiples  équipements, elle dispose, entre autres, de deux bassins de natation, cinq terrains de tennis, un parcours de golf et une boucle de randonnée.


text:
module Dtime
  module Resources
    class Resource
      attr_accessor :client, :root, :response
      def initialize(client, link, response = nil)
        @client = client
        if link.respond_to?(:href)
          @root = link
        else
          # Get rel, fetch from index page if necessary
          @root = client.link_for_rel(link, force: true) if link
        end
        if response
          @response = response
        end
      end

      def follow(*args)
        self.options
        client.follow(*args)
      end

      # Get may raise a 404
      def get(opts = {})
        @response = client._get(@root, opts)
        self
      end

      def result
        if(@response.has_key?("_embedded") && @response._embedded.item.is_a?(Array))
          @response._embedded.item
        else
          (@response.result.is_a?(Array) ?  @response.result : @response)
        end
      end

      def raw
        @response.env[:raw_body]
      end

      def get_result
        self.get unless @response
        self.result
      end

      def options
        @response = client._options(@root)
        self
      end

      def template(force = false)
        # Template can be included in a link for easier access
        @template ||= @root.to_template
        return @template if @template

        options if force
        @template = @response.template if @response
        @template
      end

      def can_build?
        !!template
      end

      # Builds with clientside validation enabled. Raises error
      # if clientside template not available
      def build!(*args)
        raise Dtime::NoTemplate.new("Can't build without a template") unless can_build?
        build(*args)
      end

      # Builds without needing a clientside template
      def build(*args)
        if can_build?
          template.build(*args)
        else
          Hashie::Mash.new(*args)
        end
      end

      # Posts without clientside validation
      # May raise a 422 - unprocessable
      #
      def post(*args)
        object = build(*args)
        @response = client._post(@root, object)
        self
      end
      def patch(*args)
        object = build(*args)
        @response = client._patch(@root, object)
        self
      end
      def delete(*args)
        @response = client._delete(@root, args.first)
        self
      end
      def put(*args)
        object = build(*args)
        @response = client._put(@root, object)
        self
      end

      # Posts without clientside validation
      # May raise a 422 - unprocessable
      #
      def post_with_file(*args)
        @response = client._post_file(@root, args.first)
        self
      end

      # Posts with clientside validation
      # May raise a 422 - unprocessable
      # May raise TemplateMismatch if clientside template validation error
      #
      # May raise NoTemplate if no template for clientside validation
      def post!(*args)
        object = build!(*args)
        object.validate!
        @response = client._post(@root, object)
        self
      end

    end
  end
end


text:
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Cosmos.Asynchronous;
using Cosmos.Logging.Core.Enrichers;
using Cosmos.Logging.Core.Payloads;
using Cosmos.Logging.Events;
using Cosmos.Logging.Filters;
using Cosmos.Logging.Sinks.Console.Internals;
using EnumsNET;

namespace Cosmos.Logging.Sinks.Console {
    /// <summary>
    /// Console Payload client
    /// </summary>
    public class ConsolePayloadClient : ILogEventSink, ILogPayloadClient {
        private readonly IFormatProvider _formatProvider;
        private readonly ConsoleSinkConfiguration _sinkConfiguration;
        private readonly MessageConsumer _messageConsumer;

        private static (ConsoleColor?, ConsoleColor?) _defaultConsoleColour = ((ConsoleColor?) null, (ConsoleColor?) null);

        /// <summary>
        /// Create a new instance of <see cref="ConsolePayloadClient"/>.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="sinkConfiguration"></param>
        /// <param name="formatProvider"></param>
        public ConsolePayloadClient(string name, ConsoleSinkConfiguration sinkConfiguration, IFormatProvider formatProvider = null) {
            _sinkConfiguration = sinkConfiguration ?? throw new ArgumentNullException(nameof(sinkConfiguration));
            Name = name;
            Level = _sinkConfiguration.GetDefaultMinimumLevel();
            _formatProvider = formatProvider;

            _messageConsumer = new MessageConsumer(ConsoleFactory.CreateConsole());
        }

        /// <inheritdoc />
        public string Name { get; set; }

        /// <inheritdoc />
        public LogEventLevel? Level { get; set; }

        /// <inheritdoc />
        public Task WriteAsync(ILogPayload payload, CancellationToken cancellationToken = default) {
            if (payload != null) {
                var legalityEvents = LogEventSinkFilter.Filter(payload, _sinkConfiguration).ToList();

                foreach (var logEvent in legalityEvents) {
                    LogEventEnricherManager.Enricher(logEvent);

                    var stringBuilder = new StringBuilder();

                    stringBuilder.AppendLine($"[{logEvent.Level.GetName()}] {logEvent.Timestamp.Date:yyyy-MM-dd HH:mm:ss.ffff}");

                    using (var output = new StringWriter(stringBuilder, _formatProvider)) {
                        logEvent.RenderMessage(output, _sinkConfiguration.Rendering, _formatProvider);
                    }

                    if (logEvent.ExtraProperties.Count > 0) {
                        stringBuilder.AppendLine("Extra properties:");
                        foreach (var extra in logEvent.ExtraProperties) {
                            var property = extra.Value;
                            if (property != null) {
                                stringBuilder.AppendLine($"    {property}");
                            }
                        }
                    }

                    _messageConsumer.EnqueueMessage(CreateMessageWrapper(logEvent.Level, stringBuilder));
                }
            }

            return Tasks.CompletedTask();

            MessageWrapper CreateMessageWrapper(LogEventLevel level, StringBuilder builder) {
                var (background, foreground) = _sinkConfiguration.RealColourfulConsoleEnabled
                    ? ConsoleColourHelper.GetColour(level)
                    : _defaultConsoleColour;

                return new MessageWrapper(builder.ToString(), background, foreground);
            }
        }
    }
}


text:
package com.fkeglevich.rawdumper.camera.data;

import com.fkeglevich.rawdumper.camera.extension.IntelParameters;

/**
 * TODO: Add class header
 * <p>
 * Created by Flávio Keglevich on 31/10/17.
 */

public enum DataFormat implements ParameterValue
{
    JPEG(IntelParameters.RAW_DATA_FORMAT_NONE),
    YUV(IntelParameters.RAW_DATA_FORMAT_NONE),
    RAW(IntelParameters.RAW_DATA_FORMAT_BAYER);

    private final String parameterValue;

    DataFormat(String parameterValue)
    {
        this.parameterValue = parameterValue;
    }

    @Override
    public String getParameterValue()
    {
        return parameterValue;
    }
}


text:
L20n: Localization 2.0
======================

L20n reinvents software localization. Users should be able to benefit from the
entire expressive power of a natural language.  L20n keeps simple things
simple, and at the same time makes complex things possible.

What L20n looks like
--------------------

A straight-forward example in English:

```php
<brandName "Firefox">
<about "About {{ brandName }}">
```

And the same thing in Polish:

```php
<brandName {
  nominative: "Firefox",
  genitive: "Firefoksa",
  dative: "Firefoksowi",
  accusative: "Firefoksa",
  instrumental: "Firefoksem",
  locative: "Firefoksie"
}>
<about "O {{ brandName.locative }}">
```

Visit [L20n by Example](http://l20n.org/learn) to learn more about L20n's
syntax.

The JavaScript API
------------------

```javascript
var ctx = L20n.getContext();
ctx.linkResource('./locales/strings.l20n');
ctx.freeze();
```

When you freeze the context, the resource files will be retrieved, parsed and
compiled.  You can listen to the `ready` event (emitted by the `Context`
instance when all the resources have been compiled) and use `ctx.get` and
`ctx.getEntity` to get translations synchronously.

Alternatively, you can register callbacks to execute when the context is ready
with `ctx.localize`.

```javascript
ctx.localize(['hello', 'new'], function(l10n) {
  var node = document.querySelector('[data-l10n-id=hello]');
  node.textConent = l10n.entities.hello.value;
  node.classList.remove('hidden');
});
```

### ctx.addResource(String)
### ctx.registerLocales(Array<String>)
### ctx.linkResource(String|Function)
### ctx.freeze()
### ctx.addEventListener(String, Function)
### ctx.removeEventListener(String, Function)
### ctx.get(String, Object)
### ctx.getEntity(String, Object)
### ctx.localize(Array, Function)

The HTML Bindings
-----------------

You can take advantage of HTML bindings to localize your HTML documents with
L20n.  See [bindings/README][].

[bindings/README]: https://github.com/l20n/l20n.js/blob/master/bindings/README.md

Install L20n in Node.js (using NPM)
-----------------------------------

    npm install l20n

Or, if you want to hack on L20n, install from source:

    git clone https://github.com/l20n/l20n.js.git
    cd l20n.js
    sudo npm link
    cd ../some/other/project
    npm link l20n

In your other project you can now require L20n:

    var L20n = require('l20n');
    var ctx = L20n.getContext();

Build L20n for the Clientside
-----------------------------

In order to use L20n on a webpage, all you need is an optimized to a single
file, and possibly minified, version of the library.

    git clone https://github.com/l20n/l20n.js.git
    cd l20n.js
    npm install
    make build

This will produce the optimized files in `dist`.

    dist/l20n.js
    dist/l20n.min.js

Include the optimized script in your webpage to make the `L20n` object global.

```html
<script src="../path/to/dist/l20n.js"></script>
<script>
  var ctx = L20n.getContext();
</script>
```

For resource file loading over XHR to work properly, remember to run your
webpage on a server (localhost will do).

Set up L20n for Development
---------------------------

If you want to hack on L20n locally, you don't have to `make build` after every
edit.  L20n follows the AMD naming scheme and can be used with module loaders
like [RequireJS][].

[RequireJS]: http://requirejs.org/

```html
<script src="require.js"></script>
<script>
  require.config({
    baseUrl: '../path/to/lib/', // tell RequireJS where to look for L20n
    paths: {
      'l20n/platform': 'client/l20n/platform' // and where the client-
                                              // specific code lives relative
                                              // to `baseUrl` (you shouldn't
                                              // need to change this)
    }
  });
  require(['l20n'], function(L20n) {
    var ctx = L20n.getContext();
    // write the rest of your code here
  });
</script>
```

Further Reading
---------------
You can find the documentation for localizers, developers and contributors at
the [Mozilla Developer Network][].  The original design documents can be found
at the [Mozilla Wiki][].  We also use the wiki for release planning.

[Mozilla Developer Network]: https://developer.mozilla.org/en-US/docs/L20n
[Mozilla Wiki]: https://wiki.mozilla.org/L20n

Discuss
-------
We'd love to hear your thoughts on L20n!  Whether you're a localizer looking
for a better way to express yourself in your language, or a developer trying to
make your app localizable and multilingual, or a hacker looking for a project
to contribute to, please do get in touch on the mailing list and the IRC
channel.

 - mailing list: https://lists.mozilla.org/listinfo/tools-l10n
 - IRC channel: [irc://irc.mozilla.org/l20n](irc://irc.mozilla.org/l20n)

Get Involved
------------
L20n is open-source, licensed under the Apache License, Version 2.0.  We
encourage everyone to take a look at our code and we'll listen to your
feedback.

We use Bugzilla to track our work. Visit our [Tracking] page for a collection
of useful links and information about our release planning.  You can also go
straight to the [Dashboard][] or [file a new bug][].

We <3 GitHub, but we prefer `text/plain` patches over pull requests.  Refer to
the [Contributor's documentation][]  for more information.

[Tracking]: https://wiki.mozilla.org/L20n/Tracking
[Dashboard]: https://bugzilla.mozilla.org/page.cgi?id=productdashboard.html&product=L20n&bug_status=open&tab=summary
[file a new bug]: https://bugzilla.mozilla.org/enter_bug.cgi?product=L20n
[Contributor's documentation]: https://developer.mozilla.org/en-US/docs/L20n/Contribute


text:
class User < ActiveRecord::Base
  enum role: [:user, :vip, :admin]
  after_initialize :set_default_role, :if => :new_record?

  def set_default_role
    self.role ||= :user
  end

  def full_name
    "#{first_name last_name}"
  end

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :token_authenticatable, :confirmable, :lockable, :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :timeoutable

  validates :email, :uniqueness => true, :length => { minimum: 6, maximum: 255}, :presence => true, on: 'create'
  validates :first_name, :presence => true
  validates :last_name, :presence => true

  has_many :aquariums, :dependent => :destroy
end


text:
$(function () {

  // navbar notification popups
  $(".notification-dropdown").each(function (index, el) {
    var $el = $(el);
    var $dialog = $el.find(".pop-dialog");
    var $trigger = $el.find(".trigger");

    $dialog.click(function (e) {
        e.stopPropagation()
    });
    $dialog.find(".close-icon").click(function (e) {
      e.preventDefault();
      $dialog.removeClass("is-visible");
      $trigger.removeClass("active");
    });
    $("body").click(function () {
      $dialog.removeClass("is-visible");
      $trigger.removeClass("active");
    });

    $trigger.click(function (e) {
      e.preventDefault();
      e.stopPropagation();

      // hide all other pop-dialogs
      $(".notification-dropdown .pop-dialog").removeClass("is-visible");
      $(".notification-dropdown .trigger").removeClass("active")

      $dialog.toggleClass("is-visible");
      if ($dialog.hasClass("is-visible")) {
        $(this).addClass("active");
      } else {
        $(this).removeClass("active");
      }
    });
  });

  // skin changer
  $(".skins-nav .skin").click(function (e) {
    e.preventDefault();
    if ($(this).hasClass("selected")) {
      return;
    }
    $(".skins-nav .skin").removeClass("selected");
    $(this).addClass("selected");

    if (!$("#skin-file").length) {
      $("head").append('<link rel="stylesheet" type="text/css" id="skin-file" href="">');
    }
    var $skin = $("#skin-file");
    if ($(this).attr("data-file")) {
      $skin.attr("href", $(this).data("file"));
    } else {
      $skin.attr("href", "");
    }

  });

  // sidebar menu dropdown toggle
  $("#dashboard-menu .dropdown-toggle").click(function (e) {
    e.preventDefault();
    var $item = $(this).parent();
    $item.toggleClass("active");
    if ($item.hasClass("active")) {
      $item.find(".submenu").slideDown("fast");
    } else {
      $item.find(".submenu").slideUp("fast");
    }
  });

  // mobile side-menu slide toggler
  var $menu = $("#sidebar-nav");
  $("body").click(function () {
    if ($menu.hasClass("display")) {
      $menu.removeClass("display");
    }
  });
  $menu.click(function(e) {
    //e.stopPropagation();
  });
  $("#menu-toggler").click(function (e) {
    e.stopPropagation();
    $menu.toggleClass("display");
  });

	// build all tooltips from data-attributes
	$("[data-toggle='tooltip']").each(function (index, el) {
		$(el).tooltip({
			placement: $(this).data("placement") || 'top'
		});
	});

  // custom uiDropdown element, example can be seen in user-list.html on the 'Filter users' button
	var uiDropdown = new function() {
  	var self;
  	self = this;
  	this.hideDialog = function($el) {
    		return $el.find(".dialog").hide().removeClass("is-visible");
  	};
  	this.showDialog = function($el) {
    		return $el.find(".dialog").show().addClass("is-visible");
  	};
		return this.initialize = function() {
  		$("html").click(function() {
    		$(".ui-dropdown .head").removeClass("active");
      		return self.hideDialog($(".ui-dropdown"));
    		});
    		$(".ui-dropdown .body").click(function(e) {
      		return e.stopPropagation();
    		});
    		return $(".ui-dropdown").each(function(index, el) {
      		return $(el).click(function(e) {
      			e.stopPropagation();
      			$(el).find(".head").toggleClass("active");
      			if ($(el).find(".head").hasClass("active")) {
        			return self.showDialog($(el));
      			} else {
        			return self.hideDialog($(el));
      			}
      		});
    		});
    	};
  	};

    // instantiate new uiDropdown from above to build the plugins
  	new uiDropdown();

  	// toggle all checkboxes from a table when header checkbox is clicked
  	$(".table th input:checkbox").click(function () {
  		$checks = $(this).closest(".table").find("tbody input:checkbox");
  		if ($(this).is(":checked")) {
  			$checks.prop("checked", true);
  		} else {
  			$checks.prop("checked", false);
  		}
  	});

});


text:
Rails.application.routes.draw do
  get "posts/create", to: "posts#create"
end


text:
set -e

#echo command
set -v

#change current directory to this file
cd `dirname $0`
echo pwd = `pwd`

# build ax_gen
make -C ../../projects/makefile

../../bin/ax_gen ws=Hello.axworkspace gen=makefile -gen -verbose "$@"


text:
import { IConfettiOptions } from './Confetti'
import { IRect } from './Rect'
import Particle from './Particle'
import { randomRange } from './utils'

export interface IParticleGenerator extends IRect {
  removeParticleAt: (index: number) => void
  getParticle: () => void
  animate: () => boolean
  particles: Particle[]
  particlesGenerated: number
}

export default class ParticleGenerator implements IParticleGenerator {
  constructor(canvas: HTMLCanvasElement, getOptions: () => IConfettiOptions) {
    this.canvas = canvas
    const ctx = this.canvas.getContext('2d')
    if(!ctx) {
      throw new Error('Could not get canvas context')
    }
    this.context = ctx
    this.getOptions = getOptions
  }

  canvas: HTMLCanvasElement

  context: CanvasRenderingContext2D

  getOptions: () => IConfettiOptions

  x: number = 0

  y: number = 0

  w: number = 0

  h: number = 0

  lastNumberOfPieces: number = 0

  tweenInitTime: number = Date.now()

  particles: Particle[] = []

  particlesGenerated: number = 0

  removeParticleAt = (i: number) => {
    this.particles.splice(i, 1)
  }

  getParticle = () => {
    const newParticleX = randomRange(this.x, this.w + this.x)
    const newParticleY = randomRange(this.y, this.h + this.y)
    return new Particle(this.context, this.getOptions, newParticleX, newParticleY)
  }

  animate = (): boolean => {
    const {
      canvas,
      context,
      particlesGenerated,
      lastNumberOfPieces,
    } = this
    const {
      run,
      recycle,
      numberOfPieces,
      debug,
      tweenFunction,
      tweenDuration,
    } = this.getOptions()
    if(!run) {
      return false
    }

    const nP = this.particles.length
    const activeCount = recycle ? nP : particlesGenerated

    const now = Date.now()

    // Initial population
    if(activeCount < numberOfPieces) {
      // Use the numberOfPieces prop as a key to reset the easing timing
      if(lastNumberOfPieces !== numberOfPieces) {
        this.tweenInitTime = now
        this.lastNumberOfPieces = numberOfPieces
      }
      const { tweenInitTime } = this
      // Add more than one piece per loop, otherwise the number of pieces would
      // be limitted by the RAF framerate
      const progressTime = now - tweenInitTime > tweenDuration
        ? tweenDuration
        : Math.max(0, now - tweenInitTime)
      const tweenedVal = tweenFunction(progressTime, activeCount, numberOfPieces, tweenDuration)
      const numToAdd = Math.round(tweenedVal - activeCount)
      for(let i = 0; i < numToAdd; i++) {
        this.particles.push(this.getParticle())
      }
      this.particlesGenerated += numToAdd
    }
    if(debug) {
      // Draw debug text
      context.font = '12px sans-serif'
      context.fillStyle = '#333'
      context.textAlign = 'right'
      context.fillText(`Particles: ${nP}`, canvas.width - 10, canvas.height - 20)
    }

    // Maintain the population
    this.particles.forEach((p, i) => {
      // Update each particle's position
      p.update()
      // Prune the off-canvas particles
      if(p.y > canvas.height || p.y < -100 || p.x > canvas.width + 100 || p.x < -100) {
        if(recycle && activeCount <= numberOfPieces) {
          // Replace the particle with a brand new one
          this.particles[i] = this.getParticle()
        } else {
          this.removeParticleAt(i)
        }
      }
    })
    return nP > 0 || activeCount < numberOfPieces
  }
}


text:
package org.eclipse.jetty.websocket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.websocket.WebSocket.FrameConnection;
import org.eclipse.jetty.websocket.WebSocketParser.FrameHandler;

import android.annotation.TargetApi;
import android.os.Build;
import android.text.TextUtils;

/**
 * PerMessageDeflateExtension
 *
 * Copyright (c) 2015 KNOWLEDGECODE
 */
public class PerMessageDeflateExtension implements Extension {

    private static final Logger __log = Log.getLogger(PerMessageDeflateExtension.class.getName());
    private static final byte[] TAIL_BYTES = new byte[] { 0x00, 0x00, (byte) 0xff, (byte) 0xff };
    private static final int TAIL_LENGTH = TAIL_BYTES.length;
    private static final int INITIAL_CAPACITY = 16384;
    private static final String EXTENSION = "permessage-deflate";
    private static final String CLIENT_NO_CONTEXT_TAKEOVER = "client_no_context_takeover";
    private static final String SERVER_NO_CONTEXT_TAKEOVER = "server_no_context_takeover";
    private static final String SERVER_MAX_WINDOW_BITS = "server_max_window_bits";

    private static class Zlib {
        protected Deflater _deflater;
        protected Inflater _inflater;
        protected byte[] _buffer;
        protected int _capcacity;
        protected boolean _deflaterReset;
        protected boolean _inflaterReset;

        public Zlib(boolean deflaterReset, boolean inflaterReset) {
            _deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);
            _inflater = new Inflater(true);
            _buffer = new byte[INITIAL_CAPACITY];
            _capcacity = _buffer.length;
            _deflaterReset = deflaterReset;
            _inflaterReset = inflaterReset;
        }

        public static byte[] appendTailBytes(byte[] array, int offset, int length) {
            byte[] buffer = Arrays.copyOfRange(array, offset, offset + length + TAIL_LENGTH);
            System.arraycopy(TAIL_BYTES, 0, buffer, length, TAIL_LENGTH);
            return buffer;
        }

        public byte[] compress(byte[] b, int offset, int length) {
            int len;
            int position = 0;

            _deflater.reset();
            _deflater.setInput(b, offset, length);
            _deflater.finish();
            while ((len = _deflater.deflate(_buffer, position, _capcacity - position)) > 0) {
                if ((position += len) == _capcacity) {
                    _buffer = Arrays.copyOf(_buffer, _capcacity <<= 1);
                }
            }
            return Arrays.copyOf(_buffer, position);
        }

        public byte[] decompress(byte[] b) throws DataFormatException {
            return decompress(b, 0, b.length);
        }

        public byte[] decompress(byte[] b, int offset, int length) throws DataFormatException {
            int len;
            int position = 0;

            if (_inflaterReset) {
                _inflater.reset();
            }
            _inflater.setInput(b, offset, length);
            while ((len = _inflater.inflate(_buffer, position, _capcacity - position)) > 0) {
                if ((position += len) == _capcacity) {
                    _buffer = Arrays.copyOf(_buffer, _capcacity <<= 1);
                }
            }
            return Arrays.copyOf(_buffer, position);
        }

        public boolean isCompressible() {
            return _deflaterReset;
        }

        public void end() {
            _deflater.end();
            _inflater.end();
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private static class NewZlib extends Zlib {
        public NewZlib(boolean deflaterReset, boolean inflaterReset) {
            super(deflaterReset, inflaterReset);
        }

        @Override
        public byte[] compress(byte[] b, int offset, int length) {
            int len;
            int position = 0;

            if (_deflaterReset) {
                _deflater.reset();
            }
            _deflater.setInput(b, offset, length);
            while ((len = _deflater.deflate(_buffer, position, _capcacity - position, Deflater.SYNC_FLUSH)) > 0) {
                if ((position += len) == _capcacity) {
                    _buffer = Arrays.copyOf(_buffer, _capcacity <<= 1);
                }
            }
            return Arrays.copyOf(_buffer, position - TAIL_LENGTH);
        }

        @Override
        public boolean isCompressible() {
            return true;
        }
    }

    private FrameConnection _connection;
    private FrameHandler _inbound;
    private WebSocketGenerator _outbound;
    private Zlib _zlib;
    private String _parameters;
    private boolean _compressed;

    public PerMessageDeflateExtension() {
        if (Build.VERSION.SDK_INT < 19) {
            _parameters = TextUtils.join("; ", new String[]{ EXTENSION, CLIENT_NO_CONTEXT_TAKEOVER });
        } else {
            _parameters = EXTENSION;
        }
        _compressed = false;
    }

    @Override
    public void onFrame(byte flags, byte opcode, byte[] array, int offset, int length) {
        switch (opcode) {
        case WebSocketConnectionRFC6455.OP_TEXT:
        case WebSocketConnectionRFC6455.OP_BINARY:
            _compressed = ((flags & 0x07) == 0x04);
        case WebSocketConnectionRFC6455.OP_CONTINUATION:
            if (_compressed) {
                try {
                    byte[] buffer;
                    if ((flags &= 0x08) > 0) {
                        buffer = _zlib.decompress(Zlib.appendTailBytes(array, offset, length));
                    } else {
                        buffer = _zlib.decompress(array, offset, length);
                    }
                    _inbound.onFrame(flags, opcode, buffer, 0, buffer.length);
                } catch (DataFormatException e) {
                    __log.warn(e);
                    _connection.close(WebSocketConnectionRFC6455.CLOSE_BAD_DATA, "Bad data");
                }
                return;
            }
        }
        _inbound.onFrame(flags, opcode, array, offset, length);
    }

    @Override
    public void close(int code, String message) {
        _zlib.end();
    }

    @Override
    public int flush() throws IOException {
        return 0;
    }

    @Override
    public boolean isBufferEmpty() {
        return _outbound.isBufferEmpty();
    }

    @Override
    public void addFrame(byte flags, byte opcode, byte[] content, int offset, int length) throws IOException {
        if (opcode == WebSocketConnectionRFC6455.OP_TEXT || opcode == WebSocketConnectionRFC6455.OP_BINARY) {
            if (_zlib.isCompressible()) {
                byte[] compressed = _zlib.compress(content, offset, length);
                _outbound.addFrame((byte) (flags | 0x04), opcode, compressed, 0, compressed.length);
                return;
            }
        }
        _outbound.addFrame(flags, opcode, content, offset, length);
    }

    @Override
    public String getName() {
        return EXTENSION;
    }

    @Override
    public String getParameterizedName() {
        return _parameters;
    }

    @Override
    public boolean init(Map<String, String> parameters) {
        boolean extension = false;
        boolean client_no_context_takeover = false;
        boolean server_no_context_takeover = false;
        int server_max_window_bits = 0;

        _parameters = "";
        for (String key : parameters.keySet()) {
            String value = parameters.get(key);

            if (EXTENSION.equals(key) && TextUtils.isEmpty(value) && !extension) {
                extension = true;
            } else if (CLIENT_NO_CONTEXT_TAKEOVER.equals(key) && TextUtils.isEmpty(value) && !client_no_context_takeover) {
                client_no_context_takeover = true;
            } else if (SERVER_NO_CONTEXT_TAKEOVER.equals(key) && TextUtils.isEmpty(value) && !server_no_context_takeover) {
                server_no_context_takeover = true;
            } else if (SERVER_MAX_WINDOW_BITS.equals(key) && server_max_window_bits == 0) {
                if (TextUtils.isEmpty(value)) {
                    __log.warn("Unexpected parameter: {}", key);
                    return false;
                }
                if (!value.matches("[1-9]\\d?")) {
                    __log.warn("Unexpected parameter: {}={}", key, value);
                    return false;
                }
                int v = Integer.parseInt(value);
                if (v < 8 || v > 15) {
                    __log.warn("Unexpected parameter: {}={}", key, value);
                    return false;
                }
                server_max_window_bits = v;
            } else if (!TextUtils.isEmpty(value)) {
                __log.warn("Unexpected parameter: {}={}", key, value);
                return false;
            } else {
                __log.warn("Unexpected parameter: {}", key);
                return false;
            }
        }
        if (extension) {
            List<String> p = new ArrayList<String>();

            p.add(EXTENSION);
            if (client_no_context_takeover) {
                p.add(CLIENT_NO_CONTEXT_TAKEOVER);
            }
            if (server_no_context_takeover) {
                p.add(SERVER_NO_CONTEXT_TAKEOVER);
            }
            if (server_max_window_bits > 0) {
                p.add(String.format("%s=%d", SERVER_MAX_WINDOW_BITS, server_max_window_bits));
            }
            _parameters = TextUtils.join("; ", p);

            if (Build.VERSION.SDK_INT < 19) {
                _zlib = new Zlib(client_no_context_takeover, server_no_context_takeover);
            } else {
                _zlib = new NewZlib(client_no_context_takeover, server_no_context_takeover);
            }
        }
        return extension;
    }

    @Override
    public void bind(FrameConnection connection, FrameHandler inbound, WebSocketGenerator outbound) {
        _connection = connection;
        _inbound = inbound;
        _outbound = outbound;
    }
}


text:
{% extends "base.html" %}
{% block content %}

Home

{{ business }}

{{ business.name }}

{% if business_editable %}

  Update Business
  Delete Business

{% endif %}

Description

{% if business.description %}{{ business.description|linebreaks }}
{% else %}
No description has been written for this business.
{% endif %}

Associated Stations

{% if business_editable %}

  Create Station

{% endif %}

  {% for sb in business.stationbusiness_set.all %}

{{ sb.station }}

  {% empty %}

No station is associated with this business!

  {% endfor %}

Location

Address

{{ business.address_1 }}

  {% if business.address_2 %}

Address (cont.)

{{ business.address_2 }}

  {% endif %}

Country

{{ business.country }}

  {% if business.region %}

Region

{{ business.region }}

  {% endif %}

City

{{ business.city }}

Postal Code

{{ business.postal_code }}

Business Members

{% if business_editable %}

  Create Business
    Membership

{% endif %}

  {% for bmembership in business.businessmembership_set.all %}

{% if business_editable %}
    Delete |
    {% endif %}
    Username: {{ bmembership.user }}

  {% empty %}

This business has no members.

  {% endfor %}

{% endblock %}


text:
package org.apache.struts.taglib.html;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.Globals;
import org.apache.struts.taglib.TagUtils;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;

/**
 * This tag tells all other html taglib tags to render themselves in xhtml.
 * Its presence in a page turns on xhtml.

 * Example:
 <html:xhtml/>

 */
public class XhtmlTag extends TagSupport {

    /**
     * Commons logging instance.
     */
    private static final Log log = LogFactory.getLog(XhtmlTag.class);

    /**
     * The scope within which to store the markup format.
     */
    private String scope;

    /**
     * Constructor for XhtmlTag.
     */
    public XhtmlTag() {
        super();
    }

    /**
     * @see javax.servlet.jsp.tagext.Tag#doEndTag()
     */
    public int doEndTag() throws JspException {
        int inScope = PageContext.PAGE_SCOPE;
        try {
            if (this.scope != null) {
                inScope = TagUtils.getInstance().getScope(this.scope);
            }
        } catch (JspException e) {
            log.warn("invalid scope name - defaulting to PAGE_SCOPE", e);
        }

        this.pageContext.setAttribute(Globals.XHTML_KEY, "true", inScope);
        return EVAL_PAGE;
    }

    public String getScope() {
        return this.scope;
    }

    public void setScope(String scope) {
        this.scope = scope;
    }
}


text:
package com.turn.edc.service.retry;

/**
 * Exception when a retry attempt has exceeded the maximum number of attempts
 *
 * @author tshiou
 */
public class NumberOfFailedAttemptsException extends Exception {
	public NumberOfFailedAttemptsException(
			Class<? extends RetryAttempt> retryAttemptClass, int numberOfAttempts ) {
		super(retryAttemptClass.getSimpleName() + " exceeded the maximum number of retries at " + numberOfAttempts);
	}
}


text:
require 'test_helper'

class CallListTest < ActionDispatch::IntegrationTest
  before do
    Capybara.current_driver = :poltergeist
    @patient = create :patient, name: 'Susan Everyteen'
    @pregnancy = create :pregnancy, patient: @patient
    @patient_2 = create :patient, name: 'Thorny', primary_phone: '123-123-1235'
    @pregnancy_2 = create :pregnancy, patient: @patient_2
    @user = create :user
    log_in_as @user
    add_to_call_list @patient.name
  end

  after do
    #use reset_sessions! if enabling Timecop
    #Capybara.reset_sessions!
    Capybara.use_default_driver
  end

  describe 'populating call list' do
    it 'should add people to the call list roll' do
      within :css, '#call_list_content' do
        assert has_text? @patient.name
        assert has_link? 'Remove'
      end

      # problematic test
      # add_to_call_list @patient_2.name
      # within :css, '#call_list_content' do
        # assert has_text? @patient.name
        # assert has_text? @patient_2.name
        # assert has_link? 'Remove', count: 2
      # end
    end

    it 'should let you remove people from the call list roll' do
      find('a', text: 'Remove').click
      within :css, '#call_list_content' do
        assert has_no_text? @patient.name
      end
    end
  end

  describe 'call list persistence between multiple users' do
    before do
      @user_2 = create :user
    end

    it 'should allow a call to be on two users call lists' do
      sign_out
      log_in_as @user_2
      add_to_call_list @patient.name
      within :css, '#call_list_content' do
        assert has_text? @patient.name
      end
      sign_out

      log_in_as @user
      within :css, '#call_list_content' do
        assert has_text? @patient.name
      end
    end
  end

  describe 'completed calls section' do
    before do
      within :css, '#call_list_content' do
        find("a[href='#call-123-123-1234']").click
      end
      find('a', text: 'I left a voicemail for the patient').click
      visit authenticated_root_path
    end

    # problematic test
    # it 'should add a call to completed when a call was made within 8 hrs' do
    #   within :css, '#completed_calls_content' do
    #     assert has_text? @patient.name
    #   end
    # end

    # problematic test
    # it 'should time a call out after 8 hours' do
    #   Timecop.freeze(9.hours.from_now) do
    #     visit authenticated_root_path
    #     within :css, '#completed_calls_content' do
    #       assert has_no_text? @patient.name
    #     end
    #   end
    # end
  end

  private

  def add_to_call_list(patient_name)
    fill_in 'search', with: patient_name
    click_button 'Search'
    find('a', text: 'Add').click
  end
end


text:
package org.apache.harmony.auth.tests.module;

import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.Set;

import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginException;

import junit.framework.TestCase;

import org.apache.harmony.auth.module.LdapLoginModule;
import org.apache.harmony.auth.UserPrincipal;

public class LdapLoginModuleTest extends TestCase {

    //  module options
    private HashMap<String, String> options = new HashMap<String, String>();

    private final String USER_PROVIDER_URL = "ldap://9.181.106.121:389/ou=People,o=JNDITutorial,dc=my-domain,dc=com";

    protected void setUp() throws Exception {
        options.put("userProvider", USER_PROVIDER_URL);
        options.put("useSSL", "false");
    }

    @Override
    protected void tearDown() throws Exception {
        options.clear();
    }

    /**
     * Test method for {@link org.apache.harmony.auth.module.LdapLoginModule#abort()}.
     */
    public void test_abort() throws LoginException{
        LdapLoginModule jlm = new LdapLoginModule();
        try {
            assertFalse("Should return false if login failed or no login", jlm
                    .abort());
        } catch (LoginException e) {
            fail("Abort failed");
        }
        Subject subject = new Subject();
        subject.setReadOnly();
        jlm.initialize(subject, null, null, options);
        try {
            assertFalse("Should return false if login failed or no login", jlm
                    .abort());
        } catch (Exception e) {
            fail("Not any exception here");
        }
        subject = new Subject();
        jlm.initialize(subject, new FaultCallbackHandler(), null, options);
        try {
            jlm.login();
            fail("login should fail");
        } catch (LoginException e) {
            assertFalse("Should return false because of login failure", jlm
                    .abort());
        }
        subject = new Subject();
        options.put("authIdentity","cn=Manager,dc=my-domain,dc=com");
        jlm.initialize(subject, new MockCallbackHandler(), null, options);
        jlm.login();
        assertTrue("Should return true if login was successful", jlm
                .abort());
    }

    /**
     * Test method for {@link org.apache.harmony.auth.module.LdapLoginModule#commit()}.
     */
    public void test_commit() {
        LdapLoginModule module = new LdapLoginModule();
        Subject subject = new Subject();
        options.put("authIdentity","cn=Manager,dc=my-domain,dc=com");
        module.initialize(subject, new MockCallbackHandler(), null, options);
        try {
            assertTrue("Login should be successful", module.login());
            module.commit();
        } catch (LoginException e) {
            fail("Login shouldn't fail");
        }
        Set<Principal> principals = subject.getPrincipals();
        assertFalse("Should get at least one principal", principals.isEmpty());
        subject = new Subject();
        subject.setReadOnly();
        module.initialize(subject, new MockCallbackHandler(), null, options);
        try {
            assertFalse("Commit shouldn't be successful", module.commit());
            fail("Should throw LoginException here because of trying to clear read-only subject");
        } catch (LoginException e) {
            // expected LoginException here
        }
    }

    /**
     * Test method for {@link org.apache.harmony.auth.module.LdapLoginModule#initialize(javax.security.auth.Subject, javax.security.auth.callback.CallbackHandler, java.util.Map, java.util.Map)}.
     */
    public void test_initialize() {
        LdapLoginModule module = new LdapLoginModule();
        try {
            module.initialize(null, null, null, null);
            fail("Should throw NullPointerException here.");
        } catch (NullPointerException e) {
            // expected NullPointerException
        }
    }

    /**
     * Test method for {@link org.apache.harmony.auth.module.LdapLoginModule#login()}.
     */
    public void test_login() {
        LdapLoginModule module = new LdapLoginModule();
        HashMap<String, String> emptyOptions = new HashMap<String, String>();
        module.initialize(null, new MockCallbackHandler(), null, emptyOptions);
        try {
            module.login();
            fail("Should throw LoginException here.");
        } catch (LoginException e) {
            // expected LoginException
        }

        options.put("authIdentity","cn=Manager,dc=my-domain,dc=com");
        Subject subject = new Subject();
        module.initialize(subject, new MockCallbackHandler(), null, options);
        try {
            assertTrue("Login should be successful", module.login());
        } catch (LoginException e) {
            fail("Login shouldn't fail");
        }
        module.initialize(subject, new FaultCallbackHandler(), null, options);
        try {
            assertFalse("Login shouldn't be successful", module.login());
            fail("Login should fail");
        } catch (LoginException e) {
            // expected Loginexception here
        }
    }

    /**
     * Test method for {@link org.apache.harmony.auth.module.LdapLoginModule#logout()}.
     */
    public void test_logout() {
        LdapLoginModule module = new LdapLoginModule();
        Subject subject = new Subject();
        options.put("authIdentity","cn=Manager,dc=my-domain,dc=com");
        module.initialize(subject, new MockCallbackHandler(), null, options);
        try {
            assertTrue("Login should be successful", module.login());
            module.commit();
        } catch (LoginException e) {
            fail("Login shouldn't fail");
        }
        Set<Principal> principals = subject.getPrincipals();
        assertFalse("Should get at least one principal", principals.isEmpty());
        try {
            assertTrue("Should be true", module.logout());
        } catch (LoginException e) {
            fail("Logout failed");
        }
        principals = subject.getPrincipals();
        assertTrue("Principals should be cleared", principals.isEmpty());
    }

    public void test_optionsAndSharedStatus() throws LoginException{
        options.put("authIdentity","cn=Manager,dc=my-domain,dc=com");
        options.put("authzIdentity","testAuthzIdentityOption");
        LdapLoginModule module = new LdapLoginModule();
        Subject subject = new Subject();
        module.initialize(subject, new MockCallbackHandler(), null, options);
        try {
            module.login();
            module.commit();
            assertTrue("Should get a principal from authzIdentity option",subject.getPrincipals().contains(new UserPrincipal("testAuthzIdentityOption")));
        }
        catch(LoginException e){
            fail("Login failed");
        }
        finally{
            module.logout();
        }

        options.put("debug", "true");
        options.put("useFirstPass", "true");
        HashMap<String, Object> status = new HashMap<String,Object>();
        status.put("javax.security.auth.login.name", "leo");
        status.put("javax.security.auth.login.password", "faultPass".toCharArray());
        subject = new Subject();
        module.initialize(subject, new MockCallbackHandler(), status, options);
        try {
            module.login();
            fail("Should be failed for using password from shared state");
        }
        catch(LoginException e){
            //expected LoginException here
        }

        options.remove("useFirstPass");
        options.put("tryFirstPass", "true");
        module.initialize(subject, new MockCallbackHandler(), status, options);
        try {
            module.login();
            module.commit();
        }
        catch(LoginException e){
            fail("Login should be failed");
        }
        finally{
            module.logout();
        }

        options.remove("tryFirstPass");
        options.put("clearPass", "true");
        status.put("javax.security.auth.login.name", "leo");
        status.put("javax.security.auth.login.password", "passw0rd".toCharArray());
        module.initialize(subject, new MockCallbackHandler(), status, options);
        try {
            module.login();
            module.commit();
            assertNull("javax.security.auth.login.name in shared state should be null when clearPass switch on",status.get("javax.security.auth.login.name"));
            assertNull("javax.security.auth.login.password in shared state should be null when clearPass switch on",status.get("javax.security.auth.login.password"));
        } catch (LoginException e) {
            fail("Login shouldn't fail");
        }
        finally{
            module.logout();
        }

        status = new HashMap<String,Object>();
        options.remove("clearPass");
        options.put("storePass", "true");
        module.initialize(subject, new FaultCallbackHandler(), status, options);
        try {
            module.login();
            module.commit();
        } catch (LoginException e) {
            assertNull("javax.security.auth.login.name in shared state should be null when login failed",status.get("javax.security.auth.login.name"));
            assertNull("javax.security.auth.login.password in shared state should be null when login failed",status.get("javax.security.auth.login.password"));
        }
        finally{
            module.logout();
        }

        module.initialize(subject, new MockCallbackHandler(), status, options);
        try {
            module.login();
            module.commit();
        } catch (LoginException e) {
            fail("Login failed");
        }
        finally{
            module.logout();
        }
        assertNotNull("javax.security.auth.login.name should be stored in shared state when storePass switch on",status.get("javax.security.auth.login.name"));
        assertNotNull("javax.security.auth.login.password should be stored in shared state when storePass switch on",status.get("javax.security.auth.login.password"));

        status.put("javax.security.auth.login.name", "tester");
        status.put("javax.security.auth.login.password", "testerPass");
        module.initialize(subject, new MockCallbackHandler(), status, options);
        try {
            module.login();
            module.commit();
        } catch (LoginException e) {
            fail("Login failed");
        }
        finally{
            module.logout();
        }
        assertEquals("Should't override the username value in sharedState",status.get("javax.security.auth.login.name"),"tester");
        assertEquals("Should't override the password value in sharedState",status.get("javax.security.auth.login.password"),"testerPass");
    }

    static private class MockCallbackHandler implements CallbackHandler{

        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for(int i=0;i<callbacks.length;i++){
                if(callbacks[i] instanceof NameCallback){
                    NameCallback nc = (NameCallback)callbacks[i];
                    nc.setName("leo");
                }
                else if(callbacks[i] instanceof PasswordCallback){
                    PasswordCallback pc = (PasswordCallback)callbacks[i];
                    pc.setPassword("secret".toCharArray());
                }
                else
                {
                    throw new Error(callbacks[i].getClass().toString());
                }
            }
        }
    }

    static private class FaultCallbackHandler implements CallbackHandler{

        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for(int i=0;i<callbacks.length;i++){
                if(callbacks[i] instanceof NameCallback){
                    NameCallback nc = (NameCallback)callbacks[i];
                    nc.setName("leo");
                }
                else if(callbacks[i] instanceof PasswordCallback){
                    PasswordCallback pc = (PasswordCallback)callbacks[i];
                    pc.setPassword("password".toCharArray());
                }
                else
                {
                    throw new Error(callbacks[i].getClass().toString());
                }
            }
        }
    }
}


text:
#include<stdio.h>
#include <time.h>
#include<math.h>
// this is for mingw, for other compilers you may nead #include<thread> instead
#include"threads.h"
const int DIM=1024;
const int NUM_THREADS=8;

float*a;
float *b;
float *c;

// some functions to make and check matrix multiplications
// n.b. this just makes a single matrix with numbers in, and an
// identity matrix - it isn't a very good matrix test
void makeMatrices( float*a,float *b,const int DIM)
{
	for(int c=0;c<DIM;c++)
	{
		a[c+c*DIM]=c;
		a[c*DIM]=c;
		a[c]=c;
		b[c+c*DIM]=1; // b = identity matrix
	}
}

void checkMatrix(float *a,float *c,const int DIM)
{
	for(int i=0;i<DIM*DIM;i++)
	{
		if(fabs(a[i]-c[i])>0.001)
		{
			printf("Error in multiply %f %f\n",a[i],c[i]);
			return;
		}
	}
}

// this thread function just calculates the output value for all cells in a
// range of columns multiple threads are made to do the
// full matrix multiply
void multiplyThread(int colStart,int colEnd)
{
	if(colEnd>DIM)
	{
		colEnd=DIM;
	}
	for(int col=colStart;col<colEnd;col++)
	{
		for(int row=0;row<DIM;row++)
		{
			c[row+col*DIM]=0;
			for(int cell=0;cell<DIM;cell++)
			{
				c[row+col*DIM]+=a[row+cell*DIM]*b[cell+col*DIM];
			}
		}
	}
}

int main()
{
	clock_t start, end;
	a=new float[DIM*DIM];
	b=new float[DIM*DIM];
	c=new float[DIM*DIM];
	makeMatrices(a,b,DIM);
	printf("go\n");
	double cpu_time_used;

	// basic matrix multiply - in the single main thread
	start = clock();
	// cycle round columns and rows of the output matrix
	for(int row=0;row<DIM;row++)
	{
	  for(int col=0;col<DIM;col++)
	  {
		// calculate one output cell
		c[row+col*DIM]=0;
		for(int cell=0;cell<DIM;cell++)
		{
			c[row+col*DIM]+=a[row+cell*DIM]*b[cell+col*DIM];
		}
	  }
	}
	end = clock();
	// time how long it takes
	cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
	printf("done standard version %f\n",cpu_time_used);
	checkMatrix(a,c,DIM);
	std::thread **threads=new std::thread*[NUM_THREADS];
	// threaded multiply
	start = clock();
	int start_col=0;
	int end_col=0;
	// multiply matrix in thread - this launches all the threads
	// each of which calculates a subset of the columns of the
	// output matrix
	for(int c=0;c<NUM_THREADS;c++)
	{
		end_col=((c+1)*DIM)/NUM_THREADS;
		// launch a thread to do just some of the columns
		std::thread *t =new std::thread(std::bind(multiplyThread,start_col,end_col));
		threads[c]=t;
		start_col=end_col;
	}
	// then we wait for all threads to finish
	for(int c=0;c<NUM_THREADS;c++)
	{
		threads[c]->join();
	}
	// once all threads are finished, we are done
	end = clock();
	// time how long it takes
	cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
	printf("done threaded multiply on %d threads %f\n",NUM_THREADS,cpu_time_used);
	checkMatrix(a,c,DIM);
	// don't forget to delete the allocated memory
	delete a;
	delete b;
	delete c;
}


text:
open module com.hack23.cia.model.external.riksdagen.dokumentlista.impl {
	exports com.hack23.cia.model.external.riksdagen.dokumentlista.impl;

	requires com.hack23.model.common.api;
	requires com.hack23.cia.model.common.impl;

	requires java.xml.bind;
	requires java.persistence;
	requires org.hibernate.orm.jpamodelgen;
	requires org.slf4j;
	requires org.apache.commons.lang3;
	requires jaxb2.basics.runtime;
	requires org.hibernate.search.mapper.pojo;

}


text:
Rails.application.routes.draw do
  get "cookies-policy", to: "eu_cookies#policy",
                        as: :cookies_policy,
                        constraints: ->(_) {
                          EuCookies.enabled && EuCookies.display_policy == true
                        }
end


text:
<?php

namespace Drupal\field_ui;

use Drupal\Component\Utility\Html;
use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\FieldTypePluginManagerInterface;
use Drupal\Core\Url;
use Drupal\field\FieldConfigInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides lists of field config entities.
 */
class FieldConfigListBuilder extends ConfigEntityListBuilder {

  /**
   * The name of the entity type the listed fields are attached to.
   *
   * @var string
   */
  protected $targetEntityTypeId;

  /**
   * The name of the bundle the listed fields are attached to.
   *
   * @var string
   */
  protected $targetBundle;

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

  /**
   * The field type plugin manager.
   *
   * @var \Drupal\Core\Field\FieldTypePluginManagerInterface
   */
  protected $fieldTypeManager;

  /**
   * Constructs a new class instance.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
   * @param \Drupal\Core\Field\FieldTypePluginManagerInterface $field_type_manager
   *   The field type manager
   */
  public function __construct(EntityTypeInterface $entity_type, EntityManagerInterface $entity_manager, FieldTypePluginManagerInterface $field_type_manager) {
    parent::__construct($entity_type, $entity_manager->getStorage($entity_type->id()));

    $this->entityManager = $entity_manager;
    $this->fieldTypeManager = $field_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static($entity_type, $container->get('entity.manager'), $container->get('plugin.manager.field.field_type'));
  }

  /**
   * {@inheritdoc}
   */
  public function render($target_entity_type_id = NULL, $target_bundle = NULL) {
    $this->targetEntityTypeId = $target_entity_type_id;
    $this->targetBundle = $target_bundle;

    $build = parent::render();
    $build['table']['#attributes']['id'] = 'field-overview';
    $build['table']['#empty'] = $this->t('No fields are present yet.');

    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function load() {
    $entities = array_filter($this->entityManager->getFieldDefinitions($this->targetEntityTypeId, $this->targetBundle), function ($field_definition) {
      return $field_definition instanceof FieldConfigInterface;
    });

    // Sort the entities using the entity class's sort() method.
    // See \Drupal\Core\Config\Entity\ConfigEntityBase::sort().
    uasort($entities, [$this->entityType->getClass(), 'sort']);
    return $entities;
  }

  /**
   * {@inheritdoc}
   */
  public function buildHeader() {
    $header = [
      'label' => $this->t('Label'),
      'field_name' => [
        'data' => $this->t('Machine name'),
        'class' => [RESPONSIVE_PRIORITY_MEDIUM],
      ],
      'field_type' => $this->t('Field type'),
    ];
    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $field_config) {
    /** @var \Drupal\field\FieldConfigInterface $field_config */
    $field_storage = $field_config->getFieldStorageDefinition();
    $route_parameters = [
      'field_config' => $field_config->id(),
    ] + FieldUI::getRouteBundleParameter($this->entityManager->getDefinition($this->targetEntityTypeId), $this->targetBundle);

    $row = [
      'id' => Html::getClass($field_config->getName()),
      'data' => [
        'label' => $field_config->getLabel(),
        'field_name' => $field_config->getName(),
        'field_type' => [
          'data' => [
            '#type' => 'link',
            '#title' => $this->fieldTypeManager->getDefinitions()[$field_storage->getType()]['label'],
            '#url' => Url::fromRoute("entity.field_config.{$this->targetEntityTypeId}_storage_edit_form", $route_parameters),
            '#options' => ['attributes' => ['title' => $this->t('Edit field settings.')]],
          ],
        ],
      ],
    ];

    // Add the operations.
    $row['data'] = $row['data'] + parent::buildRow($field_config);

    if ($field_storage->isLocked()) {
      $row['data']['operations'] = ['data' => ['#markup' => $this->t('Locked')]];
      $row['class'][] = 'menu-disabled';
    }

    return $row;
  }

  /**
   * {@inheritdoc}
   */
  public function getDefaultOperations(EntityInterface $entity) {
    /** @var \Drupal\field\FieldConfigInterface $entity */
    $operations = parent::getDefaultOperations($entity);

    if ($entity->access('update') && $entity->hasLinkTemplate("{$entity->getTargetEntityTypeId()}-field-edit-form")) {
      $operations['edit'] = [
        'title' => $this->t('Edit'),
        'weight' => 10,
        'url' => $entity->urlInfo("{$entity->getTargetEntityTypeId()}-field-edit-form"),
        'attributes' => [
          'title' => $this->t('Edit field settings.')
        ],
      ];
    }
    if ($entity->access('delete') && $entity->hasLinkTemplate("{$entity->getTargetEntityTypeId()}-field-delete-form")) {
      $operations['delete'] = [
        'title' => $this->t('Delete'),
        'weight' => 100,
        'url' => $entity->urlInfo("{$entity->getTargetEntityTypeId()}-field-delete-form"),
        'attributes' => [
          'title' => $this->t('Delete field.')
        ],
      ];
    }

    $operations['storage-settings'] = [
      'title' => $this->t('Storage settings'),
      'weight' => 20,
      'attributes' => ['title' => $this->t('Edit storage settings.')],
      'url' => $entity->urlInfo("{$entity->getTargetEntityTypeId()}-storage-edit-form"),
    ];

    return $operations;
  }

}


text:
<?php

namespace Ardent;

use Ardent\Exception\KeyException;
use Ardent\Exception\TypeException;
use ArrayAccess;

interface Map extends ArrayAccess, \IteratorAggregate, Collection {

    /**
     * @param $key
     *
     * @return mixed
     * @throws KeyException when the $key does not exist.
     * @throws TypeException when the $key is not the correct type.
     */
    function get($key);

    /**
     * Note that if the key is considered equal to an already existing key in
     * the map that it's value will be replaced with the new one.
     *
     * @param $key
     * @param mixed $value
     *
     * @return void
     * @throws TypeException when the $key or $value is not the correct type.
     */
    function insert($key, $value);

    /**
     * @param $key
     *
     * @return mixed
     * @throws TypeException when the $key is not the correct type.
     */
    function remove($key);

}


text:
Sequel.migration do
  change do
    alter_table(:dynflow_delayed_plans) do
      add_column :frozen, :boolean
    end
    self[:dynflow_delayed_plans].update(:frozen => false)
  end
end


text:
package igeo;

import java.util.ArrayList;
import java.util.HashMap;
import java.awt.*;
import java.nio.*;

import igeo.gui.*;

/**
   A server to contain graphic objects to manage drawing process.

   @author Satoru Sugihara
*/
public class IGraphicServer{

    public static IGraphicMode defaultMode =
	new IGraphicMode(IGraphicMode.GraphicType.GL, true, true, true); //

    //boolean shareObjects = false;

    /*
    ArrayList<IGraphicGLWireI> graphicsGLWire;
    ArrayList<IGraphicGLFillI> graphicsGLFill;
    ArrayList<IGraphicGLTransparentI> graphicsGLTrans;

    HashMap<IView, ArrayList<IGraphicJavaWireI>> graphicsJavaWire;
    HashMap<IView, ArrayList<IGraphicJavaFillI>> graphicsJavaFill;
    HashMap<IView, ArrayList<IGraphicJavaTransparentI>> graphicsJavaTrans;
    */

    //public ArrayList<IGraphicObject> graphicsGL;
    //public HashMap<IView, ArrayList<IGraphicObject>> graphicsJava;

    /** graphic elements keeping 3D info; no need to be sorted due to depth buffer */
    public ArrayList<IGraphicI> graphics3D; //graphicsGL;
    /** graphic elements already flattened in 2D; need to be sorted and vary depending on view */
    public HashMap<IView, ArrayList<IGraphicI>> graphics2D; //graphicsJava;

    //ArrayList<IGraphicObject> graphicsGLWire;
    //ArrayList<IGraphicObject> graphicsGLFill;
    //ArrayList<IGraphicObject> graphicsGLTrans;
    //HashMap<IView, ArrayList<IGraphicObject>> graphicsJavaWire;
    //HashMap<IView, ArrayList<IGraphicObject>> graphicsJavaFill;
    //HashMap<IView, ArrayList<IGraphicObject>> graphicsJavaTrans;

    public ArrayList<IView> views;

    public IServer server;

    public IPanelI panel;

    public IGraphicMode[] modes=null;

    public boolean useGL;

    public String bgImageFilename;
    //public int bgTextureID;
    //public boolean bgTextureGenerated=false;

    public IGraphicServer(IServer s, IPanelI p){
	server=s;
	panel = p;
	views=new ArrayList<IView>();
	for(int i=0; i<panel.paneNum(); i++) views.add(panel.pane(i).getView());
    }

    public void addView(IView v){ views.add(v); }

    public IView view(int i){ return views.get(i); }

    public int viewNum(){ return views.size(); }

    public void setMode(IGraphicMode m){
	if(views!=null) for(IView v:views) v.setMode(new IGraphicMode(m));
    }

    public void enableGL(){ useGL=true; }
    public void disableGL(){ useGL=false; }
    public boolean isGL(){ return useGL; }

    public void bg(IColor c1, IColor c2, IColor c3, IColor c4){
	if(views!=null) for(IView v:views) v.bgColor(c1,c2,c3,c4);
    }
    public void background(IColor c1, IColor c2, IColor c3, IColor c4){ bg(c1,c2,c3,c4); }

    public void bg(String imageFilename){
	bgImageFilename = imageFilename;
	/*
	int w = IImageLoader.getWidth(img);
	int h = IImageLoader.getHeight(img);
	byte[] buf = IImageLoader.getRGBBytes(img);

	IG.err("w = "+w+", h = "+h+", w*h*3="+(w*h*3));
	IG.err("buf.length = "+buf.length);

	// upside down for GL
	byte[] buf2 = new byte[buf.length];
	for(int j=0; j<h; j++){
	    for(int i=0; i<w; i++){
		buf2[((h-1-j)*w+i)*3] = buf[(j*w+i)*3];
		buf2[((h-1-j)*w+i)*3+1] = buf[(j*w+i)*3+1];
		buf2[((h-1-j)*w+i)*3+2] = buf[(j*w+i)*3+2];
	    }
	}
	ByteBuffer bbuf = ByteBuffer.wrap(buf2);
	if(views!=null){
	    for(IView v:views){
		v.bgImage(bbuf,w,h);
	    }
	}
	*/
    }
    public void background(String imageFilename){
	bg(imageFilename);
    }

    public void add(IObject e){
	boolean is3DGraphic=false;
	for(IView v: views) if(v.mode().isGraphic3D()) is3DGraphic=true;

	if(is3DGraphic){
	    //IGraphicObject g = e.getGraphic(views.get(0).mode());
	    IGraphicI g = e.getGraphic(views.get(0).mode());
	    if(g!=null) add(g, views.get(0));
	    else{ IOut.err("graphic of the object is null : "+e); }

	    /*
	    ArrayList<IGraphicMode.DisplayType> dtype = new ArrayList<IGraphicMode.DisplayType>();
	    for(IView v: views){
		if(!dtype.contains(v.mode().getDisplayType())){
		    dtype.add(v.mode().getDisplayType());
		    IGraphicObject g = e.getGraphic(v.mode());
		    if(g!=null) add(g, v);
		}
	    }
	    */
	}
	else{
	    for(IView v: views){
		//IGraphicObject g = e.getGraphic(v.mode());
		IGraphicI g = e.getGraphic(v.mode());
		if(g!=null) add(g, v);
		else{ IOut.err("graphic of the object is null : "+e); }
	    }
	}
    }

    //public void add(IGraphicObject e, IView view){
    public void add(IGraphicI e, IView view){
	if(view.mode().isGraphic3D()){
	    //if(graphics3D==null) graphics3D = new ArrayList<IGraphicObject>();
	    if(graphics3D==null) graphics3D = new ArrayList<IGraphicI>();
	    graphics3D.add(e);
	}
	else if(view.mode().isGraphic2D()){
	    if(graphics2D==null)
		//graphics2D = new HashMap<IView, ArrayList<IGraphicObject>>();
		graphics2D = new HashMap<IView, ArrayList<IGraphicI>>();
	    //ArrayList<IGraphicObject> objects = graphics2D.get(view);
	    ArrayList<IGraphicI> objects = graphics2D.get(view);
	    if(objects==null){
		//objects = new ArrayList<IGraphicObject>();
		objects = new ArrayList<IGraphicI>();
		graphics2D.put(view, objects);
	    }
	    objects.add(e);
	}

	/*
	if(view.mode().isGL()){
	    if(view.mode().isWireframe()){
		if(graphicsGLWire==null) graphicsGLWire = new ArrayList<IGraphicObject>();
		graphicsGLWire.add(e);
	    }
	    else if(view.mode().isFill()){
		if(graphicsGLFill==null) graphicsGLFill = new ArrayList<IGraphicObject>();
		graphicsGLFill.add(e);
	    }
	    else if(view.mode().isTransparent()){
		if(graphicsGLTrans==null) graphicsGLTrans = new ArrayList<IGraphicObject>();
		graphicsGLTrans.add(e);
	    }
	}
	else if(view.mode().isJ2D()){
	    if(view.mode().isWireframe()){
		if(graphicsJavaWire==null)
		    graphicsJavaWire = new HashMap<IView, ArrayList<IGraphicObject>>();
		ArrayList<IGraphicObject> objects = graphicsJavaWire.get(view);
		if(objects==null){
		    objects = new ArrayList<IGraphicObject>();
		    graphicsJavaWire.put(view, objects);
		}
		objects.add(e);
	    }
	    else if(view.mode().isFill()){
		if(graphicsJavaFill==null)
		    graphicsJavaFill = new HashMap<IView, ArrayList<IGraphicObject>>();
		ArrayList<IGraphicObject> objects = graphicsJavaFill.get(view);
		if(objects==null){
		    objects = new ArrayList<IGraphicObject>();
		    graphicsJavaFill.put(view, objects);
		}
		objects.add(e);
	    }
	    else if(view.mode().isTransparent()){
		if(graphicsJavaTrans==null)
		    graphicsJavaTrans = new HashMap<IView, ArrayList<IGraphicObject>>();
		ArrayList<IGraphicObject> objects = graphicsJavaTrans.get(view);
		if(objects==null){
		    objects = new ArrayList<IGraphicObject>();
		    graphicsJavaTrans.put(view, objects);
		}
		objects.add(e);
	    }
	}
	*/
    }

    //public ArrayList<IGraphicObject> getObjects(IView view){
    public ArrayList<IGraphicI> getObjects(IView view){
	if(view.mode().isGraphic3D()) return graphics3D;
	if(view.mode().isGraphic2D()) return graphics2D.get(view);
	return null;
	/*
	if(//shareObjects ||
	   view.mode().isGL()){
	    if(view.mode().isWireframe()) return graphicsGLWire;
	    if(view.mode().isFill()) return graphicsGLFill;
	    if(view.mode().isTransparent()) return graphicsGLTrans;
	}
	else if(view.mode().isJ2D()){
	    if(view.mode().isWireframe()) return graphicsJavaWire.get(view);
	    if(view.mode().isFill()) return graphicsJavaFill.get(view);
	    if(view.mode().isTransparent()) return graphicsJavaTrans.get(view);
	}
	return null;
	*/
    }

    //public void remove(IGraphicObject g){
    public void remove(IGraphicI g){
	// search and remove
	if(modes==null) modes = IGraphicMode.getAllModes();
	for(IGraphicMode m : modes){
	    if(g.isDrawable(m)){
		if(m.isGraphic3D()){ graphics3D.remove(g); }
		else if(m.isGraphic2D()){
		    for(IView v: views)
			if(graphics2D.get(v)!=null) graphics2D.get(v).remove(g);
		}

		/*
		if(m.isGraphic3D()){
		    if(m.isWireframe()) graphicsGLWire.remove(g);
		    else if(m.isFill()) graphicsGLFill.remove(g);
		    else if(m.isTransparent()) graphicsGLTrans.remove(g);
		}
		else if(m.isGraphic2D()){
		    if(m.isWireframe()){
			for(IView v: views)
			    if(graphicsJavaWire.get(v)!=null)
				graphicsJavaWire.get(v).remove(g);
		    }
		    else if(m.isFill()){
			for(IView v: views)
			    if(graphicsJavaFill.get(v)!=null)
				graphicsJavaFill.get(v).remove(g);
		    }
		    else if(m.isTransparent()){
			for(IView v: views)
			    if(graphicsJavaTrans.get(v)!=null)
				graphicsJavaTrans.get(v).remove(g);
		    }
		}
		*/
	    }
	}
    }

    /** remove all the graphic objects
     */
    public void clearObjects(){
	if(graphics3D!=null){ graphics3D.clear(); graphics3D = null; }
	if(graphics2D!=null){
	    for(IView v:views){
		if(graphics2D.get(v)!=null) graphics2D.get(v).clear();
	    }
	    graphics2D.clear();
	    graphics2D=null;
	}

	/*
	if(graphicsGLWire!=null) graphicsGLWire.clear();
	if(graphicsGLFill!=null) graphicsGLFill.clear();
	if(graphicsGLTrans!=null) graphicsGLTrans.clear();
	for(IView v:views){
	    if(graphicsJavaWire!=null) graphicsJavaWire.get(v).clear();
	    if(graphicsJavaFill!=null) graphicsJavaFill.get(v).clear();
	    if(graphicsJavaTrans!=null) graphicsJavaTrans.get(v).clear();
	}
	*/
    }

    /** remove all views.
	don't clearViews before clearObjects
     */
    public void clearViews(){ views.clear(); }

}


text:
using System;
using System.Reflection;

namespace NanoBuilder
{
   internal interface IConstructorMatcher
   {
      ConstructorInfo Match( ConstructorInfo[] constructors, Type[] types );
   }
}


text:
<!doctype html>

<meta content="text/html; charset=UTF-8" http-equiv="content-type" />

<title>Embeded Topbar template</title>

				<button type="button" class="navbar-toggle" data-toggle="collapse"
					data-target=".navbar-ex1-collapse">
					Toggle navigation
				</button>
				FoBo


text:
const Block = require('./block');
const R = require('ramda');

class Blocks extends Array {
    static fromJson(data) {
        let blocks = new Blocks();
        R.forEach((block) => { blocks.push(Block.fromJson(block)); }, data);
        return blocks;
    }
}

module.exports = Blocks;


text:
package net.savantly.graphite.query;

public enum GraphiteTimeUnit {

	SECONDS("s"),
	MINUTES("min"),
	HOURS("h"),
	DAYS("d"),
	WEEKS("w"),
	MONTHS("mon"),
	YEARS("y");

	private final String value;
	public String value() {
		return this.value;
	}

	GraphiteTimeUnit(String value){
		this.value = value;
	}

}


text:
SELECT 0 FROM (SELECT * FROM t1)
UNION SELECT 9 FROM (SELECT a FROM t1)
LIMIT ii;


text:
"""
api_manager.py

This module contains functions that manage the RESTful API.
"""

from rad.models import *
from flask.ext.restless import *

def pre_post(**kw):
    """
    Will check to make sure if a user is authorized to edit the information on a resource (a POST method).
    Right now, it just returns a not authorized exception.
    """
    raise ProcessingException(description="Not Authorized", code=401)

# if the result does not exist or is not marked as visible, raise a not found exception
def post_get_single(result=None, **kw):
    """Don't allow a single record marked as not visible to be viewed."""
    if (result is None or not result['visable']):
        raise ProcessingException(description="Record not found", code=404)
    else:
        del result['visable']  # remove the visible entry because it will always be true

# if a given record in the list isn't visible, remove just that record
def post_get_many(result=None, search_params=None, **kw):
    """When listing multiple entries, don't allow non-visible entries to be seen."""
    entries = result['objects']
    for entry in list(entries):
        if not entry['visable']:
            entries.remove(entry)
        else:
            del entry['visable']  # remove the visible entry because it will always be true

    result['objects'] = entries

def init_api_manager(app, db):
    """
    This method starts the api manager and properly initializes all pre- and post- preprocessors

    Args:
        app: the current running context
        db: the database used in the current context
    """
    api_manager = APIManager(app, flask_sqlalchemy_db=db)
    api_manager.create_api(Resource,
                           methods=['GET', 'POST'],  # exclude_columns=['visable'],
                           preprocessors={
                           'POST': [pre_post]
                           },
                           postprocessors={
                           'GET_SINGLE': [post_get_single],
                           'GET_MANY': [post_get_many]
                           }
    )
    return api_manager