text:
require "google/cloud/translate/service"
require "google/cloud/translate/translation"
require "google/cloud/translate/detection"
require "google/cloud/translate/language"

module Google
  module Cloud
    module Translate
      ##
      # # Api
      #
      # Represents top-level access to the Google Translate API. Each instance
      # requires a public API access key. To create a key, follow the general
      # instructions at [Identifying your application to
      # Google](https://cloud.google.com/translate/v2/using_rest#auth), and the
      # specific instructions for [Server
      # keys](https://cloud.google.com/translate/v2/using_rest#creating-server-api-keys).
      # See {Google::Cloud#translate}.
      #
      # @see https://cloud.google.com/translate/v2/getting_started Translate API
      #   Getting Started
      #
      # @example
      #   require "google/cloud/translate"
      #
      #   translate = Google::Cloud::Translate.new
      #
      #   translation = translate.translate "Hello world!", to: "la"
      #
      #   translation.to_s #=> "Salve mundi!"
      #
      #   translation.from #=> "en"
      #   translation.origin #=> "Hello world!"
      #   translation.to #=> "la"
      #   translation.text #=> "Salve mundi!"
      #
      class Api
        ##
        # @private The Service object.
        attr_accessor :service

        ##
        # @private Creates a new Translate Api instance.
        #
        # See {Google::Cloud.translate}
        def initialize service
          @service = service
        end

        ##
        # Returns text translations from one language to another.
        #
        # @see https://cloud.google.com/translate/v2/using_rest#Translate
        #   Translate Text
        #
        # @param [String] text The text or texts to translate.
        # @param [String] to The target language into which the text should be
        #   translated. This is required. The value must be an [ISO
        #   639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
        #   language code.
        # @param [String] from The source language of the text or texts. This is
        #   an [ISO
        #   639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
        #   language code. This is optional.
        # @param [String] format The format of the text. Possible values include
        #   `:text` and `:html`. This is optional. The Translate API default is
        #   `:html`.
        # @param [String] cid The customization id for translate. This is
        #   optional.
        #
        # @return [Translation, Array<Translation>] A single {Translation}
        #   object if just one text was given, or an array of {Translation}
        #   objects if multiple texts were given.
        #
        # @example
        #   require "google/cloud/translate"
        #
        #   translate = Google::Cloud::Translate.new
        #
        #   translation = translate.translate "Hello world!", to: "la"
        #
        #   translation.to_s #=> "Salve mundi!"
        #
        #   translation.detected? #=> true
        #   translation.from #=> "en"
        #   translation.origin #=> "Hello world!"
        #   translation.to #=> "la"
        #   translation.text #=> "Salve mundi!"
        #
        # @example Setting the `from` language.
        #   require "google/cloud/translate"
        #
        #   translate = Google::Cloud::Translate.new
        #
        #   translation = translate.translate "Hello world!",
        #                                     from: :en, to: :la
        #   translation.detected? #=> false
        #   translation.text #=> "Salve mundi!"
        #
        # @example Retrieving multiple translations.
        #   require "google/cloud/translate"
        #
        #   translate = Google::Cloud::Translate.new
        #
        #   translations = translate.translate "Hello my friend.",
        #                                      "See you soon.",
        #                                      from: "en", to: "la"
        #   translations.count #=> 2
        #   translations[0].text #=> "Salve amice."
        #   translations[1].text #=> "Vide te mox."
        #
        # @example Preserving HTML tags.
        #   require "google/cloud/translate"
        #
        #   translate = Google::Cloud::Translate.new
        #
        #   translation = translate.translate "Hello world!",
        #                                     to: :la
        #   translation.text #=> "Salve mundi!"
        #
        def translate *text, to: nil, from: nil, format: nil, cid: nil
          return nil if text.empty?
          fail ArgumentError, "to is required" if to.nil?
          to = to.to_s
          from = from.to_s if from
          format = format.to_s if format
          text = Array(text).flatten
          gapi = service.translate text, to: to, from: from,
                                         format: format, cid: cid
          Translation.from_gapi_list gapi, text, to, from
        end

        ##
        # Detect the most likely language or languages of a text or multiple
        # texts.
        #
        # @see https://cloud.google.com/translate/v2/using_rest#detect-language
        #   Detect Language
        #
        # @param [String] text The text or texts upon which language detection
        #   should be performed.
        #
        # @return [Detection, Array<Detection>] A single {Detection} object if
        #   just one text was given, or an array of {Detection} objects if
        #   multiple texts were given.
        #
        # @example
        #   require "google/cloud/translate"
        #
        #   translate = Google::Cloud::Translate.new
        #
        #   detection = translate.detect "Hello world!"
        #   detection.language #=> "en"
        #   detection.confidence #=> 0.7100697
        #
        # @example Detecting multiple texts.
        #   require "google/cloud/translate"
        #
        #   translate = Google::Cloud::Translate.new
        #
        #   detections = translate.detect "Hello world!",
        #                                 "Bonjour le monde!"
        #   detections.count #=> 2
        #   detections.first.language #=> "en"
        #   detections.first.confidence #=> 0.7100697
        #   detections.last.language #=> "fr"
        #   detections.last.confidence #=> 0.40440267
        #
        def detect *text
          return nil if text.empty?
          text = Array(text).flatten
          gapi = service.detect(text)
          Detection.from_gapi gapi, text
        end

        ##
        # List the languages supported by the API. These are the languages to
        # and from which text can be translated.
        #
        # @see https://cloud.google.com/translate/v2/using_rest#supported-languages
        #   Discover Supported Languages
        #
        # @param [String] language The language and collation in which the names
        #   of the languages are returned. If this is `nil` then no names are
        #   returned.
        #
        # @return [Array<Language>] An array of {Language} objects supported by
        #   the API.
        #
        # @example
        #   require "google/cloud/translate"
        #
        #   translate = Google::Cloud::Translate.new
        #
        #   languages = translate.languages
        #   languages.count #=> 104
        #
        #   english = languages.detect { |l| l.code == "en" }
        #   english.name #=> nil
        #
        # @example Get all languages with their names in French.
        #   require "google/cloud/translate"
        #
        #   translate = Google::Cloud::Translate.new
        #
        #   languages = translate.languages "fr"
        #   languages.count #=> 104
        #
        #   english = languages.detect { |l| l.code == "en" }
        #   english.name #=> "Anglais"
        #
        def languages language = nil
          language = language.to_s if language
          gapi = service.languages language
          Array(gapi.languages).map { |g| Language.from_gapi g }
        end
      end
    end
  end
end


text:
<?php

namespace Mage\Runtime;

use Mage\Deploy\Strategy\ReleasesStrategy;
use Mage\Deploy\Strategy\RsyncStrategy;
use Mage\Deploy\Strategy\StrategyInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Symfony\Component\Process\Process;
use Mage\Runtime\Exception\RuntimeException;
use Mage\Task\AbstractTask;

/**
 * Runtime is a container of all run in time configuration, stages of progress, hosts being deployed, etc.
 *
 * @author Andrés Montañez <andresmontanez@gmail.com>
 */
class Runtime
{
    public const PRE_DEPLOY = 'pre-deploy';
    public const ON_DEPLOY = 'on-deploy';
    public const POST_DEPLOY = 'post-deploy';
    public const ON_RELEASE = 'on-release';
    public const POST_RELEASE = 'post-release';

    /**
     * @var array<string, mixed> Magallanes configuration
     */
    protected array $configuration = [];

    /**
     * @var string|null Environment being deployed
     */
    protected ?string $environment = null;

    /**
     * @var string|null Stage of Deployment
     */
    protected ?string $stage = null;

    /**
     * @var string|null The host being deployed to
     */
    protected ?string $workingHost = null;

    /**
     * @var string|null The Release ID
     */
    protected ?string $releaseId = null;

    /**
     * @var array<string, string> Hold a bag of variables for sharing information between tasks, if needed
     */
    protected $vars = [];

    protected ?LoggerInterface $logger = null;

    /**
     * @var bool Indicates if a Rollback operation is in progress
     */
    protected bool $rollback = false;

    public function isWindows(): bool
    {
        return stripos(PHP_OS, 'WIN') === 0;
    }

    public function hasPosix(): bool
    {
        return function_exists('posix_getpwuid');
    }

    /**
     * Generate the Release ID
     */
    public function generateReleaseId(): self
    {
        $this->setReleaseId(date('YmdHis'));
        return $this;
    }

    /**
     * Sets the Release ID
     */
    public function setReleaseId(string $releaseId): self
    {
        $this->releaseId = $releaseId;
        return $this;
    }

    /**
     * Retrieve the current Release ID
     */
    public function getReleaseId(): ?string
    {
        return $this->releaseId;
    }

    /**
     * Sets the Runtime in Rollback mode On or Off
     */
    public function setRollback(bool $inRollback): self
    {
        $this->rollback = $inRollback;
        return $this;
    }

    /**
     * Indicates if Runtime is in rollback
     */
    public function inRollback(): bool
    {
        return $this->rollback;
    }

    /**
     * Sets a value in the Vars bag
     */
    public function setVar(string $key, string $value): self
    {
        $this->vars[$key] = $value;
        return $this;
    }

    /**
     * Retrieve a value from the Vars bag, or a default (null) if not set
     */
    public function getVar(string $key, mixed $default = null): ?string
    {
        if (array_key_exists($key, $this->vars)) {
            return $this->vars[$key];
        }

        return $default;
    }

    /**
     * Sets the Logger instance
     */
    public function setLogger(?LoggerInterface $logger = null): self
    {
        $this->logger = $logger;
        return $this;
    }

    /**
     * Sets the Magallanes Configuration to the Runtime
     *
     * @param array<string, mixed> $configuration
     */
    public function setConfiguration(array $configuration): self
    {
        $this->configuration = $configuration;
        return $this;
    }

    /**
     * Retrieve the Configuration
     *
     * @return array<string, mixed> $configuration
     */
    public function getConfiguration(): array
    {
        return $this->configuration;
    }

    /**
     * Retrieves the Configuration Option for a specific section in the configuration
     */
    public function getConfigOption(string $key, mixed $default = null): mixed
    {
        if (array_key_exists($key, $this->configuration)) {
            return $this->configuration[$key];
        }

        return $default;
    }

    /**
     * Returns the Configuration Option for a specific section the current Environment
     */
    public function getEnvOption(string $key, mixed $default = null): mixed
    {
        if (
            !array_key_exists('environments', $this->configuration) ||
            !is_array($this->configuration['environments'])
        ) {
            return $default;
        }

        if (!array_key_exists($this->environment, $this->configuration['environments'])) {
            return $default;
        }

        if (array_key_exists($key, $this->configuration['environments'][$this->environment])) {
            return $this->configuration['environments'][$this->environment][$key];
        }

        return $default;
    }

    /**
     * Shortcut to get the the configuration option for a specific environment and merge it with
     * the global one (environment specific overrides the global one if present).
     *
     * @param array<string, mixed> $defaultEnv
     * @return array<string, mixed>
     */
    public function getMergedOption(string $key, array $defaultEnv = []): array
    {
        $userGlobalOptions = $this->getConfigOption($key, $defaultEnv);
        $userEnvOptions = $this->getEnvOption($key, $defaultEnv);

        return array_merge(
            (is_array($userGlobalOptions) ? $userGlobalOptions : []),
            (is_array($userEnvOptions) ? $userEnvOptions : [])
        );
    }

