text:
---
id: version-stable-install
title: Install
original_id: install
---

First, install Prettier locally:

<!--DOCUSAURUS_CODE_TABS-->
<!--npm-->

```bash
npm install --save-dev --save-exact prettier
```

<!--yarn-->

```bash
yarn add --dev --exact prettier
```

<!--END_DOCUSAURUS_CODE_TABS-->

Then, create an empty config file to let editors and other tools know you are using Prettier:

<!-- Note: `echo "{}" > .prettierrc.json` would result in `"{}"<SPACE>` on Windows. The below version works in cmd.exe, bash, zsh, fish. -->

```bash
echo {}> .prettierrc.json
```

Next, create a [.prettierignore](ignore.md) file to let the Prettier CLI and editors know which files to _not_ format. Here's an example:

```
# Ignore artifacts:
build
coverage
```

> Tip! Base your .prettierignore on .gitignore and .eslintignore (if you have one).

> Another tip! If your project isn't ready to format, say, HTML files yet, add `*.html`.

Now, format all files with Prettier:

<!--DOCUSAURUS_CODE_TABS-->
<!--npm-->

```bash
npx prettier --write .
```

> What is that `npx` thing? `npx` ships with `npm` and lets you run locally installed tools. We'll leave off the `npx` part for brevity throughout the rest of this file!
>
> Note: If you forget to install Prettier first, `npx` will temporarily download the latest version. That's not a good idea when using Prettier, because we change how code is formatted in each release! It's important to have a locked down version of Prettier in your `package.json`. And it's faster, too.

<!--yarn-->

```bash
yarn prettier --write .
```

> What is `yarn` doing at the start? `yarn prettier` runs the locally installed version of Prettier. We'll leave off the `yarn` part for brevity throughout the rest of this file!

<!--END_DOCUSAURUS_CODE_TABS-->