    /**
     * Overwrites an Environment Configuration Option
     */
    public function setEnvOption(string $key, mixed $value): self
    {
        if (array_key_exists('environments', $this->configuration) && is_array($this->configuration['environments'])) {
            if (array_key_exists($this->environment, $this->configuration['environments'])) {
                $this->configuration['environments'][$this->environment][$key] = $value;
            }
        }

        return $this;
    }

    /**
     * Sets the working Environment
     *
     * @throws RuntimeException
     */
    public function setEnvironment(string $environment): self
    {
        if (
            array_key_exists('environments', $this->configuration) &&
            array_key_exists($environment, $this->configuration['environments'])
        ) {
            $this->environment = $environment;
            return $this;
        }

        throw new RuntimeException(sprintf('The environment "%s" does not exists.', $environment), 100);
    }

    /**
     * Returns the current working Environment
     */
    public function getEnvironment(): ?string
    {
        return $this->environment;
    }

    /**
     * Sets the working stage
     */
    public function setStage(string $stage): self
    {
        $this->stage = $stage;
        return $this;
    }

    /**
     * Retrieve the current working Stage
     */
    public function getStage(): ?string
    {
        return $this->stage;
    }

    /**
     * Retrieve the defined Tasks for the current Environment and Stage
     *
     * @return string[]
     */
    public function getTasks(): array
    {
        if (
            !array_key_exists('environments', $this->configuration) ||
            !is_array($this->configuration['environments'])
        ) {
            return [];
        }

        if (!array_key_exists($this->environment, $this->configuration['environments'])) {
            return [];
        }

        if (array_key_exists($this->stage, $this->configuration['environments'][$this->environment])) {
            if (is_array($this->configuration['environments'][$this->environment][$this->stage])) {
                return $this->configuration['environments'][$this->environment][$this->stage];
            }
        }

        return [];
    }

    /**
     * Sets the working Host
     */
    public function setWorkingHost(?string $host): self
    {
        $this->workingHost = $host;
        return $this;
    }

    /**
     * Retrieve the working Host
     */
    public function getWorkingHost(): ?string
    {
        return $this->workingHost;
    }

    /**
     * Logs a Message into the Logger
     */
    public function log(string $message, string $level = LogLevel::DEBUG): void
    {
        if ($this->logger instanceof LoggerInterface) {
            $this->logger->log($level, $message);
        }
    }

    /**
     * Executes a command, it will be run Locally or Remotely based on the working Stage
     */
    public function runCommand(string $cmd, int $timeout = 120): Process
    {
        switch ($this->getStage()) {
            case self::ON_DEPLOY:
            case self::ON_RELEASE:
            case self::POST_RELEASE:
                return $this->runRemoteCommand($cmd, true, $timeout);
            default:
                return $this->runLocalCommand($cmd, $timeout);
        }
    }

    /**
     * Execute a command locally
     */
    public function runLocalCommand(string $cmd, int $timeout = 120): Process
    {
        $this->log($cmd, LogLevel::INFO);

        $process = Process::fromShellCommandline($cmd);
        $process->setTimeout($timeout);
        $process->run();

        $this->log($process->getOutput(), LogLevel::DEBUG);
        if (!$process->isSuccessful()) {
            $this->log($process->getErrorOutput(), LogLevel::ERROR);
        }

        return $process;
    }

    /**
     * Executes a command remotely, if jail is true, it will run inside the Host Path and the Release (if available)
     */
    public function runRemoteCommand(string $cmd, bool $jail, int $timeout = 120): Process
    {
        $user = $this->getEnvOption('user', $this->getCurrentUser());
        $sudo = $this->getEnvOption('sudo', false);
        $host = $this->getHostName();
        $sshConfig = $this->getSSHConfig();

        $cmdDelegate = $cmd;
        if ($sudo === true) {
            $cmdDelegate = sprintf('sudo %s', $cmd);
        }

        $hostPath = rtrim($this->getEnvOption('host_path'), '/');
        if ($jail && $this->getReleaseId() !== null) {
            $cmdDelegate = sprintf('cd %s/releases/%s && %s', $hostPath, $this->getReleaseId(), $cmdDelegate);
        } elseif ($jail) {
            $cmdDelegate = sprintf('cd %s && %s', $hostPath, $cmdDelegate);
        }

        $cmdRemote = str_replace('"', '\"', $cmdDelegate);
        $cmdLocal = sprintf(
            'ssh -p %d %s %s@%s "%s"',
            $sshConfig['port'],
            $sshConfig['flags'],
            $user,
            $host,
            $cmdRemote
        );

        return $this->runLocalCommand($cmdLocal, $timeout);
    }

    /**
     * Get the SSH configuration based on the environment
     *
     * @return array<string, string>
     */
    public function getSSHConfig(): array
    {
        $sshConfig = $this->getEnvOption(
            'ssh',
            [
                'port' => 22,
                'flags' => '-q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
            ]
        );

        if ($this->getHostPort() !== null) {
            $sshConfig['port'] = $this->getHostPort();
        }

        if (!array_key_exists('port', $sshConfig)) {
            $sshConfig['port'] = '22';
        }

        if (!array_key_exists('flags', $sshConfig)) {
            $sshConfig['flags'] = '-q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no';
        }

        if (!array_key_exists('timeout', $sshConfig)) {
            $sshConfig['timeout'] = 300;
        }

        return $sshConfig;
    }

    /**
     * Get the current Host Port or default ssh port
     */
    public function getHostPort(): ?int
    {
        $info = explode(':', strval($this->getWorkingHost()));
        return isset($info[1]) ? intval($info[1]) : null;
    }

    /**
     * Get the current Host Name
     */
    public function getHostName(): ?string
    {
        if (strpos(strval($this->getWorkingHost()), ':') === false) {
            return $this->getWorkingHost();
        }

        $info = explode(':', $this->getWorkingHost());
        return strval($info[0]);
    }

    /**
     * Gets a Temporal File name
     */
    public function getTempFile(): string
    {
        return tempnam(sys_get_temp_dir(), 'mage');
    }

    /**
     * Get the current user
     */
    public function getCurrentUser(): string
    {
        if ($this->hasPosix()) {
            $userData = posix_getpwuid(posix_geteuid());
            return $userData['name'];
        }

        // Windows fallback
        return strval(getenv('USERNAME'));
    }

    /**
     * Shortcut for getting Branch information
     *
     * @return bool|string
     */
    public function getBranch(): mixed
    {
        return $this->getEnvOption('branch', false);
    }

    /**
     * Shortcut for getting Tag information
     *
     * @return bool|string
     */
    public function getTag(): mixed
    {
        return $this->getEnvOption('tag', false);
    }

    /**
     * Guesses the Deploy Strategy to use
     */
    public function guessStrategy(): StrategyInterface
    {
        $strategy = new RsyncStrategy();

        if ($this->getEnvOption('releases', false)) {
            $strategy = new ReleasesStrategy();
        }

        $strategy->setRuntime($this);
        return $strategy;
    }
}

redpajama_set_name: RedPajamaGithub


text:
title:  Osamelý rodič
date:   20/05/2019
---

>

> Ja poznám svoje zámery, ktoré mám s vami – znie výrok Hospodina – sú to zámery pokoja, a nie nešťastia; dám vám budúcnosť a nádej.  (Jer 29,11)

Vo svete je veľmi častým fenoménom osamelý rodič, ktorým je väčšinou – ale nie výlučne – žena.

Niekedy máme tendenciu vnímať osamelého rodiča ako toho, kto splodil dieťa mimo manželský či dokonca partnerský zväzok. Často sú však veci oveľa komplikovanejšie. Hagar bola dotlačená k tomu, aby mala dieťa s Abrahámom, a potom bola nútená aj so svojím dieťaťom odísť (1Moj 16,3.4; 21,17). Batšebino tehotenstvo bolo v podstate následkom sexuálneho útoku mocného muža (2Sam 11,4.5). Eliáš bol poslaný do dediny Sarepta, aby pomohol matke, ktorá bola vdovou (1Kráľ 17,9). Skôr ako Ježiš začal svoju verejnú službu, jeho adoptívny otec Jozef už bol mŕtvy a zanechal Máriu ako vdovu a osamelého rodiča. "Smrť ju odlúčila od Jozefa, s ktorým sa delila o tajomstvo Ježišovho narodenia. Nemala nikoho, komu by sa mohla zveriť so svojimi nádejami a obavami. Posledné dva mesiace boli pre ňu veľmi tiesnivé." (TV 91; DA 145)

Byť slobodným rodičom je pravdepodobne najzložitejšia úloha, akú človek môže mať. Mnohí sú vystavení ťažkostiam v súvislosti s nedostatkom finančných prostriedkov, nezhodami s druhým rodičom (často bývalým partnerom, niekedy sú konflikty len pokračovaním komplikovanej situácie, ktorá viedla k rozvodu alebo k rozluke) alebo jednoducho majú nedostatok času sami na seba, na čas s Bohom a možno vo svojej samote prežívajú bolestnú túžbu nájsť si opäť niekoho, kto by ich miloval a kto by im bol oporou.

**Uvažuj o nasledovných textoch. Aké zasľúbenia a povzbudenia v nich môžeme nájsť – vrátane ľudí, ktorí zostali so svojimi deťmi sami?**

`Jer 31,25`

`Mat 11,28`

`Jer 29,11`

`Jer 32,27`

`Prísl 3,5.6`

`Iz 43,1.2`

Ako cirkev máme zodpovednosť pomáhať osamelým rodičom. Apoštol Jakub napísal: "Čistá a nepoškvrnená nábožnosť pred Bohom a Otcom je: navštevovať siroty a vdovy v ich tiesni a chrániť sa pred poškvrnou sveta." (Jak 1,27) Dalo by sa k tomu dodať: "a osamotených rodičov v ich problémoch tiež". Môžeme im ponúknuť oveľa viac než nejakú finančnú pomoc. Môžeme im na chvíľu povarovať deti, aby takýto osamotený rodič mal čas oddýchnuť si, zašportovať si, stráviť čas pri štúdiu Písma a podobne. Môžeme pomôcť s doučovaním ich detí alebo s opravou niečoho v dome alebo byte. Naozaj rôznymi spôsobmi sa môžeme stať nástrojom v Božích rukách na pomoc osamelým rodičom.

`Bez toho, aby sme osamelých rodičov posudzovali, odsudzovali alebo hľadali príčiny situácie, v ktorej sa ocitli, ako im môžeme byť povzbudením v ich neľahkej úlohe?`


text:
namespace Flepper.QueryBuilder
{
    /// <summary>
    /// Alias Operator Extensions
    /// </summary>
    public static class AliasOperatorExtensions
    {
        /// <summary>
        /// Add Where Operator to query
        /// </summary>
        /// <param name="aliasOperator">Alias Operator instance</param>
        /// <param name="field">Column Name</param>
        /// <returns></returns>
        public static IWhereFilter Where(this IAliasOperator aliasOperator, string field)
            => aliasOperator is IWhereFilter command ? command.Where(field) : null;

        /// <summary>
        /// Add Where Operator to query
        /// </summary>
        /// <param name="aliasOperator">Alias Operator instance</param>
        /// <param name="alias">Table Alias</param>
        /// <param name="field">Column Name</param>
        /// <returns></returns>
        public static IWhereFilter Where(this IAliasOperator aliasOperator, string alias, string field)
            => aliasOperator is IWhereFilter command ? command.Where(alias, field) : null;

        /// <summary>
        /// Add Inner Join Operator to query
        /// </summary>
        /// <param name="aliasOperator">Alias Operator instance</param>
        /// <param name="table">Column Name</param>
        /// <returns></returns>
        public static IJoin InnerJoin(this IAliasOperator aliasOperator, string table)
            => aliasOperator is IJoin command ? command.InnerJoin(table) : null;

        /// <summary>
        /// Add Left Join Operator to query
        /// </summary>
        /// <param name="aliasOperator">Alias Operator instance</param>
        /// <param name="table">Table Name</param>
        /// <returns></returns>
        public static IJoin LeftJoin(this IAliasOperator aliasOperator, string table)
            => aliasOperator is IJoin command ? command.LeftJoin(table) : null;

        /// <summary>
        /// Add On Operator to query
        /// </summary>
        /// <param name="aliasOperator">Alias Operator instance</param>
        /// <param name="tableAlias">Table Alias</param>
        /// <param name="column">Column Name</param>
        /// <returns></returns>
        public static IOnOperator On(this IAliasOperator aliasOperator, string tableAlias, string column)
            => aliasOperator is IOnOperator command ? command.On(tableAlias, column) : null;
    }
}


text:
# event-log

[![build status][1]][2] [![dependency status][3]][4]

<!-- [![browser support][5]][6] -->

An append only event log with streaming support

## Example

An event-log is currently coupled to mongo and backed by two
    collection. A capped real time collection of events and a
    historic collection.

You configure the event log with a time to live, this means that
    the event log will keep events in memory for that period of
    time. If you try to `read()` from the log for any events
    older then `Date.now() - timeToLive` it will not return them.

The event log is designed for real time events and should be used
    in combination with snapshots, i.e. you read the recent state
    from a concrete snapshot and merge in real time data from
    the event log on the fly, preferably in the browser.

```js
var eventLog = require("event-log")

/* get a mongoDB guy somehow */
var db = someMongoDb

db.createCollection("event-log.realtime", {
    capped: true
    , size: 100000
}, function (err, res) {
    /* ensure that the real time collection is capped */
    /* this allows us to use tailable cursors */
})

var realtimeCollection = db.collection("event-log.realtime")
var rawCollection = db.collection("event-log")

var log = eventLog(realtimeCollection, {
    timeToLive: 60 * 60 * 1000 /* HOUR */
    , rawCollection: rawCollection
})

/* each piece of data being added MUST have a timestamp */
log.add("event-type", {
    /* some data */
    timestamp: Date.now()
}, function (err, record) {
    // inserted data
})

/* infinite stream of data */
var stream = log.read(Date.now() - 1000)

stream.on("data", function (item) {
    /* item from event log */
})
```

## Installation

`npm install event-log`

## Contributors

 - Raynos

## MIT Licenced

  [1]: https://secure.travis-ci.org/Colingo/event-log.png
  [2]: http://travis-ci.org/Colingo/event-log
  [3]: https://david-dm.org/Colingo/event-log.png
  [4]: http://david-dm.org/Colingo/event-log
  [5]: http://ci.testling.com/Colingo/event-log.png
  [6]: http://ci.testling.com/Colingo/event-log


text:
package ocio

// #include "stdlib.h"
//
// #include "ocio.h"
//
import "C"

import (
	"runtime"
	"unsafe"
)

/* Processor */

type Processor struct {
	ptr C.ProcessorId
}

func newProcessor(p C.ProcessorId) *Processor {
	cfg := &Processor{p}
	runtime.SetFinalizer(cfg, deleteProcessor)
	return cfg
}

func deleteProcessor(p *Processor) {
	if p == nil {
		return
	}
	if p.ptr != nil {
		runtime.SetFinalizer(p, nil)
		C.deleteProcessor(p.ptr)
		p.ptr = nil
	}
	runtime.KeepAlive(p)
}

// Create a new empty Processor
func NewProcessor() *Processor {
	return newProcessor(C.Processor_Create())
}

func (p *Processor) lastError(errno ...error) error {
	if p == nil {
		return nil
	}
	err := getLastError(p.ptr, errno...)
	runtime.KeepAlive(p)
	return err
}

// Destroy immediately frees resources for this
// instance instead of waiting for garbage collection
// finalizer to run at some point later
func (p *Processor) Destroy() {
	deleteProcessor(p)
}

func (p *Processor) IsNoOp() bool {
	ret := bool(C.Processor_isNoOp(p.ptr))
	runtime.KeepAlive(p)
	return ret
}

// does the processor represent an image transformation that
// introduces crosstalk between the image channels
func (p *Processor) HasChannelCrosstalk() bool {
	ret := bool(C.Processor_hasChannelCrosstalk(p.ptr))
	runtime.KeepAlive(p)
	return ret
}

func (p *Processor) Metadata() *ProcessorMetadata {
	return newProcessorMetadata(C.Processor_getMetadata(p.ptr))
}

/* Processor CPU */

// Apply to an image.
func (p *Processor) Apply(i ImageDescriptor) error {
	_, err := C.Processor_apply(p.ptr, unsafe.Pointer(i.imageDescPtr()))
	err = p.lastError(err)
	runtime.KeepAlive(p)
	runtime.KeepAlive(i)
	return err
}

func (p *Processor) CpuCacheID() (string, error) {
	id, err := C.Processor_getCpuCacheID(p.ptr)
	if err = p.lastError(err); err != nil {
		return "", err
	}
	runtime.KeepAlive(p)
	return C.GoString(id), nil
}

// This class contains meta information about the process that generated this processor.
// The results of these functions do not impact the pixel processing.
type ProcessorMetadata struct {
	ptr C.ProcessorMetadataId
}

func newProcessorMetadata(p C.ProcessorMetadataId) *ProcessorMetadata {
	cfg := &ProcessorMetadata{p}
	runtime.SetFinalizer(cfg, deleteProcessorMetadata)
	return cfg
}

func deleteProcessorMetadata(c *ProcessorMetadata) {
	if c == nil {
		return
	}
	if c.ptr != 0 {
		runtime.SetFinalizer(c, nil)
		C.deleteProcessorMetadata(c.ptr)
		c.ptr = 0
	}
	runtime.KeepAlive(c)
}

// Create a new empty ProcessorMetadata
func NewProcessorMetadata() *ProcessorMetadata {
	return newProcessorMetadata(C.ProcessorMetadata_Create())
}

// Destroy immediately frees resources for this
// instance instead of waiting for garbage collection
// finalizer to run at some point later
func (p *ProcessorMetadata) Destroy() {
	deleteProcessorMetadata(p)
}

func (p *ProcessorMetadata) NumFiles() int {
	ret := int(C.ProcessorMetadata_getNumFiles(p.ptr))
	runtime.KeepAlive(p)
	return ret
}

func (p *ProcessorMetadata) File(index int) string {
	ret := C.GoString(C.ProcessorMetadata_getFile(p.ptr, C.int(index)))
	runtime.KeepAlive(p)
	return ret
}

// Files is a helper to return a slice of the file paths,
// using NumFiles and File(index)
func (p *ProcessorMetadata) Files() []string {
	num := p.NumFiles()
	files := make([]string, 0, num)
	for i := 0; i < num; i++ {
		files = append(files, p.File(i))
	}
	return files
}

func (p *ProcessorMetadata) NumLooks() int {
	ret := int(C.ProcessorMetadata_getNumLooks(p.ptr))
	runtime.KeepAlive(p)
	return ret
}

func (p *ProcessorMetadata) Look(index int) string {
	ret := C.GoString(C.ProcessorMetadata_getLook(p.ptr, C.int(index)))
	runtime.KeepAlive(p)
	return ret
}

func (p *ProcessorMetadata) AddFile(fileName string) {
	c_str := C.CString(fileName)
	defer C.free(unsafe.Pointer(c_str))

	C.ProcessorMetadata_addFile(p.ptr, c_str)
	runtime.KeepAlive(p)
}

func (p *ProcessorMetadata) AddLook(lookName string) {
	c_str := C.CString(lookName)
	defer C.free(unsafe.Pointer(c_str))

	C.ProcessorMetadata_addLook(p.ptr, c_str)
	runtime.KeepAlive(p)
}

/* ImageDesc */

// A ColorData meant to hold floating point pixel data in forms:
// * RGBRGB...
// * RGBARGBA...
type ColorData []float32

type ImageDescriptor interface {
	imageDescPtr() unsafe.Pointer
}

// This is a light-weight wrapper around an image, that provides a context for pixel access
type PackedImageDesc struct {
	ptr  unsafe.Pointer
	data ColorData
}

func newPackedImageDesc(p unsafe.Pointer, data ColorData) *PackedImageDesc {
	i := &PackedImageDesc{p, data}
	runtime.SetFinalizer(i, deletePackedImageDesc)
	return i
}

func deletePackedImageDesc(p *PackedImageDesc) {
	if p == nil {
		return
	}
	if p.ptr != nil {
		runtime.SetFinalizer(p, nil)
		C.deletePackedImageDesc(p.ptr)
		p.ptr = nil
	}
	runtime.KeepAlive(p)
}

// Create a PackedImageDesc wrapper for some raw rgb data
// Pass a []float32 slice of image data: rgbrgbrgb, etc.
// The number of channels must be greater than or equal to 3 If a 4th channel is specified,
// it is assumed to be alpha information. Channels > 4 will be ignored.
func NewPackedImageDesc(rgb ColorData, width, height, numChannels int) *PackedImageDesc {
	ptr := C.PackedImageDesc_Create((*C.float)(&rgb[0]), C.long(width), C.long(height), C.long(numChannels))
	return newPackedImageDesc(ptr, rgb)
}

// Destroy immediately frees resources for this
// instance instead of waiting for garbage collection
// finalizer to run at some point later
func (p *PackedImageDesc) Destroy() {
	deletePackedImageDesc(p)
}

// Return the current state of the image data,
// potentially modified if color transformations
// have been applied.
func (p *PackedImageDesc) Data() ColorData {
	return p.data
}

// Pixel width of the image
func (p *PackedImageDesc) Width() int {
	ret := int(C.PackedImageDesc_getWidth(p.ptr))
	runtime.KeepAlive(p)
	return ret
}

// Pixel height of the image
func (p *PackedImageDesc) Height() int {
	ret := int(C.PackedImageDesc_getHeight(p.ptr))
	runtime.KeepAlive(p)
	return ret
}