`prettier --write .` is great for formatting everything, but for a big project it might take a little while. You may run `prettier --write app/` to format a certain directory, or `prettier --write app/components/Button.js` to format a certain file. Or use a _glob_ like `prettier --write "app/**/*.test.js"` to format all tests in a directory (see [fast-glob](https://github.com/mrmlnc/fast-glob#pattern-syntax) for supported glob syntax).

If you have a CI setup, run the following as part of it to make sure that everyone runs Prettier. This avoids merge conflicts and other collaboration issues!

```bash
npx prettier --check .
```

`--check` is like `--write`, but only checks that files are already formatted, rather than overwriting them. `prettier --write` and `prettier --check` are the most common ways to run Prettier.

## Set up your editor

Formatting from the command line is a good way to get started, but you get the most from Prettier by running it from your editor, either via a keyboard shortcut or automatically whenever you save a file. When a line has gotten so long while coding that it won't fit your screen, just hit a key and watch it magically be wrapped into multiple lines! Or when you paste some code and the indentation gets all messed up, let Prettier fix it up for you without leaving your editor.

See [Editor Integration](editors.md) for how to set up your editor. If your editor does not support Prettier, you can instead [run Prettier with a file watcher](watching-files.md).

> **Note:** Don't skip the regular local install! Editor plugins will pick up your local version of Prettier, making sure you use the correct version in every project. (You wouldn't want your editor accidentally causing lots of changes because it's using a newer version of Prettier than your project!)
>
> And being able to run Prettier from the command line is still a good fallback, and needed for CI setups.

## ESLint (and other linters)

If you use ESLint, install [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier#installation) to make ESLint and Prettier play nice with each other. It turns off all ESLint rules that are unnecessary or might conflict with Prettier. There's a similar config for Stylelint: [stylelint-config-prettier](https://github.com/prettier/stylelint-config-prettier)

(See [Prettier vs. Linters](comparison.md) to learn more about formatting vs linting, [Integrating with Linters](integrating-with-linters.md) for more in-depth information on configuring your linters, and [Related projects](related-projects.md) for even more integration possibilities, if needed.)

## Git hooks

In addition to running Prettier from the command line (`prettier --write`), checking formatting in CI, and running Prettier from your editor, many people like to run Prettier as a pre-commit hook as well. This makes sure all your commits are formatted, without having to wait for your CI build to finish.

For example, you can do the following to have Prettier run before each commit:

1. Install [husky](https://github.com/typicode/husky) and [lint-staged](https://github.com/okonet/lint-staged):

   <!--DOCUSAURUS_CODE_TABS-->
   <!--npm-->

   ```bash
   npm install --save-dev husky lint-staged
   npx husky install
   npm set-script prepare "husky install"
   npx husky add .husky/pre-commit "npx lint-staged"
   ```

   <!--yarn-->

   ```bash
   yarn add --dev husky lint-staged
   npx husky install
   npm set-script prepare "husky install"
   npx husky add .husky/pre-commit "npx lint-staged"
   ```

   > If you use Yarn 2, see https://typicode.github.io/husky/#/?id=yarn-2

   <!--END_DOCUSAURUS_CODE_TABS-->

> Note: npm **set-script** command requires at least **npm v7.x**. See https://docs.npmjs.com/cli/v7/commands/npm-set-script.

2. Add the following to your `package.json`:

```json
{
  "lint-staged": {
    "**/*": "prettier --write --ignore-unknown"
  }
}
```

> Note: If you use ESLint, make sure lint-staged runs it before Prettier, not after.

See [Pre-commit Hook](precommit.md) for more information.

## Summary

To summarize, we have learned to:

- Install an exact version of Prettier locally in your project. This makes sure that everyone in the project gets the exact same version of Prettier. Even a patch release of Prettier can result in slightly different formatting, so you wouldn't want different team members using different versions and formatting each other's changes back and forth.
- Add a `.prettierrc.json` to let your editor know that you are using Prettier.
- Add a `.prettierignore` to let your editor know which files _not_ to touch, as well as for being able to run `prettier --write .` to format the entire project (without mangling files you don't want, or choking on generated files).
- Run `prettier --check .` in CI to make sure that your project stays formatted.
- Run Prettier from your editor for the best experience.
- Use [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) to make Prettier and ESLint play nice together.
- Set up a pre-commit hook to make sure that every commit is formatted.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BitShuva.Chavah.Common;
using BitShuva.Chavah.Models;
using BitShuva.Chavah.Services;
using BitShuva.Chavah.Settings;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Raven.Client.Documents.Session;

namespace BitShuva.Chavah.Controllers
{
    [Route("api/[controller]/[action]")]
    public class CdnController : RavenController
    {
        private readonly ICdnManagerService cdnManager;
        private readonly IOptions<CdnSettings> cdnSettings;

        public CdnController(
            ICdnManagerService cdnManager,
            IOptions<CdnSettings> cdnSettings,
            IAsyncDocumentSession dbSession,
            ILogger<CdnController> logger)
            : base(dbSession, logger)
        {
            this.cdnManager = cdnManager;
            this.cdnSettings = cdnSettings;
        }

        [Authorize(Roles = AppUser.AdminRole)]
        [HttpGet]
        public async Task<List<string>> ValidateSongCdnLinks()
        {
            // Find all song CDN URLs.
            var invalidSongUris = new HashSet<string>(5000, StringComparer.InvariantCultureIgnoreCase);
            var songEnumerator = await DbSession.Advanced.StreamAsync<Song>("songs/");
            while (await songEnumerator.MoveNextAsync())
            {
                var songUri = songEnumerator.Current.Document.Uri?.ToString();
                if (!string.IsNullOrEmpty(songUri))
                {
                    invalidSongUris.Add(songUri);
                }
            }

            // Find all the artist directories in the music directory.
            var musicDir = cdnSettings.Value.MusicDirectory;
            var artistDirectories = await cdnManager.GetDirectories(musicDir);
            foreach (var artistDir in artistDirectories)
            {
                var files = await cdnManager.GetFiles($"{musicDir}/{artistDir}");
                foreach (var file in files)
                {
                    var mp3Uri = $"{cdnSettings.Value.HttpPath}/{musicDir}/{artistDir}/{file}";

                    // Since it exists on the CDN, remove it from the invalid Song URIs list.
                    invalidSongUris.Remove(mp3Uri);
                }
            }

            return invalidSongUris.ToList();
        }

        /// <summary>
        /// Redirects to a random station identifier MP3 on the CDN.
        /// </summary>
        /// <returns></returns>
        public RedirectResult GetStationId()
        {
            var directory = new Uri(cdnSettings.Value.HttpPath).Combine(cdnSettings.Value.SoundEffects);
            var idAnnouncement = new Random().Next(1, 9);
            return Redirect(directory.Combine($"StationId{idAnnouncement}.mp3").AbsoluteUri);
        }

        /// <summary>
        /// Redirects to the profile picture of the user with the specified ID. If it doesn't exist,
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<RedirectResult> GetUserProfile(string userId)
        {
            if (string.IsNullOrWhiteSpace(userId))
            {
                return Redirect(DefaultProfilePic.ToString());
            }

            var user = await DbSession.LoadOptionalAsync<AppUser>(userId);
            var profilePic = user?.ProfilePicUrl ?? DefaultProfilePic;
            return Redirect(profilePic.ToString());
        }

        private Uri DefaultProfilePic => new Uri(cdnSettings.Value.HttpPath)
            .Combine(cdnSettings.Value.ProfilePicsDirectory)
            .Combine("unknown-user.jpg");
    }
}

redpajama_set_name: RedPajamaGithub


text:
var winston = require('winston');

var ReplaceHeaders = function(rules, realResponse, headers) {
    this.rules = rules;
    this.realResponse = realResponse;
    this.headers = headers;
};

ReplaceHeaders.prototype.process = function(modifiedResponse) {
    winston.info("Replacing headers. Details: " + JSON.stringify(this.headers));
    modifiedResponse.writeHead(200, this.headers);
};

module.exports = ReplaceHeaders;


text:
package com.squareup.wire.protos.one_extension;

import com.squareup.wire.Message;
import com.squareup.wire.ProtoField;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;

public final class Foo extends Message<Foo> {
  private static final long serialVersionUID = 0L;

  public static final String DEFAULT_BAR = "";

  @ProtoField(
      tag = 1,
      type = Message.Datatype.STRING
  )
  public final String bar;

  public Foo(String bar) {
    this.bar = bar;
  }

  private Foo(Builder builder) {
    this(builder.bar);
    setBuilder(builder);
  }

  @Override
  public boolean equals(Object other) {
    if (other == this) return true;
    if (!(other instanceof Foo)) return false;
    return equals(bar, ((Foo) other).bar);
  }

  @Override
  public int hashCode() {
    int result = hashCode;
    return result != 0 ? result : (hashCode = bar != null ? bar.hashCode() : 0);
  }

  public static final class Builder extends com.squareup.wire.Message.Builder<Foo, Builder> {
    public String bar;

    public Builder() {
    }

    public Builder(Foo message) {
      super(message);
      if (message == null) return;
      this.bar = message.bar;
    }

    public Builder bar(String bar) {
      this.bar = bar;
      return this;
    }

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


text:
'use strict';

// TODO linting approach
// TODO testing approach
// TODO metrics approach
// TODO documentation

// Application controller for node application.
var app = exports;

// app.js
// --------------

var _ = require('lodash');
var path = require('path');
var bunyan = require('bunyan');

// Module Exports (config, pkg, logger)
// --------------

var config = app.config = require('config');
var pkg = app.pkg = require('./package.json');
var logger = app.logger = bunyan.createLogger({
  name: app.pkg.name,
  streams: [
    {
      level:  config.logger.level || 'info',
      stream: process.stdout
    }
  ]
});

logger.warn(_.pick(pkg, ['name','version']), 'app');
logger.warn({ proc: process.pid,  env: process.env.NODE_ENV }, 'process');
logger.warn({
  directory: config.util.getEnv('NODE_CONFIG_DIR'),
  sources: _.pluck(config.util.getConfigSources(), 'name')
}, 'config');

// Programmatically set app config values.
config.app = config.app || {};
config.app.name = pkg.name;
config.app.description = pkg.description;
config.app.version = pkg.version;

// Update config.paths to include full path.
for (var p in config.paths) {
  if (config.paths.hasOwnProperty(p)) {
    config.paths[p] = path.normalize(__dirname + config.paths[p]);
  }
}

// Initialize/Configure Express
// --------------

logger.info('configuring express...');

var express = require('express');
var compress = require('compression');
var favicon = require('serve-favicon');
var uuid = require('node-uuid');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var responseTime = require('response-time');
var expressBunyanLogger = require('express-bunyan-logger');
var timeout = require('connect-timeout');

// Module Export (app)
// --------------

app.express = express();
app.express.logger = logger;

// Copy config app to app locals.
_.extend(app.express.locals, config.app);

// Set timeout
var timeoutVal = config.app.timeout || '5s';
logger.info('setting "timeout" to %s', timeoutVal);
app.express.use(timeout(timeoutVal));

// Enable gzip compression.
logger.info('registering middleware "compress", "gzip" compression enabled');
app.express.use(compress());

logger.info('registering middleware, misc. functionality (json, cookie support, etc.)');
app.express.use(bodyParser.json());
app.express.use(bodyParser.urlencoded({ extended: false }));
app.express.use(cookieParser());
// uncomment after placing your favicon in /public
//app.express.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

logger.info('registering middleware, set ID in request object & header (req.id)');
app.express.use(function(req, res, next) {
  var reqIdHeader = 'X-Request-Id';
  req.id = req.get(reqIdHeader) || uuid.v4();
  res.setHeader('X-Request-Id', req.id);
  next();
});

logger.info('registering middleware "express-bunyan-logger", "X-Response-Time" header enabled');
app.express.use(expressBunyanLogger({
  logger: logger,
  format: config.logger.format,
  excludes: config.logger.excludes,
  genReqId: function(req) {
    return req.id;
  }
}));

logger.info('registering middleware, copy reference og req.log to res.log');
app.express.use(function(req, res, next) {
  req.log.info({ method: req.method, url: req.url }, 'REQUEST');
  res.log = req.log;
  next();
});

logger.info('registering middleware "response-time", "X-Response-Time" header enabled');
app.express.use(responseTime()); // note headers are sent before actual completion of request time is not exact

// Disable "X-Powered-By"
app.express.set('x-powered-by', false);

// Public directory.
logger.info('setting "%s" as public directory', config.paths.public);
app.express.use(express.static(config.paths.public));

// View engine setup.
logger.info('setting "%s/views" as view directory', config.paths.server);
app.express.set('views', config.paths.views);
logger.info('setting "jade" as view engine');
app.express.set('view engine', 'jade');

logger.info('express configured!');

// Initialize Routes
// --------------

// TODO add to config
var index = require('./src/server/routes/index');
var api = require('./src/server/routes/api');
app.express.use('/', index);
app.express.use('/api', api);

logger.info('routes registered!');

// Register Error Handlers
// --------------

// catch 404 and forward to error handler
app.express.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.express.get('env') === 'development') {
  app.express.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.express.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


text:
import { Component } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Observable } from 'rxjs/Observable';

import { Field } from '../models/df-field.model';
import { FieldConfig } from '../models/df-config.model';

import { Store } from '@ngrx/store';
import { DFState, DFActions } from '../index';

@Component({
  selector: 'form-validation-message',
  styles:[
    `
    `
  ],
  template: `
    <ion-row class="is-hoverable" (click)="toggleExpand()">
      <ion-col responsiveGrid leftOrRight="left" col-4 class="is-borderRight">
        <ion-item class="is-fullHeight">

Validations

        </ion-item>
      </ion-col>
      <ion-col responsiveGrid leftOrRight="right" col-7>
        <ion-item [formGroup]="group">
          <ion-input [disabled]="true"
            value="{{(passedValidations$ | async).length}}/{{(validations$ | async).length}}">
          </ion-input>
        </ion-item>
      </ion-col>
      <ion-col col-1>
        <ion-item class="is-fullHeight">

<ion-icon color="light" name="arrow-dropdown" class="is-iconLabel"></ion-icon>

        </ion-item>
      </ion-col>
    </ion-row>
    <ng-container *ngIf="validationsToggle">
      <ng-container *ngFor="let validation of (validations$ | async);">
        <ion-item *ngIf="validation.valid" text-wrap>
{{validation.message}}
 </ion-item>
        <ion-item *ngIf="!validation.valid" text-wrap>
{{validation.message}}
 </ion-item>
      </ng-container>
    </ng-container>
  `
})
export class DFValidationMessageComponent implements Field {
  allConfig: FieldConfig[] = [];
  config: FieldConfig;
  group: FormGroup;

  validations$ = this.store.select(store => (store as any).dynamicForms.validations);
  passedValidations$ = this.validations$
  .flatMap((validation) => {
    return Observable.of(validation.map((validation) => validation.valid).filter(Boolean));
  });

  validationsToggle = false;

  constructor(private store: Store<{}>) {}

  toggleExpand() {
    this.validationsToggle = !this.validationsToggle;
  }

}


text:
require "spec_helper"

describe Brightbox::CloudIP do
  subject(:cloud_ip) do
    Brightbox::CloudIP.new("cip-12345")
  end

  it_behaves_like "a wrapped API resource"
end


text:
<?php
namespace ridona;

abstract class Parse
{
    abstract public function by_entire();
    abstract public function by_chunk($chunk_size);
    public function extract($pattern)
    {
        return Extract::start($pattern);
    }
    public function get_filetype($filename)
    {
        return mime_content_type($filename);
    }
}


text:
gitsteps
========

Collection of useful commands when using Git, GitHub and/or Gerrit


text:
define([
    "tracemon.env.config",
    "tracemon.lib.jquery-amd",
    "tracemon.connector.translation",
    "tracemon.connector.persist-host",
    "tracemon.connector.log.persist",
    "tracemon.connector.ripe-database"
], function(config, $, TranslateConnector, PersistHostConnector, LogRestConnector, RipeDatabaseConnector) {
    var antiFloodTimerNewStatus;

    var ConnectorFacade = function (env) {
        var translateConnector, $this, cache, persitHostConnector, logConnector, ripeDatabaseConnector;

        $this = this;
        translateConnector = new TranslateConnector(env);
        persitHostConnector = new PersistHostConnector(env);
        ripeDatabaseConnector = new RipeDatabaseConnector(env);
        logConnector = new LogRestConnector(env);
        cache = {
            geoRequests: {},
            reversDns: {},
            asnLookup: {},
            triangulated: {}
        };

        if (env.sendErrors) {
            window.onerror = function (error, url, line) {
                $this.persistLog("document", error + " url: " + url + " line: " + line);
            };

            env.utils.observer.subscribe("error", function (error) {
                this.persistLog(error.type, error.message);
            }, this);

        }

        this._handleError = function(error){
            var message;

            message = config.errors[error] || error;
            if (error) {
                env.utils.observer.publish("error", {
                    type: error,
                    message: message
                });
            }
        };

        this.getRealTimeResults = function(measurement, filtering){
            filtering = filtering || {};
            filtering.stream_type = "result";
            filtering.buffering = "true";
            filtering.msm = measurement.id;
            translateConnector.getRealTimeResults(
                filtering,
                function(result){
                    measurement.addTraceroutes(result);
                    clearTimeout(antiFloodTimerNewStatus);
                    antiFloodTimerNewStatus = setTimeout(function(){
                        env.historyManager.getLastState();
                    }, config.eventGroupingAntiFlood);
                }.bind(this));
        };

        this.getMeasurementsResults = function(measurements, options){
            var deferredCall, deferredArray, resultsPromise, measurement;

            deferredCall = $.Deferred();
            deferredArray = [];

            for (var n=0,length=measurements.length; n<length; n++){
                measurement = measurements[n];

                resultsPromise = translateConnector
                    .getMeasurementResults(measurement, options);

                deferredArray.push(resultsPromise); // Get results
            }

            $.when
                .apply($, deferredArray)
                .then(function(){
                    var measurements, traceroutes;

                    measurements = [].slice.call(arguments);
                    traceroutes = $.map(measurements, function(measurement){ // Enrich the probes (e.g. check if they replied) NOTE: it's ASYNC
                        return measurement.getTraceroutes();
                    });

                    $this._enrichProbes(traceroutes, options.sources);

                    env.utils.observer.publish("model.history:new");
                    deferredCall.resolve(measurements);
                }, function(error){
                    $this._handleError(error);
                });

            return deferredCall.promise();
        };

        this.getSourceHosts = function () {
            var sourceHosts = translateConnector.getSourceHosts();
            return Object.keys(env.loadedSources)
                .map(function (probeId) {
                    return sourceHosts[probeId];
                }).filter(function (item) {
                    return item != null;
                });
        };

        this.getAutonomousSystem = function(ip){
            var deferredCall;

            if (!cache.asnLookup[ip]) {
                deferredCall = $.Deferred();

                translateConnector.getAutonomousSystem(ip)
                    .done(function (data) {

                        deferredCall.resolve(data);
                    })
                    .fail(function (error) {
                        $this._handleError(error);
                    });
                cache.asnLookup[ip] = deferredCall.promise();
            }

            return cache.asnLookup[ip];
        };

        this.getHostReverseDns = function(host) {
            var deferredCall;

            if (!cache.reversDns[host.ip]) {

                deferredCall = $.Deferred();
                if (host.isPrivate || !host.ip) {
                    deferredCall.resolve(null);
                } else if (host.reverseDns) {
                    deferredCall.resolve(host.reverseDns);
                } else {
                    translateConnector.getHostReverseDns(host)
                        .done(function (data) {
                            deferredCall.resolve(data);
                        })
                        .fail(function (error) {
                            $this._handleError(error);
                        });
                }
                cache.reversDns[host.ip] = deferredCall.promise();
            }

            return cache.reversDns[host.ip];
        };

        this.tryGeolocatingAgain = function (host) {
            if (!cache.triangulated[host.ip]){
                // Try to locate the ip in a couple of minutes (try only once)
                setTimeout(function () {
                    cache.triangulated[host.ip] = true; // try once
                    delete cache.geoRequests[host.ip];
                    $this.getGeolocation(host, true);
                }, config.retryGeolocationAfter);
            }
        };

        this.getGeolocation = function(host, force, body){
            var deferredCall;

            if (host.isPrivate || !host.ip){
                throw "501"; // Not possible to find a geolocation
            }

            if (!force && cache.geoRequests[host.ip]){
                return cache.geoRequests[host.ip];
            } else {

                deferredCall = $.Deferred();

                if (host.getLocation()) {
                    deferredCall.resolve(host.getLocation());
                } else {
                    translateConnector.getGeolocation(host, force, body)
                        .done(function (data) {
                            deferredCall.resolve(data);
                        })
                        .fail(function(error){
                            $this._handleError(error);
                        });
                }
                cache.geoRequests[host.ip] = deferredCall.promise();

                return cache.geoRequests[host.ip];
            }
        };

        this.getMeasurements = function(measurementIds){
            var deferredCall, measurementId, promises, deferredArray;

            deferredCall = $.Deferred();
            deferredArray = [];

            for (var n=0,length=measurementIds.length; n<length; n++) {
                measurementId = measurementIds[n];

                promises = translateConnector
                    .getMeasurementInfo(measurementId);

                deferredArray.push(promises);
            }

            $.when
                .apply($, deferredArray)
                .then(function(){
                    deferredCall.resolve([].slice.call(arguments));
                }, function(error){
                    $this._handleError(error);
                });

            return deferredCall.promise();
        };

        this.getHosts = function() {
            return translateConnector.getHosts();
        };

        this.getASes = function () {
            return translateConnector.getASes();
        };

        this.getProbeInfo = function(probeId){
            return translateConnector.getProbeInfo(probeId);
        };

        this._enrichProbes = function(traceroutes, probesList){
            var replyingProbes, probeIds;

            probeIds = $.map(traceroutes, function(traceroute){
                return traceroute.source.probeId;
            });
            replyingProbes = env.utils.arrayUnique(probeIds);

            // Check if all the probes are replying and mark them.
            for (var n=0,length=probesList.length; n<length; n++) {
                env.loadedSources[probesList[n]].empty = (replyingProbes.indexOf(probesList[n]) == -1);
            }

        };

        this.persistLog = function(type, log){
            var browserVersion;

            if (env.sendErrors) {
                browserVersion = env.utils.getBrowserVersion();
                logConnector.error(type, log + ' (browser: ' + browserVersion.name + ' ' + browserVersion.version.toString() + ')');
            }
        };

        this.getAutonomousSystemContacts = function (asObject) {
            return ripeDatabaseConnector.getAutonomousSystemContacts(asObject.id).fail($this._handleError);
        };

        this.persist = function() {
            var hosts, host, callsArray, deferredCall;

            deferredCall = $.Deferred();
            hosts = this.getHosts();
            callsArray = [];
            for (var n=0,length=hosts.length; n<length; n++) {
                host = hosts[n];

                if (host && !host.isPrivate && host.ip && host.dirty && host.getLocation()){
                    callsArray.push(persitHostConnector.persist(host));
                }
            }

            $.when
                .apply($, callsArray)
                .then(function(){

                    for (var n=0,length=hosts.length; n<length; n++) {
                        hosts[n].dirty = false;
                    }
                    deferredCall.resolve();
                }, function(error){
                    for (var n=0,length=hosts.length; n<length; n++) {
                        hosts[n].dirty = false;
                    }
                    deferredCall.reject();
                });

            return deferredCall.promise();
        };

        this.getSparseHost = function (ip) {
            return translateConnector.getSparseHost(ip);
        };

        env.utils.observer.subscribe("model.host:locating", this.tryGeolocatingAgain, this);
    };

    return ConnectorFacade;

});


text:
module Ruy
  module Conditions

    # Expects that a context attribute is included in a set of values.
    class In < Condition
      attr_reader :attr, :values

      # @param values Expected set of values
      # @param attr Context attribute's name
      # @yield a block in the context of the current rule
      def initialize(values, attr, &block)
        super
        @values = values
        @attr = attr
      end

      def call(var_ctx)
        self.values.include?(var_ctx.resolve(self.attr))
      end

      def ==(o)
        o.kind_of?(In) &&
          self.attr == o.attr &&
          self.values == o.values
      end
    end

  end
end


text:
package org.gradle.plugin.management.internal.autoapply;

import com.google.common.collect.Lists;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.artifacts.ModuleVersionSelector;
import org.gradle.api.initialization.dsl.ScriptHandler;
import org.gradle.plugin.management.internal.DefaultPluginRequests;
import org.gradle.plugin.management.internal.PluginRequestInternal;
import org.gradle.plugin.management.internal.PluginRequests;

import java.util.List;

public class DefaultAutoAppliedPluginHandler implements AutoAppliedPluginHandler {

    private final AutoAppliedPluginRegistry registry;

    public DefaultAutoAppliedPluginHandler(AutoAppliedPluginRegistry registry) {
        this.registry = registry;
    }

    @Override
    public PluginRequests mergeWithAutoAppliedPlugins(PluginRequests initialRequests, Object pluginTarget) {
        if (!(pluginTarget instanceof Project)) {
            return initialRequests;
        }
        Project project = (Project) pluginTarget;

        PluginRequests autoAppliedPlugins = registry.getAutoAppliedPlugins(project);
        if (autoAppliedPlugins.isEmpty()) {
            return initialRequests;
        }

        List<PluginRequestInternal> merged = Lists.newArrayList(initialRequests);
        for (PluginRequestInternal autoAppliedPlugin : autoAppliedPlugins) {
            if (!isAlreadyAppliedOrRequested(autoAppliedPlugin, initialRequests, project)) {
                merged.add(autoAppliedPlugin);
            }
        }
        return new DefaultPluginRequests(merged);
    }

    private static boolean isAlreadyAppliedOrRequested(PluginRequestInternal autoAppliedPlugin, PluginRequests requests, Project project) {
        return isAlreadyApplied(autoAppliedPlugin, project) || isAlreadyRequestedInPluginsBlock(autoAppliedPlugin, requests) || isAlreadyRequestedInBuildScriptBlock(autoAppliedPlugin, project);
    }

    private static boolean isAlreadyApplied(PluginRequestInternal autoAppliedPlugin, Project project) {
        return project.getPlugins().hasPlugin(autoAppliedPlugin.getId().getId());
    }

    private static boolean isAlreadyRequestedInPluginsBlock(PluginRequestInternal autoAppliedPlugin, PluginRequests requests) {
        for (PluginRequestInternal request : requests) {
            if (autoAppliedPlugin.getId().equals(request.getId())) {
                return true;
            }
        }
        return false;
    }

    private static boolean isAlreadyRequestedInBuildScriptBlock(PluginRequestInternal autoAppliedPlugin, Project project) {
        ModuleVersionSelector module = autoAppliedPlugin.getModule();
        if (module == null) {
            return false;
        }

        Configuration classpathConfiguration = project.getBuildscript().getConfigurations().getByName(ScriptHandler.CLASSPATH_CONFIGURATION);
        for (Dependency dependency : classpathConfiguration.getDependencies()) {
            if (module.getGroup().equals(dependency.getGroup()) && module.getName().equals(dependency.getName())) {
                return true;
            }
        }

        return false;
    }
}


text:
module Atmosphere
  class NotAdmin < Exception; end
end


text:
"""
Style

Contains convenience functions for styling widgets.

:Authors:
	Berend Klein Haneveld
"""
import sys

def styleWidgetForTab(widget):
	"""
	This function style a widget that can be used inside a QScrollArea that
	is inside a QTabWidget. On OS X the background color inside a tab
	widget is slightly darker than the default, so it has to be styled
	otherwise it would stand out.

	There is a bug in Qt where QComboBox will not render properly
	on OS X when the background style of a parent is adjusted.
	In order to solve this, the background style of such a widget
	should only be set for that object, so by naming it and setting
	the style only for objects with that name the bug can be worked
	around.

	Use this function whenever a (container) widget is needed inside a
	QScrollArea in a QTabWidget.
	:type widget: QWidget
	"""
	if sys.platform.startswith("darwin"):
		widget.setObjectName("tabWidget")
		widget.setStyleSheet("#tabWidget {background: rgb(229, 229, 229);}")
	elif sys.platform.startswith("linux"):
		# This makes it look pretty on Elementary theme
		widget.setObjectName("tabWidget")
		widget.setStyleSheet("#tabWidget {background: rgb(236, 236, 236);}")
	elif sys.platform.startswith("win"):
		widget.setObjectName("tabWidget")
		widget.setStyleSheet("#tabWidget {background: rgb(255, 255, 255);}")


text:
import * as $ from '../lib/utils';
import * as chai from 'chai';
import {Setting, Ids}  from './../lib/setting';
import * as fs from 'fs-extra';
import * as path from 'path';
import {Model} from './../lib/model';
import * as _ from 'underscore';
import { Tuls as $t} from './test-utils';

import {CmdUtils} from './../lib/cmd-utils';

import * as child_process from 'child_process';

var assert = chai.assert;

let indir = path.join(Setting.test_items_dir);
let outdir = path.join(Setting.test_out_dir);
fs.emptyDirSync(outdir);
let firststep = () => {
  Setting.reset();
  Setting.postinit();
  Setting.mp_console = false;
};
//Init
Setting.postinit();
Setting.mp_console = false;

function ok_all_tests(ppath: string) {
  let _indir = path.join(indir, ppath);
  let _outdir = path.join(outdir, ppath);
  describe('check ' + ppath, () => {
    it('should be ok', () => {
      firststep();
      var model = new Model(_indir);
      assert.isTrue(model.proccess(Setting.validatorJSON), model.getLastDisplayError());
      _.each(Setting.templates, (val, key) => {
        let f = val.proccess(model, _outdir);
        assert.isTrue(val.proccess(model, _outdir), val.getLastDisplayError());
        assert.doesNotThrow(() => $t.assertCmpText(_indir, _outdir, val.getInfo()));
      })
    });
  });
}

ok_all_tests(path.join('pn-model'));

ok_all_tests(path.join('mcgen-config', 'test1'));

ok_all_tests(path.join('example'));

ok_all_tests(path.join('import', 'ok2'));

ok_all_tests(path.join('import', 'crosslevel'));

describe('model shouldt be properties duplication', () => {
  let _indir = path.join(indir, 'dubl-model-prop');
  let _outdir = path.join(outdir, 'dubl-model-prop');
  it('should error', () => {
    firststep();
    var model = new Model(_indir);
    assert.isFalse(model.proccess(Setting.validatorJSON), model.getLastDisplayError());
  });
});

describe('check not import error', () => {
  let _indir = path.join(indir, 'import', 'errornotadd');
  let _outdir = path.join(outdir, 'import', 'errornotadd');
  it('should error', () => {
    firststep();
    var model = new Model(_indir);
    assert.isFalse(model.proccess(Setting.validatorJSON), model.getLastDisplayError());
  });
});

describe('const shouldt be type in model', () => {
  let _indir = path.join(indir, 'const-type-err');
  let _outdir = path.join(outdir, 'const-type-err');
  it('should error', () => {
    firststep();
    var model = new Model(_indir);
    assert.isFalse(model.proccess(Setting.validatorJSON), model.getLastDisplayError());
  });
});

describe('check big project', () => {
  let _indir = path.join(indir, 'big-proj');
  let _outdir = path.join(outdir, 'big-proj');
  it('should ok', () => {
    firststep();
    $t.eachTempl(_indir, _outdir, { 'php': {}, 'eloquent-php': {} }, (val) => {
      assert.doesNotThrow(() => $t.assertCmpText(_indir, _outdir, val.getInfo()));
    });
  });
});

describe('check only enums', () => {
  let _indir = path.join(indir, 'enums');
  let _outdir = path.join(outdir, 'enums');
  it('should ok', () => {
    firststep();
    var model = new Model(_indir);
    assert.isTrue(model.proccess(Setting.validatorJSON), model.getLastDisplayError());
    let val = Setting.templates['php'];
    assert.isTrue(val.proccess(model, _outdir), val.getLastDisplayError());
  });
});

describe('check eloquent', () => {
  let _indir = path.join(indir, 'eloquent');
  let _outdir = path.join(outdir, 'eloquent');
  it('should eloquent ok', () => {
    firststep();
    var model = new Model(_indir);
    assert.isTrue(model.proccess(Setting.validatorJSON), model.getLastDisplayError());
    let val = Setting.templates['eloquent-php'];
    assert.isTrue(val.proccess(model, _outdir), val.getLastDisplayError());
    val = Setting.templates['php'];
    assert.isTrue(val.proccess(model, _outdir), val.getLastDisplayError());
  });
});

describe('check not support enums', () => {
  let _indir = path.join(indir, 'enums-const-php');
  let _outdir = path.join(outdir, 'enums-const-php');
  it('should in php int instead of enum', () => {
    firststep();
    var model = new Model(_indir);
    assert.isTrue(model.proccess(Setting.validatorJSON), model.getLastDisplayError());
    let val = Setting.templates['php'];
    assert.isTrue(val.proccess(model, _outdir), val.getLastDisplayError());
    let body: string = fs.readFileSync(path.join(_outdir, 'model.php'), 'utf8');
    assert.isTrue(body.indexOf('@property int $prop2') >= 0, `Not find '@property int $prop2'`);
  });
});

describe('Model import ok', () => {
  let _indir = path.join(indir, 'import', 'ok');
  let _outdir = path.join(outdir, 'import', 'ok');
  it('assert (json, yaml) import/ok', () => {
    firststep();
    Setting.mp_idsTemplate = new CmdUtils().parseids('php:ver=5');
    var model = new Model(_indir);
    assert.isTrue(model.proccess(Setting.validatorJSON), model.getLastDisplayError());
    _.each(Setting.templates, (val, key) => {
      val.getInfo()
      assert.isTrue(val.proccess(model, _outdir), val.getLastDisplayError());
    })
    Setting.mp_idsTemplate = {};
  });
});

describe('check type', () => {
  beforeEach(() => {
    firststep();
  });

  it('should error type', () => {
    let _indir = path.join(indir, 'type-check', 'dublication');
    let _outdir = path.join(outdir, 'type-check', 'dublication');
    var model = new Model(_indir);
    assert.isFalse(model.proccess(Setting.validatorJSON), model.getLastDisplayError());
  });
  it('should empty model ok', () => {
    let _indir = path.join(indir, 'type-check', 'emptymodel');
    let _outdir = path.join(outdir, 'type-check', 'emptymodel');
    var model = new Model(_indir);
    assert.isTrue(model.proccess(Setting.validatorJSON), model.getLastDisplayError());
  });
  it('should error type', () => {
    let _indir = path.join(indir, 'type-check', 'error-notype');
    let _outdir = path.join(outdir, 'type-check', 'error-notype');
    var model = new Model(_indir);
    assert.isFalse(model.proccess(Setting.validatorJSON), model.getLastDisplayError());
  });
  it('should error arrayparam', () => {
    let _indir = path.join(indir, 'type-check', 'error-arrayparam');
    let _outdir = path.join(outdir, 'type-check', 'error-arrayparam');
    var model = new Model(_indir);
    assert.isFalse(model.proccess(Setting.validatorJSON), model.getLastDisplayError());
  });
  it('should ok import type', () => {
    let _indir = path.join(indir, 'type-check', 'ok-import');
    let _outdir = path.join(outdir, 'type-check', 'ok-import');
    var model = new Model(_indir);
    assert.isTrue(model.proccess(Setting.validatorJSON), model.getLastDisplayError());
  });
});

describe('Model import error validation', () => {
  let _indir = path.join(indir, 'import', 'error');
  let _outdir = path.join(outdir, 'import', 'error');
  beforeEach(() => {
    firststep();
  });
  it('assert (json, yaml) import/error', () => {
    var model = new Model(_indir);
    assert.isFalse(model.proccess(Setting.validatorJSON), model.getLastDisplayError());
  });
});

describe('Parse cmd', () => {
  beforeEach(() => {
    firststep();
  });
  it('parse --id *', () => {
    let val = new CmdUtils().parseids('*');
    assert.deepEqual(val, {});
  })
  it('parse --id php', () => {
    let val = new CmdUtils().parseids('php');
    let valeq: Ids = {};
    valeq['php'] = {};
    assert.deepEqual(val, valeq);
  })
  it('parse --id php,cs', () => {
    let val = new CmdUtils().parseids('php,cs');
    let valeq: Ids = {};
    valeq['php'] = {};
    valeq['cs'] = {};
    assert.deepEqual(val, valeq);
  })
  it('parse --id php:ver=5,cs:ident=2', () => {
    let val = new CmdUtils().parseids('php:ver=5;data=5,cs:ident=2');
    let valeq: Ids = {};

    valeq['php'] = {
      'ver': '5',
      'data': '5'
    };
    valeq['cs'] = {
      'ident': '2'
    };
    assert.deepEqual(val, valeq);
  })
});

describe('Proccess', () => {
  var _indir = path.join(indir, 'import', 'ok');
  var _outdir = path.join(outdir, 'import', 'ok');

  it('exec via import', (done) => {
    child_process.exec(`node ${path.join(Setting.__root, 'lib', 'mcgen')}  build --indir ${_indir} --outdir ${_outdir}`, (err, stdout, stderr) => {
      if (err) return done(err);
      if (stdout.indexOf('Usage:') >= 0) return done('Error run'); //if help
      done();
    });
  });

});


text:
"""
kombu.transport.redis
=====================

Redis transport.

"""
from __future__ import absolute_import

import numbers
import socket

from bisect import bisect
from collections import namedtuple
from contextlib import contextmanager
from time import time

from amqp import promise

from kombu.exceptions import InconsistencyError, VersionMismatch
from kombu.five import Empty, values, string_t
from kombu.log import get_logger
from kombu.utils import cached_property, uuid
from kombu.utils.eventio import poll, READ, ERR
from kombu.utils.encoding import bytes_to_str
from kombu.utils.json import loads, dumps
from kombu.utils.url import _parse_url

NO_ROUTE_ERROR = """
Cannot route message for exchange {0!r}: Table empty or key no longer exists.
Probably the key ({1!r}) has been removed from the Redis database.
"""

try:
    from billiard.util import register_after_fork
except ImportError:  # pragma: no cover
    try:
        from multiprocessing.util import register_after_fork  # noqa
    except ImportError:
        def register_after_fork(*args, **kwargs):  # noqa
            pass

try:
    import redis
except ImportError:  # pragma: no cover
    redis = None     # noqa

from . import virtual

logger = get_logger('kombu.transport.redis')
crit, warn = logger.critical, logger.warn

DEFAULT_PORT = 6379
DEFAULT_DB = 0

PRIORITY_STEPS = [0, 3, 6, 9]

error_classes_t = namedtuple('error_classes_t', (
    'connection_errors', 'channel_errors',
))

# This implementation may seem overly complex, but I assure you there is
# a good reason for doing it this way.
#
# Consuming from several connections enables us to emulate channels,
# which means we can have different service guarantees for individual
# channels.
#
# So we need to consume messages from multiple connections simultaneously,
# and using epoll means we don't have to do so using multiple threads.
#
# Also it means we can easily use PUBLISH/SUBSCRIBE to do fanout
# exchanges (broadcast), as an alternative to pushing messages to fanout-bound
# queues manually.

def get_redis_error_classes():
    from redis import exceptions
    # This exception suddenly changed name between redis-py versions
    if hasattr(exceptions, 'InvalidData'):
        DataError = exceptions.InvalidData
    else:
        DataError = exceptions.DataError
    return error_classes_t(
        (virtual.Transport.connection_errors + (
            InconsistencyError,
            socket.error,
            IOError,
            OSError,
            exceptions.ConnectionError,
            exceptions.AuthenticationError,
            exceptions.TimeoutError)),
        (virtual.Transport.channel_errors + (
            DataError,
            exceptions.InvalidResponse,
            exceptions.ResponseError)),
    )

class MutexHeld(Exception):
    pass

@contextmanager
def Mutex(client, name, expire):
    lock_id = uuid()
    i_won = client.setnx(name, lock_id)
    try:
        if i_won:
            client.expire(name, expire)
            yield
        else:
            if not client.ttl(name):
                client.expire(name, expire)
            raise MutexHeld()
    finally:
        if i_won:
            pipe = client.pipeline(True)
            try:
                pipe.watch(name)
                if pipe.get(name) == lock_id:
                    pipe.multi()
                    pipe.delete(name)
                    pipe.execute()
                pipe.unwatch()
            except redis.WatchError:
                pass

class QoS(virtual.QoS):
    restore_at_shutdown = True

    def __init__(self, *args, **kwargs):
        super(QoS, self).__init__(*args, **kwargs)
        self._vrestore_count = 0

    def append(self, message, delivery_tag):
        delivery = message.delivery_info
        EX, RK = delivery['exchange'], delivery['routing_key']
        with self.pipe_or_acquire() as pipe:
            pipe.zadd(self.unacked_index_key, delivery_tag, time()) \
                .hset(self.unacked_key, delivery_tag,
                      dumps([message._raw, EX, RK])) \
                .execute()
            super(QoS, self).append(message, delivery_tag)

    def restore_unacked(self, client=None):
        with self.channel.conn_or_acquire(client) as client:
            for tag in self._delivered:
                self.restore_by_tag(tag, client=client)
        self._delivered.clear()

    def ack(self, delivery_tag):
        self._remove_from_indices(delivery_tag).execute()
        super(QoS, self).ack(delivery_tag)

    def reject(self, delivery_tag, requeue=False):
        if requeue:
            self.restore_by_tag(delivery_tag, leftmost=True)
        self.ack(delivery_tag)

    @contextmanager
    def pipe_or_acquire(self, pipe=None):
        if pipe:
            yield pipe
        else:
            with self.channel.conn_or_acquire() as client:
                yield client.pipeline()

    def _remove_from_indices(self, delivery_tag, pipe=None):
        with self.pipe_or_acquire(pipe) as pipe:
            return pipe.zrem(self.unacked_index_key, delivery_tag) \
                       .hdel(self.unacked_key, delivery_tag)

    def restore_visible(self, start=0, num=10, interval=10):
        self._vrestore_count += 1
        if (self._vrestore_count - 1) % interval:
            return
        with self.channel.conn_or_acquire() as client:
            ceil = time() - self.visibility_timeout
            try:
                with Mutex(client, self.unacked_mutex_key,
                           self.unacked_mutex_expire):
                    visible = client.zrevrangebyscore(
                        self.unacked_index_key, ceil, 0,
                        start=num and start, num=num, withscores=True)
                    for tag, score in visible or []:
                        self.restore_by_tag(tag, client)
            except MutexHeld:
                pass

    def restore_by_tag(self, tag, client=None, leftmost=False):
        with self.channel.conn_or_acquire(client) as client:
            p, _, _ = self._remove_from_indices(
                tag, client.pipeline().hget(self.unacked_key, tag)).execute()
            if p:
                M, EX, RK = loads(bytes_to_str(p))  # json is unicode
                self.channel._do_restore_message(M, EX, RK, client, leftmost)

    @cached_property
    def unacked_key(self):
        return self.channel.unacked_key

    @cached_property
    def unacked_index_key(self):
        return self.channel.unacked_index_key

    @cached_property
    def unacked_mutex_key(self):
        return self.channel.unacked_mutex_key

    @cached_property
    def unacked_mutex_expire(self):
        return self.channel.unacked_mutex_expire

    @cached_property
    def visibility_timeout(self):
        return self.channel.visibility_timeout

class MultiChannelPoller(object):
    eventflags = READ | ERR

    #: Set by :meth:`get` while reading from the socket.
    _in_protected_read = False

    #: Set of one-shot callbacks to call after reading from socket.
    after_read = None

    def __init__(self):
        # active channels
        self._channels = set()
        # file descriptor -> channel map.
        self._fd_to_chan = {}
        # channel -> socket map
        self._chan_to_sock = {}
        # poll implementation (epoll/kqueue/select)
        self.poller = poll()
        # one-shot callbacks called after reading from socket.
        self.after_read = set()

    def close(self):
        for fd in values(self._chan_to_sock):
            try:
                self.poller.unregister(fd)
            except (KeyError, ValueError):
                pass
        self._channels.clear()
        self._fd_to_chan.clear()
        self._chan_to_sock.clear()

    def add(self, channel):
        self._channels.add(channel)

    def discard(self, channel):
        self._channels.discard(channel)

    def _on_connection_disconnect(self, connection):
        try:
            self.poller.unregister(connection._sock)
        except (AttributeError, TypeError):
            pass

    def _register(self, channel, client, type):
        if (channel, client, type) in self._chan_to_sock:
            self._unregister(channel, client, type)
        if client.connection._sock is None:   # not connected yet.
            client.connection.connect()
        sock = client.connection._sock
        self._fd_to_chan[sock.fileno()] = (channel, type)
        self._chan_to_sock[(channel, client, type)] = sock
        self.poller.register(sock, self.eventflags)

    def _unregister(self, channel, client, type):
        self.poller.unregister(self._chan_to_sock[(channel, client, type)])

    def _register_BRPOP(self, channel):
        """enable BRPOP mode for channel."""
        ident = channel, channel.client, 'BRPOP'
        if channel.client.connection._sock is None or \
                ident not in self._chan_to_sock:
            channel._in_poll = False
            self._register(*ident)

        if not channel._in_poll:  # send BRPOP
            channel._brpop_start()

    def _register_LISTEN(self, channel):
        """enable LISTEN mode for channel."""
        if channel.subclient.connection._sock is None:
            channel._in_listen = False
            self._register(channel, channel.subclient, 'LISTEN')
        if not channel._in_listen:
            channel._subscribe()  # send SUBSCRIBE

    def on_poll_start(self):
        for channel in self._channels:
            if channel.active_queues:           # BRPOP mode?
                if channel.qos.can_consume():
                    self._register_BRPOP(channel)
            if channel.active_fanout_queues:    # LISTEN mode?
                self._register_LISTEN(channel)

    def on_poll_init(self, poller):
        self.poller = poller
        for channel in self._channels:
            return channel.qos.restore_visible(
                num=channel.unacked_restore_limit,
            )

    def maybe_restore_messages(self):
        for channel in self._channels:
            if channel.active_queues:
                # only need to do this once, as they are not local to channel.
                return channel.qos.restore_visible(
                    num=channel.unacked_restore_limit,
                )

    def on_readable(self, fileno):
        chan, type = self._fd_to_chan[fileno]
        if chan.qos.can_consume():
            return chan.handlers[type]()

    def handle_event(self, fileno, event):
        if event & READ:
            return self.on_readable(fileno), self
        elif event & ERR:
            chan, type = self._fd_to_chan[fileno]
            chan._poll_error(type)

    def get(self, timeout=None):
        self._in_protected_read = True
        try:
            for channel in self._channels:
                if channel.active_queues:           # BRPOP mode?
                    if channel.qos.can_consume():
                        self._register_BRPOP(channel)
                if channel.active_fanout_queues:    # LISTEN mode?
                    self._register_LISTEN(channel)

            events = self.poller.poll(timeout)
            for fileno, event in events or []:
                ret = self.handle_event(fileno, event)
                if ret:
                    return ret

            # - no new data, so try to restore messages.
            # - reset active redis commands.
            self.maybe_restore_messages()

            raise Empty()
        finally:
            self._in_protected_read = False
            while self.after_read:
                try:
                    fun = self.after_read.pop()
                except KeyError:
                    break
                else:
                    fun()

    @property
    def fds(self):
        return self._fd_to_chan

class Channel(virtual.Channel):
    QoS = QoS

    _client = None
    _subclient = None
    supports_fanout = True
    keyprefix_queue = '_kombu.binding.%s'
    keyprefix_fanout = '/{db}.'
    sep = '\x06\x16'
    _in_poll = False
    _in_listen = False
    _fanout_queues = {}
    ack_emulation = True
    unacked_key = 'unacked'
    unacked_index_key = 'unacked_index'
    unacked_mutex_key = 'unacked_mutex'
    unacked_mutex_expire = 300  # 5 minutes
    unacked_restore_limit = None
    visibility_timeout = 3600   # 1 hour
    priority_steps = PRIORITY_STEPS
    socket_timeout = None
    max_connections = 10
    #: Transport option to enable disable fanout keyprefix.
    #: Should be enabled by default, but that is not
    #: backwards compatible.  Can also be string, in which
    #: case it changes the default prefix ('/{db}.') into to something
    #: else.  The prefix must include a leading slash and a trailing dot.
    fanout_prefix = False

    #: If enabled the fanout exchange will support patterns in routing
    #: and binding keys (like a topic exchange but using PUB/SUB).
    #: This will be enabled by default in a future version.
    fanout_patterns = False
    _pool = None

    from_transport_options = (
        virtual.Channel.from_transport_options +
        ('ack_emulation',
         'unacked_key',
         'unacked_index_key',
         'unacked_mutex_key',
         'unacked_mutex_expire',
         'visibility_timeout',
         'unacked_restore_limit',
         'fanout_prefix',
         'fanout_patterns',
         'socket_timeout',
         'max_connections',
         'priority_steps')  # <-- do not add comma here!
    )

    def __init__(self, *args, **kwargs):
        super_ = super(Channel, self)
        super_.__init__(*args, **kwargs)

        if not self.ack_emulation:  # disable visibility timeout
            self.QoS = virtual.QoS

        self._queue_cycle = []
        self.Client = self._get_client()
        self.ResponseError = self._get_response_error()
        self.active_fanout_queues = set()
        self.auto_delete_queues = set()
        self._fanout_to_queue = {}
        self.handlers = {'BRPOP': self._brpop_read, 'LISTEN': self._receive}

        if self.fanout_prefix:
            if isinstance(self.fanout_prefix, string_t):
                self.keyprefix_fanout = self.fanout_prefix
        else:
            # previous versions did not set a fanout, so cannot enable
            # by default.
            self.keyprefix_fanout = ''

        # Evaluate connection.
        try:
            self.client.info()
        except Exception:
            if self._pool:
                self._pool.disconnect()
            raise

        self.connection.cycle.add(self)  # add to channel poller.
        # copy errors, in case channel closed but threads still
        # are still waiting for data.
        self.connection_errors = self.connection.connection_errors

        register_after_fork(self, self._after_fork)

    def _after_fork(self):
        if self._pool is not None:
            self._pool.disconnect()

    def _on_connection_disconnect(self, connection):
        if self.connection and self.connection.cycle:
            self.connection.cycle._on_connection_disconnect(connection)

    def _do_restore_message(self, payload, exchange, routing_key,
                            client=None, leftmost=False):
        with self.conn_or_acquire(client) as client:
            try:
                try:
                    payload['headers']['redelivered'] = True
                except KeyError:
                    pass
                for queue in self._lookup(exchange, routing_key):
                    (client.lpush if leftmost else client.rpush)(
                        queue, dumps(payload),
                    )
            except Exception:
                crit('Could not restore message: %r', payload, exc_info=True)

    def _restore(self, message, leftmost=False):
        if not self.ack_emulation:
            return super(Channel, self)._restore(message)
        tag = message.delivery_tag
        with self.conn_or_acquire() as client:
            P, _ = client.pipeline() \
                .hget(self.unacked_key, tag) \
                .hdel(self.unacked_key, tag) \
                .execute()
            if P:
                M, EX, RK = loads(bytes_to_str(P))  # json is unicode
                self._do_restore_message(M, EX, RK, client, leftmost)

    def _restore_at_beginning(self, message):
        return self._restore(message, leftmost=True)

    def basic_consume(self, queue, *args, **kwargs):
        if queue in self._fanout_queues:
            exchange, _ = self._fanout_queues[queue]
            self.active_fanout_queues.add(queue)
            self._fanout_to_queue[exchange] = queue
        ret = super(Channel, self).basic_consume(queue, *args, **kwargs)
        self._update_cycle()
        return ret

    def basic_cancel(self, consumer_tag):
        # If we are busy reading messages we may experience
        # a race condition where a message is consumed after
        # cancelling, so we must delay this operation until reading
        # is complete (Issue celery/celery#1773).
        connection = self.connection
        if connection:
            if connection.cycle._in_protected_read:
                return connection.cycle.after_read.add(
                    promise(self._basic_cancel, (consumer_tag,)),
                )
            return self._basic_cancel(consumer_tag)

    def _basic_cancel(self, consumer_tag):
        try:
            queue = self._tag_to_queue[consumer_tag]
        except KeyError:
            return
        try:
            self.active_fanout_queues.remove(queue)
        except KeyError:
            pass
        else:
            self._unsubscribe_from(queue)
        try:
            exchange, _ = self._fanout_queues[queue]
            self._fanout_to_queue.pop(exchange)
        except KeyError:
            pass
        ret = super(Channel, self).basic_cancel(consumer_tag)
        self._update_cycle()
        return ret

    def _get_publish_topic(self, exchange, routing_key):
        if routing_key and self.fanout_patterns:
            return ''.join([self.keyprefix_fanout, exchange, '/', routing_key])
        return ''.join([self.keyprefix_fanout, exchange])

    def _get_subscribe_topic(self, queue):
        exchange, routing_key = self._fanout_queues[queue]
        return self._get_publish_topic(exchange, routing_key)

    def _subscribe(self):
        keys = [self._get_subscribe_topic(queue)
                for queue in self.active_fanout_queues]
        if not keys:
            return
        c = self.subclient
        if c.connection._sock is None:
            c.connection.connect()
        self._in_listen = True
        c.psubscribe(keys)

    def _unsubscribe_from(self, queue):
        topic = self._get_subscribe_topic(queue)
        c = self.subclient
        should_disconnect = False
        if c.connection._sock is None:
            c.connection.connect()
            should_disconnect = True
        try:
            c.unsubscribe([topic])
        finally:
            if should_disconnect and c.connection:
                c.connection.disconnect()

    def _handle_message(self, client, r):
        if bytes_to_str(r[0]) == 'unsubscribe' and r[2] == 0:
            client.subscribed = False
        elif bytes_to_str(r[0]) == 'pmessage':
            return {'type':    r[0], 'pattern': r[1],
                    'channel': r[2], 'data':    r[3]}
        else:
            return {'type':    r[0], 'pattern': None,
                    'channel': r[1], 'data':    r[2]}

    def _receive(self):
        c = self.subclient
        response = None
        try:
            response = c.parse_response()
        except self.connection_errors:
            self._in_listen = False
            raise Empty()
        if response is not None:
            payload = self._handle_message(c, response)
            if bytes_to_str(payload['type']).endswith('message'):
                channel = bytes_to_str(payload['channel'])
                if payload['data']:
                    if channel[0] == '/':
                        _, _, channel = channel.partition('.')
                    try:
                        message = loads(bytes_to_str(payload['data']))
                    except (TypeError, ValueError):
                        warn('Cannot process event on channel %r: %s',
                             channel, repr(payload)[:4096], exc_info=1)
                        raise Empty()
                    exchange = channel.split('/', 1)[0]
                    return message, self._fanout_to_queue[exchange]
        raise Empty()

    def _brpop_start(self, timeout=1):
        queues = self._consume_cycle()
        if not queues:
            return
        keys = [self._q_for_pri(queue, pri) for pri in PRIORITY_STEPS
                for queue in queues] + [timeout or 0]
        self._in_poll = True
        self.client.connection.send_command('BRPOP', *keys)

    def _brpop_read(self, **options):
        try:
            try:
                dest__item = self.client.parse_response(self.client.connection,
                                                        'BRPOP',
                                                        **options)
            except self.connection_errors:
                # if there's a ConnectionError, disconnect so the next
                # iteration will reconnect automatically.
                self.client.connection.disconnect()
                raise Empty()
            if dest__item:
                dest, item = dest__item
                dest = bytes_to_str(dest).rsplit(self.sep, 1)[0]
                self._rotate_cycle(dest)
                return loads(bytes_to_str(item)), dest
            else:
                raise Empty()
        finally:
            self._in_poll = False

    def _poll_error(self, type, **options):
        if type == 'LISTEN':
            self.subclient.parse_response()
        else:
            self.client.parse_response(self.client.connection, type)

    def _get(self, queue):
        with self.conn_or_acquire() as client:
            for pri in PRIORITY_STEPS:
                item = client.rpop(self._q_for_pri(queue, pri))
                if item:
                    return loads(bytes_to_str(item))
            raise Empty()

    def _size(self, queue):
        with self.conn_or_acquire() as client:
            cmds = client.pipeline()
            for pri in PRIORITY_STEPS:
                cmds = cmds.llen(self._q_for_pri(queue, pri))
            sizes = cmds.execute()
            return sum(size for size in sizes
                       if isinstance(size, numbers.Integral))

    def _q_for_pri(self, queue, pri):
        pri = self.priority(pri)
        return '%s%s%s' % ((queue, self.sep, pri) if pri else (queue, '', ''))

    def priority(self, n):
        steps = self.priority_steps
        return steps[bisect(steps, n) - 1]

    def _put(self, queue, message, **kwargs):
        """Deliver message."""
        pri = self._get_message_priority(message)

        with self.conn_or_acquire() as client:
            client.lpush(self._q_for_pri(queue, pri), dumps(message))

    def _put_fanout(self, exchange, message, routing_key, **kwargs):
        """Deliver fanout message."""
        with self.conn_or_acquire() as client:
            client.publish(
                self._get_publish_topic(exchange, routing_key),
                dumps(message),
            )

    def _new_queue(self, queue, auto_delete=False, **kwargs):
        if auto_delete:
            self.auto_delete_queues.add(queue)

    def _queue_bind(self, exchange, routing_key, pattern, queue):
        if self.typeof(exchange).type == 'fanout':
            # Mark exchange as fanout.
            self._fanout_queues[queue] = (
                exchange, routing_key.replace('#', '*'),
            )
        with self.conn_or_acquire() as client:
            client.sadd(self.keyprefix_queue % (exchange,),
                        self.sep.join([routing_key or '',
                                       pattern or '',
                                       queue or '']))

    def _delete(self, queue, exchange, routing_key, pattern, *args):
        self.auto_delete_queues.discard(queue)
        with self.conn_or_acquire() as client:
            client.srem(self.keyprefix_queue % (exchange,),
                        self.sep.join([routing_key or '',
                                       pattern or '',
                                       queue or '']))
            cmds = client.pipeline()
            for pri in PRIORITY_STEPS:
                cmds = cmds.delete(self._q_for_pri(queue, pri))
            cmds.execute()

    def _has_queue(self, queue, **kwargs):
        with self.conn_or_acquire() as client:
            cmds = client.pipeline()
            for pri in PRIORITY_STEPS:
                cmds = cmds.exists(self._q_for_pri(queue, pri))
            return any(cmds.execute())

    def get_table(self, exchange):
        key = self.keyprefix_queue % exchange
        with self.conn_or_acquire() as client:
            values = client.smembers(key)
            if not values:
                raise InconsistencyError(NO_ROUTE_ERROR.format(exchange, key))
            return [tuple(bytes_to_str(val).split(self.sep)) for val in values]

    def _purge(self, queue):
        with self.conn_or_acquire() as client:
            cmds = client.pipeline()
            for pri in PRIORITY_STEPS:
                priq = self._q_for_pri(queue, pri)
                cmds = cmds.llen(priq).delete(priq)
            sizes = cmds.execute()
            return sum(sizes[::2])

    def close(self):
        if self._pool:
            self._pool.disconnect()
        if not self.closed:
            # remove from channel poller.
            self.connection.cycle.discard(self)

            # delete fanout bindings
            for queue in self._fanout_queues:
                if queue in self.auto_delete_queues:
                    self.queue_delete(queue)

            self._close_clients()

        super(Channel, self).close()

    def _close_clients(self):
        # Close connections
        for attr in 'client', 'subclient':
            try:
                self.__dict__[attr].connection.disconnect()
            except (KeyError, AttributeError, self.ResponseError):
                pass

    def _prepare_virtual_host(self, vhost):
        if not isinstance(vhost, numbers.Integral):
            if not vhost or vhost == '/':
                vhost = DEFAULT_DB
            elif vhost.startswith('/'):
                vhost = vhost[1:]
            try:
                vhost = int(vhost)
            except ValueError:
                raise ValueError(
                    'Database is int between 0 and limit - 1, not {0}'.format(
                        vhost,
                    ))
        return vhost

    def _connparams(self):
        conninfo = self.connection.client
        connparams = {'host': conninfo.hostname or '127.0.0.1',
                      'port': conninfo.port or DEFAULT_PORT,
                      'virtual_host': conninfo.virtual_host,
                      'password': conninfo.password,
                      'max_connections': self.max_connections,
                      'socket_timeout': self.socket_timeout}
        host = connparams['host']
        if '://' in host:
            scheme, _, _, _, _, path, query = _parse_url(host)
            if scheme == 'socket':
                connparams.update({
                    'connection_class': redis.UnixDomainSocketConnection,
                    'path': '/' + path}, **query)
            connparams.pop('host', None)
            connparams.pop('port', None)
        connparams['db'] = self._prepare_virtual_host(
            connparams.pop('virtual_host', None))

        channel = self
        connection_cls = (
            connparams.get('connection_class') or
            redis.Connection
            )

        class Connection(connection_cls):
            def disconnect(self):
                channel._on_connection_disconnect(self)
                super(Connection, self).disconnect()
        connparams['connection_class'] = Connection

        return connparams

    def _create_client(self):
        return self.Client(connection_pool=self.pool)

    def _get_pool(self):
        params = self._connparams()
        self.keyprefix_fanout = self.keyprefix_fanout.format(db=params['db'])
        return redis.ConnectionPool(**params)

    def _get_client(self):
        if redis.VERSION < (2, 4, 4):
            raise VersionMismatch(
                'Redis transport requires redis-py versions 2.4.4 or later. '
                'You have {0.__version__}'.format(redis))

        # KombuRedis maintains a connection attribute on it's instance and
        # uses that when executing commands
        # This was added after redis-py was changed.
        class KombuRedis(redis.Redis):  # pragma: no cover

            def __init__(self, *args, **kwargs):
                super(KombuRedis, self).__init__(*args, **kwargs)
                self.connection = self.connection_pool.get_connection('_')

        return KombuRedis

    @contextmanager
    def conn_or_acquire(self, client=None):
        if client:
            yield client
        else:
            if self._in_poll:
                client = self._create_client()
                try:
                    yield client
                finally:
                    self.pool.release(client.connection)
            else:
                yield self.client

    @property
    def pool(self):
        if self._pool is None:
            self._pool = self._get_pool()
        return self._pool

    @cached_property
    def client(self):
        """Client used to publish messages, BRPOP etc."""
        return self._create_client()

    @cached_property
    def subclient(self):
        """Pub/Sub connection used to consume fanout queues."""
        client = self._create_client()
        pubsub = client.pubsub()
        pool = pubsub.connection_pool
        pubsub.connection = pool.get_connection('pubsub', pubsub.shard_hint)
        return pubsub

    def _update_cycle(self):
        """Update fair cycle between queues.

        We cycle between queues fairly to make sure that
        each queue is equally likely to be consumed from,
        so that a very busy queue will not block others.

        This works by using Redis's `BRPOP` command and
        by rotating the most recently used queue to the
        and of the list.  See Kombu github issue #166 for
        more discussion of this method.

        """
        self._queue_cycle = list(self.active_queues)

    def _consume_cycle(self):
        """Get a fresh list of queues from the queue cycle."""
        active = len(self.active_queues)
        return self._queue_cycle[0:active]

    def _rotate_cycle(self, used):
        """Move most recently used queue to end of list."""
        cycle = self._queue_cycle
        try:
            cycle.append(cycle.pop(cycle.index(used)))
        except ValueError:
            pass

    def _get_response_error(self):
        from redis import exceptions
        return exceptions.ResponseError

    @property
    def active_queues(self):
        """Set of queues being consumed from (excluding fanout queues)."""
        return {queue for queue in self._active_queues
                if queue not in self.active_fanout_queues}

class Transport(virtual.Transport):
    Channel = Channel

    polling_interval = None  # disable sleep between unsuccessful polls.
    default_port = DEFAULT_PORT
    driver_type = 'redis'
    driver_name = 'redis'

    implements = virtual.Transport.implements.extend(
        async=True,
        exchange_types=frozenset(['direct', 'topic', 'fanout'])
    )

    def __init__(self, *args, **kwargs):
        if redis is None:
            raise ImportError('Missing redis library (pip install redis)')
        super(Transport, self).__init__(*args, **kwargs)

        # Get redis-py exceptions.
        self.connection_errors, self.channel_errors = self._get_errors()
        # All channels share the same poller.
        self.cycle = MultiChannelPoller()

    def driver_version(self):
        return redis.__version__

    def register_with_event_loop(self, connection, loop):
        cycle = self.cycle
        cycle.on_poll_init(loop.poller)
        cycle_poll_start = cycle.on_poll_start
        add_reader = loop.add_reader
        on_readable = self.on_readable

        def _on_disconnect(connection):
            if connection._sock:
                loop.remove(connection._sock)
        cycle._on_connection_disconnect = _on_disconnect

        def on_poll_start():
            cycle_poll_start()
            [add_reader(fd, on_readable, fd) for fd in cycle.fds]
        loop.on_tick.add(on_poll_start)
        loop.call_repeatedly(10, cycle.maybe_restore_messages)

    def on_readable(self, fileno):
        """Handle AIO event for one of our file descriptors."""
        item = self.cycle.on_readable(fileno)
        if item:
            message, queue = item
            if not queue or queue not in self._callbacks:
                raise KeyError(
                    'Message for queue {0!r} without consumers: {1}'.format(
                        queue, message))
            self._callbacks[queue](message)

    def _get_errors(self):
        """Utility to import redis-py's exceptions at runtime."""
        return get_redis_error_classes()


text:
<?php

namespace Ddeboer\DataImport\ItemConverter;

/**
 * An item converter takes an input item from a reader, and returns a modified item.
 *
 * @author David de Boer <david@ddeboer.nl>
 */
interface ItemConverterInterface
{
    /**
     * Convert an input
     *
     * @param mixed $input Input
     *
     * @return array|null the modified input or null to remove it
     */
    public function convert($input);
}


text:
namespace OfficeSpace
{
    using System;
    using System.Linq;

    public static class Program
    {
        private static int[] maxPathFrom;

        public static void Main()
        {
            var n = int.Parse(Console.ReadLine());
            var time = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            var adjacencyMatrix = new bool[n, n]; // 0-based matrix to represent the graph
            for (var i = 0; i < n; i++)
            {
                var requirements = Console.ReadLine().Split(' ').Select(int.Parse);
                if (requirements.First() != 0)
                {
                    foreach (var requirement in requirements)
                    {
                        adjacencyMatrix[requirement - 1, i] = true;
                    }
                }
            }

            var minTime = FindMinTime(n, time, adjacencyMatrix);
            Console.WriteLine(minTime);
        }

        private static int FindMinTime(int n, int[] time, bool[,] adjacencyMatrix)
        {
            maxPathFrom = new int[n];
            var loopFound = false;

            var maxPath = 0;
            for (var i = 0; i < n; i++)
            {
                maxPath = Math.Max(Dfs(i, time, adjacencyMatrix, new bool[n], ref loopFound), maxPath);
                if (loopFound)
                {
                    return -1;
                }
            }

            return maxPath;
        }

        private static int Dfs(int node, int[] time, bool[,] adjacencyMatrix, bool[] visited, ref bool loopFound)
        {
            if (visited[node])
            {
                loopFound = true;
                return 0;
            }

            if (!visited[node] && maxPathFrom[node] > 0)
            {
                return maxPathFrom[node];
            }

            visited[node] = true;
            maxPathFrom[node] = time[node];
            for (var v = 0; v < time.Length; v++)
            {
                if (adjacencyMatrix[v, node])
                {
                    maxPathFrom[node] = Math.Max(
                        maxPathFrom[node],
                        Dfs(v, time, adjacencyMatrix, visited, ref loopFound) + time[node]);
                }
            }

            visited[node] = false;
            return maxPathFrom[node];
        }
    }
}


text:
namespace cpp_client
{

namespace chess
{

Move_::Move_(std::initializer_list<std::pair<std::string, Any&&>> init) :
    Game_object_{
        {"captured", Any{std::decay<decltype(captured)>::type{}}},
        {"fromFile", Any{std::decay<decltype(from_file)>::type{}}},
        {"fromRank", Any{std::decay<decltype(from_rank)>::type{}}},
        {"piece", Any{std::decay<decltype(piece)>::type{}}},
        {"promotion", Any{std::decay<decltype(promotion)>::type{}}},
        {"san", Any{std::decay<decltype(san)>::type{}}},
        {"toFile", Any{std::decay<decltype(to_file)>::type{}}},
        {"toRank", Any{std::decay<decltype(to_rank)>::type{}}},
    },
    captured(variables_["captured"].as<std::decay<decltype(captured)>::type>()),
    from_file(variables_["fromFile"].as<std::decay<decltype(from_file)>::type>()),
    from_rank(variables_["fromRank"].as<std::decay<decltype(from_rank)>::type>()),
    piece(variables_["piece"].as<std::decay<decltype(piece)>::type>()),
    promotion(variables_["promotion"].as<std::decay<decltype(promotion)>::type>()),
    san(variables_["san"].as<std::decay<decltype(san)>::type>()),
    to_file(variables_["toFile"].as<std::decay<decltype(to_file)>::type>()),
    to_rank(variables_["toRank"].as<std::decay<decltype(to_rank)>::type>())
{
    for(auto&& obj : init)
    {
      variables_.emplace(std::make_pair(std::move(obj.first), std::move(obj.second)));
    }
}

Move_::~Move_() = default;

void Move_::resize(const std::string& name, std::size_t size)
{
    try
    {
        Game_object_::resize(name, size);
        return;
    }
    catch(...){}
    throw Bad_manipulation(name + " in Move treated as a vector, but it is not a vector.");
}

void Move_::change_vec_values(const std::string& name, std::vector<std::pair<std::size_t, Any>>& values)
{
    try
    {
        Game_object_::change_vec_values(name, values);
        return;
    }
    catch(...){}
    throw Bad_manipulation(name + " in Move treated as a vector, but it is not a vector.");
}

void Move_::remove_key(const std::string& name, Any& key)
{
    try
    {
        Game_object_::remove_key(name, key);
        return;
    }
    catch(...){}
    throw Bad_manipulation(name + " in Move treated as a map, but it is not a map.");
}

std::unique_ptr<Any> Move_::add_key_value(const std::string& name, Any& key, Any& value)
{
    try
    {
        return Game_object_::add_key_value(name, key, value);
    }
    catch(...){}
    throw Bad_manipulation(name + " in Move treated as a map, but it is not a map.");
}

bool Move_::is_map(const std::string& name)
{
    return false;
}

void Move_::rebind_by_name(Any* to_change, const std::string& member, std::shared_ptr<Base_object> ref)
{
   if(member == "captured")
   {
      to_change->as<Piece>() = std::static_pointer_cast<Piece_>(ref);
      return;
   }
   if(member == "piece")
   {
      to_change->as<Piece>() = std::static_pointer_cast<Piece_>(ref);
      return;
   }
   throw Bad_manipulation(member + " in Move treated as a reference, but it is not a reference.");
}

} // chess

} // cpp_client


text:
@interface WrappableCell()
@property (retain) NSString* title;
@property (retain) UILabel* label;
@end

@implementation WrappableCell

static UIFont* defaultFont;

+ (void) initialize {
  if (self == [WrappableCell class]) {
    defaultFont = [[UIFont boldSystemFontOfSize:18] retain];
  }
}

@synthesize title;
@synthesize label;

- (void) dealloc {
  self.title = nil;
  self.label = nil;

  [super dealloc];
}

- (id) initWithTitle:(NSString*) title_ {
  if ((self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil])) {
    self.title = title_;

    self.label = [[[UILabel alloc] init] autorelease];
    label.text = title;
    label.numberOfLines = 0;
    label.lineBreakMode = UILineBreakModeWordWrap;
    label.font = defaultFont;

    [self.contentView addSubview:label];
  }

  return self;
}

- (void) setFont:(UIFont*) font {
  label.font = font;
}

- (void) layoutSubviews {
  [super layoutSubviews];
  CGRect frame = self.contentView.frame;

  CGFloat height =  [WrappableCell height:title accessoryType:self.accessoryType font:label.font] - 20;
  label.frame = CGRectMake(10, 10, frame.size.width - 20, height);
}

- (void) setSelected:(BOOL)selected animated:(BOOL)animated {
  [super setSelected:selected animated:animated];

  if (selected && self.selectionStyle != UITableViewCellSelectionStyleNone) {
    label.textColor = [UIColor whiteColor];
  } else {
    label.textColor = [UIColor blackColor];
  }
}

+ (CGFloat)  height:(NSString*) text
      accessoryType:(UITableViewCellAccessoryType) accessoryType
               font:(UIFont*) font {
  CGFloat width;
  if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)) {
    width = [UIScreen mainScreen].bounds.size.height;
  } else {
    width = [UIScreen mainScreen].bounds.size.width;
  }
  width -= 20; // normal content view

  if (accessoryType == UITableViewCellAccessoryDisclosureIndicator) {
    width -= 10;
  }

  CGSize size = CGSizeMake(width, 50000);
  size = [text sizeWithFont:font
          constrainedToSize:size
              lineBreakMode:UILineBreakModeWordWrap];

  return size.height + 20;
}

+ (CGFloat) height:(NSString*) text accessoryType:(UITableViewCellAccessoryType) accessoryType {
  return [self height:text accessoryType:accessoryType font:defaultFont];
}

@end


text:
package calculators

import (
	"errors"

	"github.com/NumberXNumbers/GoCalculate/utils/parsers"
	gcv "github.com/NumberXNumbers/types/gc/values"
)

// ReversePolishCalculator is a simple reverse polish calculator
func ReversePolishCalculator(args []string) (value gcv.Value, err error) {
	stack := gcv.MakeValues()
	var operand1 gcv.Value
	var operand2 gcv.Value
	var result gcv.Value

	if len(args) <= 2 {
		err = errors.New("Not Enough Arguments")
		return
	}

	for _, argument := range args {
		if v, e := parsers.Value(argument); e == nil {
			stack.Append(v)
			continue
		}

		if stack.Len() > 1 {
			operand2, stack = pop(stack)
			operand1, stack = pop(stack)

			result, err = calculateV(operand1, operand2, argument)

			if err != nil {
				return
			}

			stack.Append(result)
		} else {
			err = errors.New("IndexOutOfBoundsException")
			return
		}
	}

	if stack.Len() != 1 {
		err = errors.New("Multiple Final Values")
		return
	}

	value = stack.Get(0)
	return
}


text:
\documentclass[11pt]{report}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\begin{document}
\title{Digital Signalbehandling - Repeteringsfrågor}
\author{Johanna Petersson}
\maketitle

\chapter{Introduktion}
\section{Signaler, system och signal processering}
\begin{enumerate}
	\item Hur definieras en signal? - Det är en fysisk kvantitet som varierar med tid, utrymme eller annan oberoende variabel (variabler)
	\item Hur kan ett system vara definierat? - Kan vara definierat som en fysisk apparat som utför en operation på en signal. Alternativt ett system som svarar på stimulans eller kraft genom att skapa en signal
\end{enumerate}

\section{Klassifikation av signaler}
\begin{enumerate}
	\item Hur definieras en analog signal? - Signalen är definierad för varje värde av tid och värdet är i ett kontinuerligt intervall mellan $-\infty$ och $\infty$
	\item Hur definieras tidsdiskreta signaler? - Signalen är bara definierad vid vissa tidpunkter
	\item Hur betecknas en analog signal? - $x(t)$
	\item Hur betecknas en tidsdiskret signal? - $x(n)$
	\item Vilka värden kan en kontinuerlig signal? - Alla värden mellan $-\infty$ och $\infty$
	\item Hur definieras en diskret-värdes signal? - En signal vars värden bara kan anta ändligt antal värde
	\item Vad är definitionen för en digital signal? - En signal som är en tidsdiskret och bara kan anta ett ändligt antal värde är en digital signal
	\item Vad är en deterministisk signal? - En signal som kan beskrivas precist med en matematisk formula eller en data tabell. Alla tidigare, nuvarande och kommande värden kan bestämmas precist.
\end{enumerate}

\section{Konceptet för frekvens i kontinuerliga tid och tidsdiskreta signaler}
\begin{enumerate}
	\item Vilka tre parametrar karaktäriserar en vanlig analog signal? - Amplituden $(A)$, frekvensen $(\Omega)$ och fasen $(\theta)$
	\item Skriv upp standardformeln för en analog signal - $x_a(t)=A \cos(\Omega t + \theta) \quad -\infty < t < \infty$
	\item Vad beskriver frekvensen $\Omega$ - Antalet radianer per sekund (rad/sec)
	\item Vad beskriver fasen $\theta$ - Fasen vriden i radianer från $0$
	\item Hur konverteras $\Omega$ till frekvens $F$? - $\Omega = 2\pi F$
\end{enumerate}

\chapter{Diskreta tids- signaler och system}
\section{Diskreta tidssignaler}
\begin{enumerate}
	\item Är en diskret tidssignal $x(n)$ definierad för alla tal? - Nej, bara heltal som är samplade, oftast antaget intervallet $-\infty < n < \infty$. Utanför heltal är signalen $0$
	\item Hur är en $\delta (n)$ definierad? - $\delta (n) = \left\{ \begin{array}{l l}
		1 & \quad \text{då } n=0 \\
		0 & \quad \text{då } n \neq 0
	\end{array}\right.$
	\item Hur betecknas en stegsignal? - $u(n)$
	\item Hur är $u(n)$ definierad? - $u(n) = \left\{ \begin{array}{l l}
		1 & \quad \text{då } n \geq 0 \\
		0 & \quad \text{då } n < 0
	\end{array}\right.$
	\item Hur betecknas en ramp signal? - $u_r(n)$
	\item Hur är $u_r(n)$ definierad? -  $u_r(n) = \left\{ \begin{array}{l l}
		n & \quad \text{då } n \geq 0 \\
		0 & \quad \text{då } n < 0
	\end{array}\right.$
	\item Hur är en exponential signal betecknas? - $x(n)=a^n$
\end{enumerate}

\section{Diskreta tidssystem}
\begin{enumerate}
	\item Hur definieras att ett system är tidsinvariant? - Ett avslappnat system $\mathcal{T}$ är tidsinvariant eller skiftinvariant om och endast om \[ x(n) \longrightarrow^{\mathcal{T}} y(n)  \] vilket ger \[ x(n-k) \longrightarrow^{\mathcal{T}} y(n-k)\] för varje insignal $x(n)$ och varje tidsskiftning $k$
	\item Hur definieras ett linjärt system? - Ett system är linjärt om och endast om \[ \mathcal{T}(a_1x_1(n)+a_2x_2(n)) = a_1\mathcal{T}(x_1(n)) + a_2 \mathcal{T}(x_2(n)) \]för alla möjliga sekvenser av $x_1(n)$ och $x_2(n)$ och alla konstanter $a_1$ och $a_2$
	\item Hur definieras ett kausalt system? - Ett system sägs vara kausalt om utsignalen från systemet för alla givna tider $n$ endast beror på tidigare insignaler men inte beror på kommande insignaler
	\item Hur definieras stabilitet för ett system? - Ett godtyckligt avslappnat system sägs vara bunden insignal-bunden utsignal (BIBO) stabilt om och endast om det för varje bunden insignal produceras en bunden utsignal
	\item Vad betyder BIBO? - Det är stabilitetsgräns som säger att varken in eller utsignalen får vara $\infty$ för att det ska vara uppfyllt
\end{enumerate}

\section{Analys av tidsdiskreta linjära tidsinvarianta system}
\begin{enumerate}
	\item Vad står LTI för? - Det står för linjära tidsinvarianta system
	\item Hur betecknas impulssvaret? - $h(n)$
	\item Vad är insignalen för att få impulssvaret? - $\delta(n)$
	\item Vad är utsignalen för ett LTI system om insignalen är $x(n)$? - $y(n)=\sum^\infty_{k=-\infty}x(k)h(n-k)$
	\item Vad är faltnings formeln? - $y(n)=\sum^\infty_{k=-\infty}x(k)h(n-k)$
	\item Vilka är stegen vid matematisk faltning? - \begin{enumerate}
		\item \emph{Viktning}. Vik $h(k)$ runt $k=0$ för att få $h(-k)$
		\item \emph{Skifta}. Skifta $h(-k)$ med $n$ till höger (vänster) om $n$ är positiv (negativ) för att få $h(n-k)$
		\item \emph{Multiplicera}. Multiplicera $x(n)$ med $h(n-k)$ för att få produkten
		\item \emph{Summera}. Summera alla multiplikationer för att få värdet av utsignalen vid tiden $n$
		\end{enumerate}
	\item Hur ser formeln för faltning ut för en insignal $x(n)$ som är kausalt och ett impulssvar $h(n)$ som också är kausalt? - $y(n)=\sum^n_{k=0}x(k)h(n-k)$
	\item Vilket krav finns det på faltningen av ett LIT system för att systemet ska vara BIBO stabilt? - Det är BIBO stabilt om och endast om impulssvaret är absolut summerbart d.v.s \[ S_h = \sum^\infty_{k=-\infty} |h(k)| < \infty \]
	\end{enumerate}

\end{document}


text:
package bean;

import javax.ejb.Local;

import entities.event.Mailable;

@Local
public interface MailNotification {

//	@Asynchronous
	public void notifyUsers(Mailable event);

	public void init();

}


text:
package com.tesshu.subsonic.client.fx.view.global;

import static com.tesshu.subsonic.client.fx.event.ActionEvent.UPDATE_MAIN;
import static javafx.scene.input.MouseEvent.MOUSE_CLICKED;

import com.tesshu.subsonic.client.fx.command.CommandLogic;
import com.tesshu.subsonic.client.fx.command.logic.CloseContainerLogic;
import com.tesshu.subsonic.client.fx.command.param.VoidParam;
import com.tesshu.subsonic.client.fx.event.Action;
import com.tesshu.subsonic.client.fx.event.ActionEvent;
import com.tesshu.subsonic.client.fx.view.ICustomComponent;
import com.tesshu.subsonic.client.fx.view.ICustomControl;
import com.tesshu.subsonic.client.fx.view.IconContent;
import com.tesshu.subsonic.client.fx.view.LabelGraphicSupport;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javafx.scene.control.Label;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Component
@Scope("prototype")
public final class CloseMainLabelImpl extends Label implements ICustomControl, Action<VoidParam> {

  @Resource
  private LabelGraphicSupport graphicSupport;

  @Override
  public Label getInstance() {
    return this;
  }

  @Override
  public ICustomComponent<?> getOrigin() {
    return this;
  }

  @Override
  public VoidParam getParameter() {
    return null;
  }

  @Override
  public Class<? extends CommandLogic<VoidParam>> getType() {
    return CloseContainerLogic.class;
  }

  @PostConstruct
  private void initialize() {
    graphicSupport.initIconWithText(this, IconContent.CLOSE, 30);
    addEventFilter(MOUSE_CLICKED, (event) -> fireEvent(new ActionEvent(this, UPDATE_MAIN)));
  }

}


text:
<?php

class ReviewRequest extends Eloquent{
	protected $dates = array('deadline');
	protected $fillable = array('user_id','paper_id', 'deadline', 'message');

	public function user(){
		return $this->belongsTo('User');
	}

	public function paper(){
		return $this->belongsTo('Paper');
	}

	public function files(){
		return $this->belongsToMany('FileObject', 'file_review_request', 'review_request_id', 'file_id');
	}

	public function authors(){
		return $this->belongsToMany('Author')->withPivot('answer')->withPivot('auth_token');
	}

	public function reviews(){
		return $this->hasMany('Review');
	}

	public function remindableUsers(){
		$users = array();
		foreach ($this->authors as $author) {
			if($author->user){
				if(is_null($author->pivot->answer))
					array_push($users, $author->user);
				if($author->pivot->answer){
					$finished = false;
					foreach ($this->reviews as $review) {
						if($review->author_id == $author->id){
							$finished = true;
							break;
						}
					}
					if(!$finished)
						array_push($users, $author->user);
				}
			}
		}
		return $users;
	}

	/**
	 * Convert a DateTime to a storable string.
	 * Overwrite fromDateTime to support the used format (e.g. May 26, 2014)
	 *
	 * @param  \DateTime|int  $value
	 * @return string
	 */
	public function fromDateTime($value) {
		if (is_string($value) && preg_match('/^([A-Z][a-z]+) (\d{2}), (\d{4})$/', $value)) {
			$value = Carbon::createFromFormat('M d, Y', $value)->startOfDay();
		}
		return parent::fromDateTime($value);
	}

	public function getPapers() {
	    return array(Paper::find($this->paper_id));
	}
}


text:
function WalkontableSelection(instance, settings) {
  this.instance = instance;
  this.settings = settings;
  this.selected = [];
  if (settings.border) {
    this.border = new WalkontableBorder(instance, settings);
  }
}

WalkontableSelection.prototype.add = function (coords) {
  this.selected.push(coords);
};

WalkontableSelection.prototype.clear = function () {
  this.selected.length = 0; //http://jsperf.com/clear-arrayxxx
};

/**
 * Returns the top left (TL) and bottom right (BR) selection coordinates
 * @returns {Object}
 */
WalkontableSelection.prototype.getCorners = function () {
  var minRow
    , minColumn
    , maxRow
    , maxColumn
    , i
    , ilen = this.selected.length;

  if (ilen > 0) {
    minRow = maxRow = this.selected[0][0];
    minColumn = maxColumn = this.selected[0][1];

    if (ilen > 1) {
      for (i = 1; i < ilen; i++) {
        if (this.selected[i][0] < minRow) {
          minRow = this.selected[i][0];
        }
        else if (this.selected[i][0] > maxRow) {
          maxRow = this.selected[i][0];
        }

        if (this.selected[i][1] < minColumn) {
          minColumn = this.selected[i][1];
        }
        else if (this.selected[i][1] > maxColumn) {
          maxColumn = this.selected[i][1];
        }
      }
    }
  }

  return [minRow, minColumn, maxRow, maxColumn];
};

WalkontableSelection.prototype.draw = function () {
  var corners, r, c, source_r, source_c;

  var visibleRows = this.instance.wtTable.countVisibleRows()
    , visibleColumns = this.instance.wtTable.countVisibleColumns();

  if (this.selected.length) {
    corners = this.getCorners();

    for (r = 0; r < visibleRows; r++) {
      for (c = 0; c < visibleColumns; c++) {
        source_r = this.instance.wtTable.rowFilter.visibleToSource(r);
        source_c = this.instance.wtTable.columnFilter.visibleToSource(c);

        if (source_r >= corners[0] && source_r <= corners[2] && source_c >= corners[1] && source_c <= corners[3]) {
          //selected cell
          this.instance.wtTable.currentCellCache.add(r, c, this.settings.className);
        }
        else if (source_r >= corners[0] && source_r <= corners[2]) {
          //selection is in this row
          this.instance.wtTable.currentCellCache.add(r, c, this.settings.highlightRowClassName);
        }
        else if (source_c >= corners[1] && source_c <= corners[3]) {
          //selection is in this column
          this.instance.wtTable.currentCellCache.add(r, c, this.settings.highlightColumnClassName);
        }
      }
    }

    this.border && this.border.appear(corners); //warning! border.appear modifies corners!
  }
  else {
    this.border && this.border.disappear();
  }
};