// Number of color channels in the image
func (p *PackedImageDesc) NumChannels() int {
	ret := int(C.PackedImageDesc_getNumChannels(p.ptr))
	runtime.KeepAlive(p)
	return ret
}

func (p *PackedImageDesc) imageDescPtr() unsafe.Pointer {
	return p.ptr
}


text:
package org.jbpm.formModeler.core.processing.impl.model;

public class Hobby {

    private String name;

    private Integer level;

    public Hobby() {
    }

    public Hobby(String name,
                 Integer level) {
        this.name = name;
        this.level = level;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getLevel() {
        return level;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Hobby hobby = (Hobby) o;

        if (name != null ? !name.equals(hobby.name) : hobby.name != null) {
            return false;
        }
        return level != null ? level.equals(hobby.level) : hobby.level == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (level != null ? level.hashCode() : 0);
        return result;
    }

    public void setLevel(Integer level) {
        this.level = level;
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView android:id="@+id/imageViewAvatar"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:layout_marginRight="?android:attr/listPreferredItemPaddingRight"
        android:src="@drawable/ic_account_circle_black_24dp"
        android:scaleType="fitCenter"
        android:tint="@color/colorPrimaryDark" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#FFF">

        <TextView android:id="@+id/textViewListItem"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#222"
            android:gravity="center_vertical"
            android:padding="@dimen/activity_vertical_margin"
            android:minHeight="?android:attr/listPreferredItemHeightSmall"
            android:text="Text message" />
    </LinearLayout>
</LinearLayout>


text:
import re

from ..parser import Parser
from ..parser import ParsedResult
from ..parser import ParsedComponent

from datetime import datetime
from util import month_index
from util import date_exist
from util import find_closest_year

class ENMonthNameLittleEndianParser(Parser):

    def pattern(self):
        return '(\W|^)((Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s*,?\s*)?([0-9]{1,2})(st|nd|rd|th)?(\s*(to|\-|\s)\s*([0-9]{1,2})(st|nd|rd|th)?)?\s*(January|Jan|February|Feb|March|Mar|April|Apr|May|June|Jun|July|Jul|August|Aug|September|Sep|October|Oct|November|Nov|December|Dec)((\s*[0-9]{2,4})(\s*BE)?)?(\W|$)'

    def extract(self, text, ref_date, match, options):

        text = match.group(0)
        text = text[len(match.groups()[0]):len(text) - len(match.groups()[-1])]

        month = month_index(match.group(10))
        day   = int(match.group(4))

        year = None
        if match.group(11):
            year = int(match.group(12))

            if year < 100:
                year = year + 2000
            elif match.group(13):
                year = year - 543

        result = ParsedResult()
        result.index = match.start() + len(match.groups()[0])
        result.text  = text
        result.start = ParsedComponent(month=month, day=day)

        if year:
            if not date_exist(year, month, day): return None
            result.start.assign('year', year)
        else:
            year = find_closest_year(ref_date=ref_date, month=month, day=day)
            if year is None: return None

            result.start.imply('year', year)

        if match.group(8):
            endDay = int(match.group(8))
            result.end = ParsedComponent(year=year, month=month, day=endDay)

        return result


text:
/********************************************************************
*
*	08. HOW MANY WIDGETS?
*
*       The Yukon Widget Company manufactures widgets that weigh 12.5
*       pounds each. Write a program that calculates how many widgets
*       are stacked on a pallet, based on the total weight of the
*       pallet. The program should ask the user how much the pallet
*       weighs by itself and with the widgets stacked on it. It
*       should then calculate and display the number of widgets
*       stacked on the pallet.
*
* 	Jesus Hilario Hernandez
* 	January 7th 2017
*
********************************************************************/
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    const float INDIVIDUAL_WIDGET_WEIGHT = 12.5; // Widget weight.
    float pallet_weight,
          pallet_with_widgets,
          widget_weight,
          number_of_widgets;

    // Ask user how much the pallet weighs by itself
    cout << endl;
    cout << "How much does the pallet weigh by itself? ";
    cin >> pallet_weight;

    // Ask user how much the pallet weighs with widget stacked on
    cout << "How much does the pallet weigh with widgets? ";
    cin >> pallet_with_widgets;

    /**
     *   Calculate how many widgets are stacked on a pallet,
     *  based on the total weight of the pallet.
     */
    widget_weight = pallet_with_widgets - pallet_weight;

    number_of_widgets = widget_weight / INDIVIDUAL_WIDGET_WEIGHT;

    // Display the number of widgets stacked on the pallet.
    cout << setprecision(2) << fixed << right << endl;
    cout << "Individual widget weight   = " << setw(6) << INDIVIDUAL_WIDGET_WEIGHT << endl;
    cout << "Pallet weight              = " << setw(6) << pallet_weight << endl;
    cout << "Pallet weight with widgets = " << setw(6) << pallet_with_widgets << endl;
    cout << "Widget weight              = " << setw(6) << widget_weight << endl;
    cout << "Number of widgets          = " << setw(6) << number_of_widgets << endl;
    cout << endl;

    // Terminate program
    return 0;
}


text:
package com.kaissersoft.minesweepergame.ui.widgets;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;

/**
 * Created by eefret on 21/04/15.
 */
public class TileButton extends Button{

    public TileButton(Context context) {
        super(context);
    }

    public TileButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TileButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec); // This is the key that will make the height equivalent to its width
    }
}


text:
package retrofit2.adapter.rxjava3;

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

import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.CompletableObserver;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.exceptions.CompositeException;
import io.reactivex.rxjava3.exceptions.Exceptions;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
import java.util.concurrent.atomic.AtomicReference;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import retrofit2.Retrofit;
import retrofit2.http.GET;

public final class CompletableThrowingTest {
  @Rule public final MockWebServer server = new MockWebServer();
  @Rule public final TestRule resetRule = new RxJavaPluginsResetRule();

  @Rule
  public final RecordingCompletableObserver.Rule observerRule =
      new RecordingCompletableObserver.Rule();

  interface Service {
    @GET("/")
    Completable completable();
  }

  private Service service;

  @Before
  public void setUp() {
    Retrofit retrofit =
        new Retrofit.Builder()
            .baseUrl(server.url("/"))
            .addCallAdapterFactory(RxJava3CallAdapterFactory.createSynchronous())
            .build();
    service = retrofit.create(Service.class);
  }

  @Test
  public void throwingInOnCompleteDeliveredToPlugin() {
    server.enqueue(new MockResponse());

    final AtomicReference<Throwable> errorRef = new AtomicReference<>();
    RxJavaPlugins.setErrorHandler(
        throwable -> {
          if (!errorRef.compareAndSet(null, throwable)) {
            throw Exceptions.propagate(throwable); // Don't swallow secondary errors!
          }
        });

    RecordingCompletableObserver observer = observerRule.create();
    final RuntimeException e = new RuntimeException();
    service
        .completable()
        .subscribe(
            new ForwardingCompletableObserver(observer) {
              @Override
              public void onComplete() {
                throw e;
              }
            });

    assertThat(errorRef.get().getCause()).isSameAs(e);
  }

  @Test
  public void bodyThrowingInOnErrorDeliveredToPlugin() {
    server.enqueue(new MockResponse().setResponseCode(404));

    final AtomicReference<Throwable> pluginRef = new AtomicReference<>();
    RxJavaPlugins.setErrorHandler(
        throwable -> {
          if (!pluginRef.compareAndSet(null, throwable)) {
            throw Exceptions.propagate(throwable); // Don't swallow secondary errors!
          }
        });

    RecordingCompletableObserver observer = observerRule.create();
    final RuntimeException e = new RuntimeException();
    final AtomicReference<Throwable> errorRef = new AtomicReference<>();
    service
        .completable()
        .subscribe(
            new ForwardingCompletableObserver(observer) {
              @Override
              public void onError(Throwable throwable) {
                errorRef.set(throwable);
                throw e;
              }
            });

    //noinspection ThrowableResultOfMethodCallIgnored
    CompositeException composite = (CompositeException) pluginRef.get();
    assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
  }

  abstract static class ForwardingCompletableObserver implements CompletableObserver {
    private final CompletableObserver delegate;

    ForwardingCompletableObserver(CompletableObserver delegate) {
      this.delegate = delegate;
    }

    @Override
    public void onSubscribe(Disposable disposable) {
      delegate.onSubscribe(disposable);
    }

    @Override
    public void onComplete() {
      delegate.onComplete();
    }

    @Override
    public void onError(Throwable throwable) {
      delegate.onError(throwable);
    }
  }
}


text:
/*
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

   - Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
   OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

static OPUS_INLINE void deb2_impl(unsigned char *_t,unsigned char **_p,int _k,int _x,int _y)
{
  int i;
  if(_x>2){
     if(_y<3)for(i=0;i<_y;i++)*(--*_p)=_t[i+1];
  }else{
     _t[_x]=_t[_x-_y];
     deb2_impl(_t,_p,_k,_x+1,_y);
     for(i=_t[_x-_y]+1;i<_k;i++){
       _t[_x]=i;
       deb2_impl(_t,_p,_k,_x+1,_x);
     }
  }
}

/*Generates a De Bruijn sequence (k,2) with length k^2*/
static OPUS_INLINE void debruijn2(int _k, unsigned char *_res)
{
   unsigned char *p;
   unsigned char *t;
   t=malloc(sizeof(unsigned char)*_k*2);
   memset(t,0,sizeof(unsigned char)*_k*2);
   p=&_res[_k*_k];
   deb2_impl(t,&p,_k,1,1);
   free(t);
}

/*MWC RNG of George Marsaglia*/
static opus_uint32 Rz, Rw;
static OPUS_INLINE opus_uint32 fast_rand(void)
{
  Rz=36969*(Rz&65535)+(Rz>>16);
  Rw=18000*(Rw&65535)+(Rw>>16);
  return (Rz<<16)+Rw;
}
static opus_uint32 iseed;

#ifdef __GNUC__
__attribute__((noreturn))
#elif defined(_MSC_VER)
__declspec(noreturn)
#endif
static OPUS_INLINE void _test_failed(const char *file, int line)
{
  fprintf(stderr,"\n ***************************************************\n");
  fprintf(stderr," ***         A fatal error was detected.         ***\n");
  fprintf(stderr," ***************************************************\n");
  fprintf(stderr,"Please report this failure and include\n");
  fprintf(stderr,"'make check SEED=%u fails %s at line %d for %s'\n",iseed,file,line,opus_get_version_string());
  fprintf(stderr,"and any relevant details about your system.\n\n");
  abort();
}
#define test_failed() _test_failed(__FILE__, __LINE__);

void regression_test(void);


text:
class GURL;

namespace net {
class ClientCertStore;
class HostResolver;
class KeygenHandler;
class URLRequestContext;
}

namespace content {

class AppCacheService;

// ResourceContext contains the relevant context information required for
// resource loading. It lives on the IO thread, although it is constructed on
// the UI thread. It must be destructed on the IO thread.
class CONTENT_EXPORT ResourceContext : public base::SupportsUserData {
 public:
#if defined(OS_IOS)
  virtual ~ResourceContext() {}
#else
  ResourceContext();
  virtual ~ResourceContext();
#endif
  virtual net::HostResolver* GetHostResolver() = 0;

  // DEPRECATED: This is no longer a valid given isolated apps/sites and
  // storage partitioning. This getter returns the default context associated
  // with a BrowsingContext.
  virtual net::URLRequestContext* GetRequestContext() = 0;

  // Get platform ClientCertStore. May return NULL.
  virtual scoped_ptr<net::ClientCertStore> CreateClientCertStore();

  // Create a platform KeygenHandler and pass it to |callback|. The |callback|
  // may be run synchronously.
  virtual void CreateKeygenHandler(
      uint32 key_size_in_bits,
      const std::string& challenge_string,
      const GURL& url,
      const base::Callback<void(scoped_ptr<net::KeygenHandler>)>& callback);

  // Returns true if microphone access is allowed for |origin|. Used to
  // determine what level of authorization is given to |origin| to access
  // resource metadata.
  virtual bool AllowMicAccess(const GURL& origin) = 0;

  // Returns true if web camera access is allowed for |origin|. Used to
  // determine what level of authorization is given to |origin| to access
  // resource metadata.
  virtual bool AllowCameraAccess(const GURL& origin) = 0;

  // Returns a callback that can be invoked to get a random salt
  // string that is used for creating media device IDs.  The salt
  // should be stored in the current user profile and should be reset
  // if cookies are cleared. The default is an empty string.
  //
  // It is safe to hold on to the callback returned and use it without
  // regard to the lifetime of ResourceContext, although in general
  // you should not use it long after the profile has been destroyed.
  //
  // TODO(joi): We don't think it should be unnecessary to use this
  // after ResourceContext goes away. There is likely an underying bug
  // in the lifetime of ProfileIOData vs. ResourceProcessHost, where
  // sometimes ProfileIOData has gone away before RPH has finished
  // being torn down (on the IO thread). The current interface that
  // allows using the salt object after ResourceContext has gone away
  // was put in place to fix http://crbug.com/341211 but I intend to
  // try to figure out how the lifetime should be fixed properly. The
  // original interface was just a method that returns a string.
  //
  // TODO(perkj): Make this method pure virtual when crbug/315022 is
  // fixed.
  typedef base::Callback<std::string()> SaltCallback;
  virtual SaltCallback GetMediaDeviceIDSalt();
};

}  // namespace content

#endif  // CONTENT_PUBLIC_BROWSER_RESOURCE_CONTEXT_H_


text:
from anki.importing.anki2 import Importer
from anki.utils import splitFields, joinFields
from anki.lang import ngettext
from parser import Tree

# TODO fix error message spacing
# TODO options file

class DirectoryImporter(Importer):

    def handle_models(self, notes, new = False):
        col = self.col
        for note in notes:
            model = note["ffsModel"]
            m = None
            if new:
                m = col.models.new(model["name"])
            else:
                m = col.models.byName(model["name"])
                if not m:
                    raise ValueError("Expected model to exist")
            if "latexPre" in model:
                m["latexPre"] = model["latexPre"]
            if "latexPost" in model:
                m["latexPost"] = model["latexPost"]
            if "css" in model:
                m["css"] = model["css"]

            if "fields" not in model:
                raise ValueError("Model file requires fields key")
            fields = ["Filename"]
            fields.extend(model["fields"].split())
            field_map = col.models.fieldMap(m)
            field_names = col.models.fieldNames(m)
            for i in range(len(fields)):
                if i < len(field_names):
                    name = field_names[i]
                    field = field_map[name][1]
                    if name != fields[i]:
                        col.models.renameField(m, field, fields[i])
                else:
                    field = col.models.newField(fields[i])
                    col.models.addField(m, field)
            if len(fields) < len(field_names):
                for i in range(len(fields), len(field_names)):
                    name = field_names[i]
                    field = field_map[name][1]
                    col.models.remField(m, field)

            if "templates" not in model:
                raise ValueError("Model file requires templates key")
            ts = model["templates"].split()
            for name in ts:
                found = False
                for template in m["tmpls"]:
                    if template["name"] == name:
                        found = True
                        if name+" qfmt" in model:
                            template["qfmt"] = model[name+" qfmt"]
                        else:
                            template["qfmt"] = "{{Front}}"
                        if name+" afmt" in model:
                            template["afmt"] = model[name+" afmt"]
                        else:
                            template["afmt"] = "{{Back}}"
                        if name+" bqfmt" in model:
                            template["bqfmt"] = model[name+" bqfmt"]
                        if name+" bafmt" in model:
                            template["bafmt"] = model[name+" bafmt"]
                if not found:
                    template = col.models.newTemplate(name)
                    if name+" qfmt" in model:
                        template["qfmt"] = model[name+" qfmt"]
                    else:
                        template["qfmt"] = "{{Front}}"
                    if name+" afmt" in model:
                        template["afmt"] = model[name+" afmt"]
                    else:
                        template["afmt"] = "{{Back}}"
                    if name+" bqfmt" in model:
                        template["bqfmt"] = model[name+" bqfmt"]
                    if name+" bafmt" in model:
                        template["bafmt"] = model[name+" bafmt"]
                    col.models.addTemplate(m, template)
            col.genCards(col.findNotes("*"))
            for template in m["tmpls"]:
                if template["name"] not in ts:
                    col.models.remTemplate(m, template)

            note["ffsModel"]["id"] = m["id"]
            if new:
                col.models.add(m)
            # Sanity check our note
            for field in col.models.fieldNames(m):
                if field not in note:
                    raise ValueError("Note missing model field, \
                        in file: {0}".format(note["Filename"]))

    def run(self):

        tree = Tree(self.file[:-4])
        queue = tree.parse()
        deck_name = tree.name

        col = self.col
        # Setup a deck
        deck = col.decks.id(deck_name)
        col.decks.select(deck)

        # Make new models
        new_models = []
        old_models = []
        old_model_ids = []
        for note in queue:
            m = col.models.byName(note["ffsModel"]["name"])
            if not m:
                unique = True
                for n in new_models:
                    if note["ffsModel"]["name"] == n["ffsModel"]["name"]:
                        unique = False
                        break
                if unique:
                    new_models.append(note)
            else:
                unique = True
                for n in old_models:
                    if note["ffsModel"]["name"] == n["ffsModel"]["name"]:
                        unique = False
                        break
                if unique:
                    old_models.append(note)
                note["ffsModel"]["id"] = m["id"]
        self.handle_models(new_models, True)

        # Check for updates
        nids = []
        nids_decks = {}
        update = []
        update_nids = []
        add = []
        delete = []
        tags_to_register = ["ffsi:added", "ffsi:changed", "ffsi:owned"]
        addedc = 0
        changedc = 0
        deletedc = 0
        for note in col.db.execute("select * from notes"):
            note = list(note)
            match = None
            deletable = False
            m = col.models.get(note[2])
            tags = col.tags.split(note[5])
            field_map = col.models.fieldMap(m)
            fields = splitFields(note[6])
            if "Filename" not in field_map:
                if col.tags.inList("ffsi:owned", tags):
                    raise ValueError("ffs owned note tampered with.")
                continue
            filename = fields[field_map["Filename"][0]]

            deck_check = filename.split('/')[0]
            if col.tags.inList("ffsi:owned", tags) \
                    and deck_name == deck_check:
                deletable = True
            for n in queue:
                om = col.models.byName(n["ffsModel"]["name"])
                if n["Filename"] == filename:
                    flds = []
                    changed = False
                    if "fields" in n["ffsModel"]:
                        flds.append(n["Filename"])
                        for field in n["ffsModel"]["fields"].split():
                            if field not in n:
                                raise ValueError("Note missing model field," +
                                    " in file: {0}".format(n["Filename"]))
                            flds.append(n[field])
                    else:
                        for field in col.models.fieldNames(om):
                            flds.append(n[field])
                    if int(note[2]) != int(om["id"]):
                        changed = True
                        old_model_ids.append(note[2])
                        note[2] = int(om["id"])
                    if note[6] != joinFields(flds):
                        changed = True
                        note[6] = joinFields(flds)

                    new_tags = col.tags.addToStr("ffsi:owned", "")
                    note[5] = col.tags.remFromStr("ffsi:added", note[5])
                    note[5] = col.tags.remFromStr("ffsi:changed", note[5])
                    if "tags" in n:
                        for t in n["tags"].split():
                            new_tags = col.tags.addToStr(t, new_tags)
                        tags_to_register.extend(col.tags.split(new_tags))
                    else:
                        new_tags = note[5]
                    if note[5] != new_tags:
                        changed = True

                    if changed:
                        new_tags = col.tags.addToStr("ffsi:changed", new_tags)
                        changedc = changedc + 1
                    note[5] = new_tags
                    update.append(note)
                    update_nids.append(note[0])
                    match = n
            if match:
                queue.remove(match)
            elif deletable:
                delete.append(note[0])
                deletedc = deletedc + 1

        self.handle_models(old_models)

        for note in queue:
            add.append(note)

        col.remNotes(delete)
        col.db.executemany(
            "insert or replace into notes values (?,?,?,?,?,?,?,?,?,?,?)",
            update)
        col.genCards(update_nids)
        col.updateFieldCache(update_nids)
        col.tags.registerNotes(update_nids)

        for textfile in add:
            m = col.models.byName(textfile["ffsModel"]["name"])
            col.models.setCurrent(m)
            note = col.newNote()

            new_tags = ["ffsi:owned", "ffsi:added"]
            if "tags" in textfile:
                custom_tags = textfile["tags"].split()
                new_tags.extend(custom_tags)
                tags_to_register.extend(custom_tags)
            [note.addTag(tag) for tag in list(set(new_tags))]

            fields = col.models.fieldNames(m)
            for field in fields:
                note[field] = textfile[field]
            col.addNote(note)
            nids.append(note.id)
            nids_decks[note.id] = textfile["ffsDeckname"]
            addedc = addedc + 1
        col.genCards(nids)

        added_cards = []
        for card in col.db.execute("select * from cards"):
            card = list(card)
            if card[1] in nids:
                added_cards.append(card)
        totalc = addedc + changedc + deletedc
        self.log.append(
            ngettext(
                "{0} card changed, " +
                "({1}, {2}, {3}) note (added, changed, or deleted).",
                "{0} cards changed. " +
                "({1}, {2}, {3}) notes (added, changed, or deleted).",
                totalc).format(len(added_cards), addedc, changedc, deletedc))
        # TODO improve this loop
        for card in added_cards:
            deck_name = nids_decks[card[1]]
            deck = col.decks.id(deck_name)
            col.decks.setDeck([card[0]], deck)

        # Set the default model to something standard
        basic = col.models.byName("Basic")
        if basic:
            col.models.setCurrent(basic)

        # Register all of our tags
        col.tags.register(list(set(tags_to_register)))

        # Cleanup empty decks
        children_decks = col.decks.children(deck)
        for child in children_decks:
            cids = col.decks.cids(child[1], True)
            if len(cids) == 0:
                col.decks.rem(child[1])

        # Cleanup models
        for note in old_models:
            m = col.models.byName(note["ffsModel"]["name"])
            if m:
                nids = col.models.nids(m)
                if len(nids) == 0:
                    col.models.rem(m)
        for i in old_model_ids:
            m = col.models.get(i)
            if m:
                nids = col.models.nids(m)
                if len(nids) == 0:
                    col.models.rem(m)

        col.conf['nextPos'] = col.db.scalar(
            "select max(due)+1 from cards where type = 0") or 0
        col.save()
        col.db.execute("vacuum")
        col.db.execute("analyze")
        col.fixIntegrity()


text:
static Window *window;
static TextLayer *text_layer;
static int current_guess;
static char message[50];
static int range[2];
static int temp_range[2];
static enum game_state state;

enum game_state { initial, guess_started, guessed };

static void generate_range() {
  range[0] = rand() % 30;
  range[1] = rand() % 51 + 50;
  temp_range[0] = range[0];
  temp_range[1] = range[1];
}

static void show_central_message(char *message) {
  text_layer_set_text(text_layer, message);
}

static void init_the_game() {
  generate_range();
  state = initial;

  snprintf(message, sizeof(message), "Make up a number\n\r between %d and %d", range[0], range[1]);
  show_central_message(message);

}

static void suggest_guess(bool random) {
  if (temp_range[1] - temp_range[0] < 2) {
    temp_range[0] = range[0];
    temp_range[1] = range[1];
  }

  current_guess = random
    ? rand() % (temp_range[1] - temp_range[0] - 1) + temp_range[0] + 1
    : (temp_range[1] - temp_range[0]) / 2 + temp_range[0];

  snprintf(message, sizeof(message), "Is it %d?", current_guess);
  show_central_message(message);
}

static void start_to_guess() {
  suggest_guess(true);
  state = guess_started;
}

static void set_guessed() {
  snprintf(message, sizeof(message), "Hurray!\n\rIt is %d", current_guess);
  show_central_message(message);
  state = guessed;
}

static void select_click_handler(ClickRecognizerRef recognizer, void *context) {
  switch (state) {
    case initial:
      start_to_guess();
      break;
    case guess_started:
      set_guessed();
      break;
    case guessed:
      init_the_game();
      break;
  }
}

static void adjust_search_range(bool is_less) {
    temp_range[is_less ? 1 : 0] = current_guess;
    suggest_guess(false);
}

static void up_click_handler(ClickRecognizerRef recognizer, void *context) {
  if (state == guess_started) {
    adjust_search_range(false);
  }
}

static void down_click_handler(ClickRecognizerRef recognizer, void *context) {
if (state == guess_started) {
    adjust_search_range(true);
  }
}

static void click_config_provider(void *context) {
  window_single_click_subscribe(BUTTON_ID_UP, up_click_handler);
  window_single_click_subscribe(BUTTON_ID_SELECT, select_click_handler);
  window_single_click_subscribe(BUTTON_ID_DOWN, down_click_handler);
}

static void main_window_load(Window *window) {
  Layer *window_layer = window_get_root_layer(window);
  GRect bounds = layer_get_bounds(window_layer);

  text_layer = text_layer_create(
      GRect(0, PBL_IF_ROUND_ELSE(58, 52), bounds.size.w, 50));

  text_layer_set_background_color(text_layer, GColorClear);
  text_layer_set_text_color(text_layer, GColorWhite);
  //text_layer_set_font(text_layer, fonts_get_system_font(FONT_KEY_BITHAM_42_BOLD));
  text_layer_set_text_alignment(text_layer, GTextAlignmentCenter);

  layer_add_child(window_layer, text_layer_get_layer(text_layer));

  srand((unsigned) time(NULL));

  init_the_game();
}

static void main_window_unload(Window *window) {
  text_layer_destroy(text_layer);
}

void init () {
  window = window_create();

  window_set_click_config_provider(window, click_config_provider);

  window_set_window_handlers(window, (WindowHandlers) {
    .load = main_window_load,
    .unload = main_window_unload
  });

  window_set_background_color(window, GColorBlack);

  window_stack_push(window, true);
}

void deinit() {
  window_destroy(window);
}

int main() {
  init();
  app_event_loop();
  deinit();
  return 0;
}


text:
<?php

namespace Tomloprod\IonicApi\Api;

use Tomloprod\IonicApi\Exception\RequestException;

/**
 * Class Request
 *
 * @package Tomloprod\IonicApi\Api
 * @author Tomás L.R (@tomloprod)
 * @author Ramon Carreras (@ramoncarreras)
 */
class Request
{
    // Available HTTP methods
    const METHOD_GET = 'GET';
    const METHOD_POST = 'POST';
    const METHOD_PUT = 'PUT';
    const METHOD_PATCH = 'PATCH';
    const METHOD_DELETE = 'DELETE';

    // API URL
    private static $ionicBaseURL = 'https://api.ionic.io';

    // cURL
    public $timeout = 5; // Set timeout to 0 is inadvisable in a production environment
    public $connectTimeout = 5; // Set timeout to 0 is inadvisable in a production environment
    public $sslVerifyPeer = 0;

    // Required for Authorization
    private $ionicProfile;
    private $ionicAPIToken;

    /**
     * Request constructor.
     *
     * @param string $ionicProfile
     * @param string $ionicAPIToken
     */
    public function __construct($ionicProfile, $ionicAPIToken)
    {
        $this->ionicProfile = $ionicProfile;
        $this->ionicAPIToken = $ionicAPIToken;
    }

    /**
     * Send requests to the Ionic Push API.
     *
     * INFO: https://docs.ionic.io/api/http.html#response-structure
     *
     * @param string $method
     * @param string $endPoint
     * @param string $data
     * @throws RequestException
     * @return object
     */
    public function sendRequest($method, $endPoint, $data = '')
    {
        $data = json_encode($data);

        $headers = [
            'Authorization: Bearer ' . $this->ionicAPIToken,
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data),
        ];

        $curlHandler = curl_init();

        curl_setopt($curlHandler, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
        curl_setopt($curlHandler, CURLOPT_TIMEOUT, $this->timeout);
        curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curlHandler, CURLOPT_SSL_VERIFYPEER, $this->sslVerifyPeer);
        curl_setopt($curlHandler, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curlHandler, CURLOPT_HEADER, false);

        switch ($method) {
            case self::METHOD_POST:
                curl_setopt($curlHandler, CURLOPT_POST, true);
                break;

            case self::METHOD_GET:
            case self::METHOD_DELETE:
            case self::METHOD_PATCH:
                curl_setopt($curlHandler, CURLOPT_CUSTOMREQUEST, $method);
                break;
        }

        if (!empty($data)) {
            curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $data);
        }

        curl_setopt($curlHandler, CURLINFO_HEADER_OUT, true);
        curl_setopt($curlHandler, CURLOPT_URL, self::$ionicBaseURL . $endPoint);

        $response = curl_exec($curlHandler);

        $statusCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE);

        curl_close($curlHandler);

        $response = json_decode($response);

        if (!$this->isSuccessResponse($statusCode)) {
            $this->throwRequestException($statusCode, $response);
        }

        // Return response.
        return $response;
    }

    /**
     * Is response valid?
     *
     * @private
     * @param number $statusCode
     * @return bool
     */
    /*private function isValidResponse($statusCode) {
    return !$this->isInvalidResponse($statusCode);
    }*/

    /**
     * Is response valid?
     *
     * @private
     * @param number $statusCode
     * @return bool
     */
    private function isSuccessResponse($statusCode)
    {
        return $statusCode >= 200 && $statusCode < 300;
    }

    /**
     * Is response invalid?
     *
     * @private
     * @param number $statusCode
     * @return bool
     */
    private function isInvalidResponse($statusCode)
    {
        return $statusCode < 100 || $statusCode >= 600;
    }

    /**
     * Is there a client error?
     *
     * @private
     * @param number $statusCode
     * @return bool
     */
    private function isClientErrorResponse($statusCode)
    {
        return $statusCode >= 400 && $statusCode < 500;
    }

    /**
     * Was there a server side error?
     *
     * @private
     * @param number $statusCode
     * @return bool
     */
    private function isServerErrorResponse($statusCode)
    {
        return $statusCode >= 500 && $statusCode < 600;
    }

    /**
     * Throw the RequestException error with error detail
     *
     * @private
     * @param number $statusCode
     * @param mixed $response
     *
     * @throws RequestException
     *
     * @return void
     */
    private function throwRequestException($statusCode, $response)
    {
        if ($response && isset($response->error)) {
            $type = $response->error->type;
            $message = $this->getResponseErrorMessage($response->error);
            $link = $response->error->link;
        } elseif ($this->isServerErrorResponse($statusCode)) {
            $type = 'Server Error';
            $message = RequestException::$statusTexts[$statusCode];
            $link = '';
        } else {
            $type = 'Client Error';
            $message = RequestException::$statusTexts[$statusCode];
            $link = '';
        }

        throw new RequestException($type, $message, $link, $statusCode);
    }

    /**
     * Generate a full message from response error request
     *
     * @private
     * @param object $error
     *
     * @return string
     */
    private function getResponseErrorMessage($error)
    {
        $message = $error->message;

        if (isset($error->details) && is_array($error->details)) {
            foreach ($error->details as $detail) {
                $message .= implode(' - ', $detail->errors).' ['.$detail->error_type.' in '.$detail->parameter.'] ';
            }
        }

        return $message;
    }

    /**
     * Is response informative?
     *
     * @private
     * @param number $statusCode
     * @return bool
     */
    /*private function isInformationalResponse($statusCode) {
    return $statusCode >= 100 && $statusCode < 200;
    }*/

    /**
     * Is response successful?
     *
     * @private
     * @param number $statusCode
     * @return bool
     */
    /*private function isSuccessfulResponse($statusCode) {
    return $statusCode >= 200 && $statusCode < 300;
    }*/

    /**
     * Is the response a redirect?
     *
     * @private
     * @param number $statusCode
     * @return bool
     */
    /*private function isRedirectionResponse($statusCode) {
    return $statusCode >= 300 && $statusCode < 400;
    }*/

    /**
     * Is the response a Auth error?
     *
     * @private
     * @param number $statusCode
     * @return bool
     */
    /*private function isAuthErrorResponse($statusCode) {
    return 401 === $statusCode;
    }*/

    /**
     * Is the response forbidden?
     *
     * @private
     * @param number $statusCode
     * @return bool
     */
    /*private function isForbiddenResponse($statusCode) {
    return 403 === $statusCode;
    }*/

    /**
     * Is the response a not found error?
     *
     * @private
     * @param number $statusCode
     * @return bool
     */
    /*private function isNotFoundResponse($statusCode) {
    return 404 === $statusCode;
    }*/

    /**
     * Is the response empty?
     *
     * @private
     * @param number $statusCode
     * @return bool
     */
    /*private function isEmptyResponse($statusCode) {
return in_array($statusCode, array(204, 304));
}*/
}


text:
import gulp from 'gulp'
import babel from 'babel-core/register'

let plugins = require('gulp-load-plugins')({ pattern: '*', rename: {
    'vinyl-buffer': 'buffer',
    'gulp-awspublish-router' : 'awspublishRouter',
    'gulp-inline-source' : 'inlinesource'
}});
plugins.utilities = require('./gulp-utilities');
plugins.source = require('vinyl-source-stream');
babel({presets: plugins.utilities.paths.BABEL_PRESETS});

function getTask(task) {
  return require('./tasks/' + task)(gulp, plugins, plugins.utilities);
}

gulp.task('awspublish', getTask('awspublish'));
gulp.task('browser-reload', getTask('browser-reload'));
gulp.task('browser-sync', getTask('browser-sync'));
gulp.task('cdn-static-assets', getTask('cdn-static-assets'));
gulp.task('clean', getTask('clean'));
gulp.task('copy-assets', getTask('copy-assets'));
gulp.task('copy-vendor-js', getTask('copy-vendor-js'));
gulp.task('deploy:prepare', getTask('deploy:prepare'));
gulp.task('deploy:test', getTask('deploy:test'));
gulp.task('deploy', getTask('deploy'));
gulp.task('eslint', getTask('eslint'));
gulp.task('hash', getTask('hash'));
gulp.task('hash-replace', getTask('hash-replace'));
gulp.task('html-hint', getTask('html-hint'));
gulp.task('html-min', getTask('html-min'));
gulp.task('inline', getTask('inline'));
gulp.task('responsive-images', getTask('responsive-images'));
gulp.task('sass', getTask('sass'));
gulp.task('scripts', getTask('scripts'));
gulp.task('test', getTask('test'));
gulp.task('wintersmith', getTask('wintersmith'));

gulp.task('default', function(done) {
  plugins.runSequence('clean', ['wintersmith', 'scripts', 'copy-assets', 'copy-vendor-js'], 'sass', 'eslint', 'html-hint', 'browser-sync', function() {
    gulp.watch(plugins.utilities.paths.JS_SRC, ['eslint', 'scripts']);
    gulp.watch('styles/**/*', ['sass']);
    gulp.watch(plugins.utilities.paths.HTML_FILES, function() {plugins.runSequence('wintersmith', 'html-hint', 'browser-reload')} );
    done();
  });
});


text:
function Sync () {
	this._steps = [ ];
  this._arguments = [ ];
  this._current = 0;
  this._error = null;
}

Sync.prototype.next = function () {
  var args = Array.prototype.slice.call(arguments);
  this._steps.push(args.shift());
  this._arguments[this._steps.length - 1] = args;

  return this;
};

Sync.prototype.error = function (error) {
  this._error = error;

  return this;
};

Sync.prototype.done = function (err) {
  this._current++;
  var args = Array.prototype.slice.call(arguments);

  // if there is an error, we are done
  if (err) {
    if (this._error) {
      this._error.apply(this, args);
    }
  } else {
    if (this._steps.length) {
      var next = this._steps.shift();
      var a = this._arguments[this._current];
      var self = this;

      function cb (err, data) {
        self.done(err, data);
      };
      a.push(cb);
      next.apply(this, a);
    } else {
      if (this._callback) {
        this._callback.apply();
      }
    }
  }
};

Sync.prototype.start = function (callback) {
  this._callback = callback;

  var start = this._steps.shift(),
      self  = this;

  if (start) {
    var args = this._arguments[0];
    function cb (err, data) {
      self.done(err, data);
    };
    args.push(cb);
    start.apply(this, args);
  } else {
    if (this._callback) {
      this._callback();
    }
  }
};


text:
package org.gradle.api.internal.tasks.options;

import org.gradle.internal.typeconversion.TypeConversionException;

import java.util.List;
import java.util.Set;

public interface OptionElement {
    Set<String> getAvailableValues();

    Class<?> getOptionType();

    String getOptionName();

    /**
     * @throws TypeConversionException On failure to convert the supplied values to the appropriate target types.
     */
    void apply(Object object, List<String> parameterValues) throws TypeConversionException;

    String getDescription();
}


text:
import time
import csv
import operator
import os

# start time
begin_time = time.clock()

# file names and paths
code_key = "code.csv" 	# must be a csv
out_table = "block_out.csv"	# must be a csv
block_dir = "btxt"

block_files = []
for root, dirs, files in os.walk(block_dir):
    for file in files:
        if file.endswith(".txt"):
			fp = (os.path.join(root, file))
			block_files.append(fp)

# can use different file types, just make sure python can read them properly

# set up csv writer to output table
writer = csv.writer(open(out_table, 'a'),lineterminator = '\n')

# code table format:
# (name string,start int,end int)

# convert code table to custom dictionary and write header to out table
code_dict = {}
with open(code_key, 'rb') as csvfile:
	# read table
	codecsv = csv.reader(csvfile, delimiter=',')
	# set header list
	header = []
	for code in codecsv:
		# append code name to header list
		header.append(code[0])
		# calculate code length
		code_length = 1 + (int(code[2]) - int(code[1]))
		# generate code dictionary in form
		# (name,[start int, end int, length])
		code_dict[code[0]] = [int(code[1]), int(code[2]), code_length]
	# append a field name for any trailing chars not picked up by the code table
	header.append("XTRA_CHARS")
	# write header list to the out csv table
	writer.writerow(header)
# sort code_dict by initial order
code_dict = sorted(code_dict.items(), key=operator.itemgetter(1))

# print the code dictionary if you want
print code_dict

c = 0
# loop through lines (i.e. strips) and output to csv with code_dict
for cma in block_files:
	text_file = open(cma, "r")
	strips = text_file.readlines()
	num_strips =  len(strips)
	count = 0
	for strip in strips:
		# set loop length
		iter = len(code_dict)
		d = 0
		# loop through code dictionary, copying chars based on code dictionary
		row = []
		while (d < iter):
			key = code_dict[d][1]
			start_val = key[0] - 1
			end_val = start_val + key[2]
			write_val = strip[start_val:end_val]
			row.append(write_val)
			d = d + 1
		# append any trailing chars that don't have an associated code
		trailer = strip[end_val:]
		row.append(trailer)

		# write row to csv output table
		writer.writerow(row)
		count = count + 1
	c += 1

print "---------------------"
print "number of rows written"
print c

# print time
print "---------------------"
end_time = time.clock()
seconds = (end_time - begin_time)
minutes = seconds / 60
print seconds
print "seconds"
print "=============="
print minutes


text:
<?php
// DO NOT EDIT! Generated by Protobuf-PHP protoc plugin 1.0
// Source: query.proto
//   Date: 2016-01-22 01:34:42

namespace Vitess\Proto\Query {

  class Target extends \DrSlump\Protobuf\Message {

    /**  @var string */
    public $keyspace = null;

    /**  @var string */
    public $shard = null;

    /**  @var int - \Vitess\Proto\Topodata\TabletType */
    public $tablet_type = null;

    /** @var \Closure[] */
    protected static $__extensions = array();

    public static function descriptor()
    {
      $descriptor = new \DrSlump\Protobuf\Descriptor(__CLASS__, 'query.Target');

      // OPTIONAL STRING keyspace = 1
      $f = new \DrSlump\Protobuf\Field();
      $f->number    = 1;
      $f->name      = "keyspace";
      $f->type      = \DrSlump\Protobuf::TYPE_STRING;
      $f->rule      = \DrSlump\Protobuf::RULE_OPTIONAL;
      $descriptor->addField($f);

      // OPTIONAL STRING shard = 2
      $f = new \DrSlump\Protobuf\Field();
      $f->number    = 2;
      $f->name      = "shard";
      $f->type      = \DrSlump\Protobuf::TYPE_STRING;
      $f->rule      = \DrSlump\Protobuf::RULE_OPTIONAL;
      $descriptor->addField($f);

      // OPTIONAL ENUM tablet_type = 3
      $f = new \DrSlump\Protobuf\Field();
      $f->number    = 3;
      $f->name      = "tablet_type";
      $f->type      = \DrSlump\Protobuf::TYPE_ENUM;
      $f->rule      = \DrSlump\Protobuf::RULE_OPTIONAL;
      $f->reference = '\Vitess\Proto\Topodata\TabletType';
      $descriptor->addField($f);

      foreach (self::$__extensions as $cb) {
        $descriptor->addField($cb(), true);
      }

      return $descriptor;
    }

    /**
     * Check if <keyspace> has a value
     *
     * @return boolean
     */
    public function hasKeyspace(){
      return $this->_has(1);
    }

    /**
     * Clear <keyspace> value
     *
     * @return \Vitess\Proto\Query\Target
     */
    public function clearKeyspace(){
      return $this->_clear(1);
    }

    /**
     * Get <keyspace> value
     *
     * @return string
     */
    public function getKeyspace(){
      return $this->_get(1);
    }

    /**
     * Set <keyspace> value
     *
     * @param string $value
     * @return \Vitess\Proto\Query\Target
     */
    public function setKeyspace( $value){
      return $this->_set(1, $value);
    }

    /**
     * Check if <shard> has a value
     *
     * @return boolean
     */
    public function hasShard(){
      return $this->_has(2);
    }

    /**
     * Clear <shard> value
     *
     * @return \Vitess\Proto\Query\Target
     */
    public function clearShard(){
      return $this->_clear(2);
    }

    /**
     * Get <shard> value
     *
     * @return string
     */
    public function getShard(){
      return $this->_get(2);
    }

    /**
     * Set <shard> value
     *
     * @param string $value
     * @return \Vitess\Proto\Query\Target
     */
    public function setShard( $value){
      return $this->_set(2, $value);
    }

    /**
     * Check if <tablet_type> has a value
     *
     * @return boolean
     */
    public function hasTabletType(){
      return $this->_has(3);
    }

    /**
     * Clear <tablet_type> value
     *
     * @return \Vitess\Proto\Query\Target
     */
    public function clearTabletType(){
      return $this->_clear(3);
    }

    /**
     * Get <tablet_type> value
     *
     * @return int - \Vitess\Proto\Topodata\TabletType
     */
    public function getTabletType(){
      return $this->_get(3);
    }

    /**
     * Set <tablet_type> value
     *
     * @param int - \Vitess\Proto\Topodata\TabletType $value
     * @return \Vitess\Proto\Query\Target
     */
    public function setTabletType( $value){
      return $this->_set(3, $value);
    }
  }
}


text:
=====================
Editing RelaxNG files
=====================

All direct edits to RelaxNG files should be in the .rnc files. The program
TRANG_ should be used to generate a correcsponding .rng file. For Ubuntu, you
can install with:

.. code-block:: bash

   sudo apt-get install trang

To convert the .rnc file to .rng, use the following syntax:

.. code-block:: bash

   trang {filename}.rnc {filename}.rng

.. _TRANG: http://www.thaiopensource.com/relaxng/trang.html


text:
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Autor',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('usuario', models.OneToOneField(verbose_name=b'Usu\xc3\xa1rio', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'db_table': 'blog_autor',
                'verbose_name_plural': 'Autores',
            },
        ),
        migrations.CreateModel(
            name='Comentario',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('texto', models.TextField()),
                ('autor', models.CharField(max_length=100)),
                ('data', models.DateTimeField(auto_now_add=True)),
            ],
            options={
                'verbose_name': 'Coment\xe1rio',
                'verbose_name_plural': 'Coment\xe1rios',
            },
        ),
        migrations.CreateModel(
            name='Publicacao',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('titulo', models.CharField(max_length=100, verbose_name=b'T\xc3\xadtulo')),
                ('texto', models.TextField(verbose_name=b'Texto')),
                ('url', models.URLField(verbose_name=b'URL', blank=True)),
                ('data', models.DateTimeField(auto_now_add=True)),
                ('autor', models.ForeignKey(to='blog.Autor')),
            ],
            options={
                'db_table': 'blog_publicacao',
                'verbose_name': 'Publica\xe7\xe3o',
                'verbose_name_plural': 'Publica\xe7\xf5es',
            },
        ),
        migrations.AddField(
            model_name='comentario',
            name='publicacao',
            field=models.ForeignKey(verbose_name=b'Publica\xc3\xa7\xc3\xa3o', to='blog.Publicacao'),
        ),
    ]


text:
<?php

namespace Dabl\Adapter;
use Dabl\Adapter\Propel\Model\Database;
use Dabl\Adapter\Propel\Platform\PgsqlPlatform;
use Dabl\Adapter\Propel\Reverse\PgsqlSchemaParser;
use DateTimeZone;
use PDOException;

/**
 * This is used to connect to PostgresQL databases.
 */
class DBPostgres extends DABLPDO {

	/**
	 * Returns SQL that converts a date value to the start of the hour
	 *
	 * @param string $date
	 * @return string
	 */
	function hourStart($date) {
		return "DATE_TRUNC('hour', $date::TIMESTAMP)::TIMESTAMP";
	}

	/**
	 * Returns SQL that converts a date value to the start of the day
	 *
	 * @param string $date
	 * @return string
	 */
	function dayStart($date) {
		return "DATE_TRUNC('day', $date::DATE)::DATE";
	}

	/**
	 * Returns SQL that converts a date value to the first day of the week
	 *
	 * @param string $date
	 * @return string
	 */
	function weekStart($date) {
		return "(DATE_TRUNC('week', $date::DATE) - '1 days'::INTERVAL)::DATE";
	}

	/**
	 * Returns SQL that converts a date value to the first day of the month
	 *
	 * @param string $date
	 * @return string
	 */
	function monthStart($date) {
		return "DATE_TRUNC('month', $date::DATE)::DATE";
	}

	/**
	 * Returns SQL which converts the date value to its value in the target timezone
	 *
	 * @param string $date SQL column expression
	 * @param string|DateTimeZone $to_tz DateTimeZone or timezone id
	 * @param string|DateTimeZone $from_tz DateTimeZone or timezone id
	 * @return string
	 */
	function convertTimeZone($date, $to_tz, $from_tz = null) {
		if ($to_tz instanceof DateTimeZone) {
			$to_tz = $to_tz->getName();
		}
		if ($from_tz) {
			if ($from_tz instanceof DateTimeZone) {
				$from_tz = $from_tz->getName();
			}
			return "(($date)::TIMESTAMP AT TIME ZONE '$from_tz' AT TIME ZONE '$to_tz')";
		}

		return "(($date)::TIMESTAMPTZ AT TIME ZONE '$to_tz')";
	}

	/**
	 * @var int the current transaction depth
	 */
	protected $_transactionDepth = 0;

	/**
	 * This method is used to ignore case.
	 *
	 * @param	  string $in The string to transform to upper case.
	 * @return	 string The upper case string.
	 */
	function toUpperCase($in) {
		return "UPPER(" . $in . ")";
	}

	/**
	 * This method is used to ignore case.
	 *
	 * @param	  in The string whose case to ignore.
	 * @return	 The string in a case that can be ignored.
	 */
	function ignoreCase($in) {
		return "UPPER(" . $in . ")";
	}

	/**
	 * Returns SQL which concatenates the second string to the first.
	 *
	 * @param	  string String to concatenate.
	 * @param	  string String to append.
	 * @return	 string
	 */
	function concatString($s1, $s2) {
		return "($s1 || $s2)";
	}

	/**
	 * Returns SQL which extracts a substring.
	 *
	 * @param	  string String to extract from.
	 * @param	  int Offset to start from.
	 * @param	  int Number of characters to extract.
	 * @return	 string
	 */
	function subString($s, $pos, $len) {
		return "substring($s from $pos" . ($len > -1 ? "for $len" : "") . ")";
	}

	/**
	 * Returns SQL which calculates the length (in chars) of a string.
	 *
	 * @param	  string String to calculate length of.
	 * @return	 string
	 */
	function strLength($s) {
		return "char_length($s)";
	}

	/**
	 * @see		DABLPDO::getIdMethod()
	 */
	protected function getIdMethod() {
		return DABLPDO::ID_METHOD_SEQUENCE;
	}

	/**
	 * Gets ID for specified sequence name.
	 */
	function getId($table_name = null, $column_name = null) {
		return $this->query("SELECT currval(pg_get_serial_sequence({$this->quote($table_name)}, {$this->quote($column_name)}))")->fetchColumn(0);
	}

	/**
	 * Returns timestamp formatter string for use in date() function.
	 * @return	 string
	 */
	function getTimestampFormatter() {
		return "Y-m-d H:i:s O";
	}

	/**
	 * Returns timestamp formatter string for use in date() function.
	 * @return	 string
	 */
	function getTimeFormatter() {
		return "H:i:s O";
	}

	/**
	 * @see		DABLPDO::applyLimit()
	 */
	function applyLimit(&$sql, $offset, $limit) {
		if ( $limit > 0 ) {
			$sql .= " LIMIT ".$limit;
		}
		if ( $offset > 0 ) {
			$sql .= " OFFSET ".$offset;
		}
	}

	/**
	 * @see		DABLPDO::random()
	 */
	function random($seed = NULL) {
		return 'random()';
	}

	/**
	 * @return Database
	 */
	function getDatabaseSchema(){
		$parser = new PgsqlSchemaParser($this);
		$database = new Database($this->getDBName());
		$database->setPlatform(new PgsqlPlatform($this));
		$parser->parse($database);
		$database->doFinalInitialization();
		return $database;
	}

	/**
	 * Start transaction
	 *
	 * @return bool|void
	 */
	public function beginTransaction() {
		if ($this->_transactionDepth == 0) {
			parent::beginTransaction();
		} else {
			$this->exec("SAVEPOINT LEVEL{$this->_transactionDepth}");
		}

		$this->_transactionDepth++;
	}

	/**
	 * Commit current transaction
	 *
	 * @return bool|void
	 */
	public function commit() {
		$this->_transactionDepth--;

		if ($this->_transactionDepth == 0) {
			parent::commit();
		} else {
			$this->exec("RELEASE SAVEPOINT LEVEL{$this->_transactionDepth}");
		}
	}

	/**
	 * Rollback current transaction,
	 *
	 * @throws PDOException if there is no transaction started
	 * @return bool|void
	 */
	public function rollBack() {
		if ($this->_transactionDepth == 0) {
			throw new PDOException('Rollback error : There is no transaction started');
		}

		$this->_transactionDepth--;

		if ($this->_transactionDepth == 0) {
			parent::rollBack();
		} else {
			$this->exec("ROLLBACK TO SAVEPOINT LEVEL{$this->_transactionDepth}");
		}
	}
}


text:
<?php

class AWPCP_ListingsTableSearchConditionsParser {
    private $conditions = array();

    public function __construct( /*array */$conditions ) {
        $this->conditions = $conditions;
    }

    public function parse( $search_type, $search_term ) {
        foreach ( $this->conditions as $condition ) {
            if ( $condition->match( $search_type ) ) {
                return $condition->create( $search_term );
            }
        }

        throw new AWPCP_Exception( sprintf( 'Unknown search type: ', $search_type ) );
    }
}

function awpcp_listings_table_search_by_condition_parser() {
    $conditions = array(
        new AWPCP_ListingsTableSearchByIdCondition(),
        new AWPCP_ListingsTableSearchByKeywordCondition(),
        new AWPCP_ListingsTableSearchByLocationCondition(),
        new AWPCP_ListingsTableSearchByTitleCondition(),
        new AWPCP_ListingsTableSearchByUserCondition(),
    );

    if ( awpcp_current_user_is_admin() ) {
        $conditions[] = new AWPCP_ListingsTableSearchByPayerEmailCondition();
    }

    return new AWPCP_ListingsTableSearchConditionsParser( $conditions );
}


text:
import { ipcRenderer, remote } from 'electron'
import * as asciiDocumentStyle from './ui/document/ascii-document-style'
import Doc from './ui/document/doc'
import './ui/document/enable-drag-and-drop'
import './ui/settings/window-settings'
import { saveImage } from './utils/general-utils'

const doc = new Doc(remote.app.getName())

ipcRenderer.on('open-file', (_: any, filePath: string) => {
    doc.open(filePath)
    remote.app.addRecentDocument(filePath)
})

ipcRenderer.on('show-open-dialog', () => ipcRenderer.send('show-open-dialog'))

ipcRenderer.on('show-export-dialog', () => ipcRenderer.send('show-export-dialog'))

ipcRenderer.on('export-to-png', () => ipcRenderer.send('export-to-png'))

ipcRenderer.on('close-file', () => doc.close())

ipcRenderer.on('export-to-png', (_: any, fileName: string) => {
    saveImage(fileName).then(() => remote.app.dock.downloadFinished(fileName))
})

ipcRenderer.on('open-preferences', () => ipcRenderer.send('open-preferences'))

ipcRenderer.on('bg-color-changed', (_: any, color: string) => {
    asciiDocumentStyle.setBgColor(color)
})

ipcRenderer.on('text-color-changed', (_: any, color: string) => {
    asciiDocumentStyle.setTextColor(color)
})

ipcRenderer.on('link-color-changed', (_: any, color: string) => {
    asciiDocumentStyle.setLinkColor(color)
})

ipcRenderer.on('selection-color-changed', (_: any, color: string) => {
    asciiDocumentStyle.setSelectionColor(color)
})

ipcRenderer.on('font-changed', (_: any, fontName: string) => {
    asciiDocumentStyle.setFont(fontName)
})

ipcRenderer.on('font-size-changed', (_: any, fontSize: string) => {
    asciiDocumentStyle.setFontSize(fontSize)
})

ipcRenderer.on('font-smooting-changed', (_: any, enabled: boolean) => {
    asciiDocumentStyle.enableFontSmoothing(enabled)
})

ipcRenderer.on('links-highlighting-changed', (_: any, enabled: boolean) => {
    asciiDocumentStyle.enableLinksHighlighting(enabled)
})


text:
compat_symbol (libm, __nextafter, nextafterl, GLIBC_2_0);
#endif
#if LONG_DOUBLE_COMPAT(libm, GLIBC_2_1)
strong_alias (__nextafter, __nexttowardd)
strong_alias (__nextafter, __nexttowardld)
#undef nexttoward
compat_symbol (libm, __nexttowardd, nexttoward, GLIBC_2_1);
compat_symbol (libm, __nexttowardld, nexttowardl, GLIBC_2_1);
#endif