text:
"use strict";

var fs           = require("fs");
var path         = require("path");
var filePath     = require("path");
var connect      = require("connect");
var Immutable    = require("immutable");
var http         = require("http");
var https        = require("https");
var Map          = require("immutable").Map;
var fromJS       = require("immutable").fromJS;
var List         = require("immutable").List;
var snippet      = require("./../snippet").utils;
var _            = require("./../../lodash.custom");
var serveStatic  = require("serve-static");
var logger       = require("../logger");
var snippetUtils = require("../snippet").utils;
var lrSnippet    = require("resp-modifier");
var utils        = require("../utils");

var serverUtils = {
    /**
     * @param options
     * @returns {{key, cert}}
     */
    getKeyAndCert: function (options) {
        return {
            key: fs.readFileSync(options.getIn(["https", "key"])  || filePath.join(__dirname, "certs/server.key")),
            cert: fs.readFileSync(options.getIn(["https", "cert"]) || filePath.join(__dirname, "certs/server.crt")),
            ca: fs.readFileSync(options.getIn(["https", "ca"]) || filePath.join(__dirname, "certs/server.csr")),
            passphrase: options.getIn(["https", "passphrase"]) || ""
        };
    },
    /**
     * @param filePath
     * @returns {{pfx}}
     */
    getPFX: function (filePath) {
        return {
            pfx: fs.readFileSync(filePath)
        };
    },
    /**
     * Get either http or https server
     * or use the httpModule provided in options if present
     */
    getServer: function (app, options) {
        return {
            server: (function () {

                var httpModule = serverUtils.getHttpModule(options);

                if (options.get("scheme") === "https") {
                    var pfxPath = options.getIn(["https", "pfx"]);
                    return pfxPath ?
                        httpModule.createServer(serverUtils.getPFX(pfxPath), app) :
                        httpModule.createServer(serverUtils.getKeyAndCert(options), app);
                }

                return httpModule.createServer(app);
            })(),
            app: app
        };
    },
    getHttpModule: function (options) {
        /**
         * Users may provide a string to be used by nodes
         * require lookup.
         */
        var httpModule = options.get("httpModule");

        if (typeof httpModule === "string") {
            /**
             * Note, this could throw, but let that happen as
             * the error message good enough.
             */
            var maybe = path.resolve(process.cwd(), "node_modules", httpModule);
            return require(maybe);
        }

        if (options.get("scheme") === "https") {
            return https;
        }

        return http;
    },
    getMiddlewares: function (bs) {

        var clientJs = bs.pluginManager.hook("client:js", {
            port: bs.options.get("port"),
            options: bs.options
        });

        var scripts = bs.pluginManager.get("client:script")(
            bs.options.toJS(),
            clientJs,
            "middleware"
        );

        var defaultMiddlewares = [
            {
                id: "Browsersync HTTP Protocol",
                route: require("../config").httpProtocol.path,
                handle: require("../http-protocol").middleware(bs)
            },
            {
                id: "Browsersync IE8 Support",
                route: "",
                handle: snippet.isOldIe(bs.options.get("excludedFileTypes").toJS())
            },
            {
                id: "Browsersync Response Modifier",
                route: "",
                handle: serverUtils.getSnippetMiddleware(bs)
            },
            {
                id: "Browsersync Client - versioned",
                route: bs.options.getIn(["scriptPaths", "versioned"]),
                handle: scripts
            },
            {
                id: "Browsersync Client",
                route: bs.options.getIn(["scriptPaths", "path"]),
                handle: scripts
            }
        ];

        /**
         * Add cors middleware to the front of the stack
         * if a user provided a 'cors' flag
         */
        if (bs.options.get("cors")) {
            defaultMiddlewares.unshift({
                id: "Browsersync CORS support",
                route: "",
                handle: serverUtils.getCorsMiddlewware()
            })
        }

        /**
         * Add serve static middleware
         */
        if (bs.options.get("serveStatic")) {

            var ssMiddlewares = serverUtils.getServeStaticMiddlewares(bs.options.get("serveStatic"), bs.options.get("serveStaticOptions", Immutable.Map({})).toJS());
            var withErrors    = ssMiddlewares.filter(function(x) { return x.get("errors").size > 0 });
            var withoutErrors = ssMiddlewares.filter(function(x) { return x.get("errors").size === 0 });

            if (withErrors.size) {
                withErrors.forEach(function (item) {
                    logger.logger.error("{red:Warning!} %s", item.getIn(["errors", 0, "data", "message"]));
                });
            }

            if (withoutErrors.size) {
                withoutErrors.forEach(function (item) {
                    defaultMiddlewares.push.apply(defaultMiddlewares, item.get("items").toJS());
                });
            }
        }

        /**
         * Add user-provided middlewares
         */
        var userMiddlewares   = bs.options.get("middleware").map(normaliseMiddleware).toArray();
        var beforeMiddlewares = userMiddlewares.filter(function (x) { return x.override; });
        var afterMiddlewares  = userMiddlewares.filter(function (x) { return !x.override; });

        return [].concat(beforeMiddlewares, defaultMiddlewares, afterMiddlewares);

        function normaliseMiddleware(item) {
            /**
             * Object given in options, which
             * ended up being a Map
             */
            if (Map.isMap(item)) {
                return item.toJS();
            }
            /**
             * Single function
             */
            if (typeof item === "function") {
                return {
                    route: "",
                    handle: item
                }
            }
            /**
             * Plain obj
             */
            if ((item.route !== undefined) && item.handle) {
                return item;
            }
        }

                /**
         * Add the proxy Middleware to the end of the stack
         */
    },
    getBaseApp: function (bs) {

        var app         = connect();
        var middlewares = serverUtils.getMiddlewares(bs);

        /**
         * Add all internal middlewares
         */
        middlewares.forEach(function (item) {
            app.stack.push(item);
        });

        return app;
    },
    getSnippetMiddleware: function (bs) {

        var rules = [];
        var blacklist = List([])
            .concat(bs.options.getIn(["snippetOptions", "ignorePaths"]))
            .concat(bs.options.getIn(["snippetOptions", "blacklist"]))
            .filter(Boolean);

        var whitelist = List([])
            .concat(bs.options.getIn(["snippetOptions", "whitelist"]));

        // Snippet
        rules.push(snippetUtils.getRegex(bs.options.get("snippet"), bs.options.get("snippetOptions")));

        // User
        bs.options.get("rewriteRules").forEach(function (rule) {
            if (Map.isMap(rule)) {
                rules.push(rule.toJS());
            }
            if (_.isPlainObject(rule)) {
                rules.push(rule);
            }
        });

        // Proxy
        if (bs.options.get("proxy")) {
            var proxyRule = require("./proxy-utils").rewriteLinks(bs.options.getIn(["proxy", "url"]).toJS());
            rules.push(proxyRule);
        }

        var lr = lrSnippet.create({
            rules:     rules,
            blacklist: blacklist.toArray(),
            whitelist: whitelist.toArray()
        });

        return lr.middleware;
    },
    getCorsMiddlewware: function () {

        return function (req, res, next) {
            // Website you wish to allow to connect
            res.setHeader("Access-Control-Allow-Origin", "*");

            // Request methods you wish to allow
            res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");

            // Request headers you wish to allow
            res.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type");

            // Set to true if you need the website to include cookies in the requests sent
            // to the API (e.g. in case you use sessions)
            res.setHeader("Access-Control-Allow-Credentials", true);
            next();
        }
    },
    /**
     * @param ssOption
     * @param serveStaticOptions
     * @returns {*}
     */
    getServeStaticMiddlewares: function (ssOption, serveStaticOptions) {

        return ssOption.map(function (dir, i) {

            /**
             * When a user gives a plain string only, eg:
             *   serveStatic: ['./temp']
             *     ->
             *       This means a middleware will be created with
             *         route: ''
             *         handle: serveStatic('./temp', options)
             */
            if (_.isString(dir)) {
                return getFromString(dir)
            }

            /**
             * If a user gave an object eg:
             *   serveStatic: [{route: "", dir: ["test", "./tmp"]}]
             *     ->
             *       This means we need to create a middle for each route + dir combo
             */
            if (Immutable.Map.isMap(dir)) {
                return getFromMap(dir, i);
            }

            /**
             * At this point, an item in the serveStatic array was not a string
             * or an object so we return an error that can be logged
             */
            return fromJS({
                items: [],
                errors: [{
                    type: "Invalid Type",
                    data: {
                        message: "Only strings and Objects (with route+dir) are supported for the ServeStatic option"
                    }
                }]
            })
        });

        /**
         * @param {string} x
         * @returns {string}
         */
        function getRoute (x) {
            if (x === "") return "";
            return x[0] === "/" ? x : "/" + x;
        }

        /**
         * @param dir
         * @returns {Map}
         */
        function getFromString(dir) {
            return fromJS({
                items: [
                    {
                        route: "",
                        handle: serveStatic(dir, serveStaticOptions)
                    }
                ],
                errors: []
            })
        }

        /**
         * @param dir
         * @returns {Map}
         */
        function getFromMap(dir) {

            var ssOptions = (function () {
                if (dir.get("options")) {
                    return dir.get("options").toJS();
                }
                return {}
            })();

            var route = Immutable.List([]).concat(dir.get("route")).filter(_.isString);
            var _dir  = Immutable.List([]).concat(dir.get("dir")).filter(_.isString);

            if (_dir.size === 0) {

                return fromJS({
                    items: [],
                    errors: [{
                        type: "Invalid Object",
                        data: {
                            message: "Serve Static requires a 'dir' property when using an Object"
                        }
                    }]
                })
            }

            var ssItems = (function () {

                /**
                 * iterate over every 'route' item
                 * @type {Immutable.List<any>|Immutable.List<*>|Immutable.List<any>|*}
                 */
                var routeItems = (function () {

                    /**
                     * If no 'route' was given, assume we want to match all
                     * paths
                     */
                    if (route.size === 0) {
                        return _dir.map(function (dirString) {
                            return Map({
                                route: "",
                                dir: dirString
                            });
                        });
                    }

                    return route.reduce(function (acc, routeString) {
                        /**
                         * For each 'route' item, also iterate through 'dirs'
                         * @type {Immutable.Iterable<K, M>}
                         */
                        var perDir = _dir.map(function (dirString) {
                            return Map({
                                route: getRoute(routeString),
                                dir: dirString
                            })
                        });
                        return acc.concat(perDir);

                    }, List([]));
                })();

                /**
                 * Now create a serverStatic Middleware for each item
                 */
                return routeItems.map(function (routeItem) {
                    return routeItem.merge({
                        handle: serveStatic(routeItem.get("dir"), ssOptions)
                    });
                });
            })();

            return fromJS({
                items: ssItems,
                errors: []
            });
        }
    }
};

module.exports = serverUtils;


text:
using System.Collections.Generic;
using NPOI.HSSF.Model;
using NPOI.HSSF.Record.Chart;
using System.Diagnostics;

namespace NPOI.HSSF.Record.Aggregates.Chart
{
    /// <summary>
    /// CHARTFOMATS = Chart Begin *2FONTLIST Scl PlotGrowth [FRAME] *SERIESFORMAT *SS ShtProps
    /// *2DFTTEXT AxesUsed 1*2AXISPARENT [CrtLayout12A] [DAT] *ATTACHEDLABEL [CRTMLFRT]
    /// *([DataLabExt StartObject] ATTACHEDLABEL [EndObject]) [TEXTPROPS] *2CRTMLFRT End
    /// </summary>
    public class ChartFormatsAggregate : ChartRecordAggregate
    {
        private ChartRecord chart = null;
        private List<FontListAggregate> fontList = new List<FontListAggregate>();

        private SCLRecord scl = null;
        private PlotGrowthRecord plotGrowth;

        private FrameAggregate frame;
        private List<SeriesFormatAggregate> seriesFormatList = new List<SeriesFormatAggregate>();
        private List<SSAggregate> ssList = new List<SSAggregate>();

        private ShtPropsRecord shtProps;
        private List<DFTTextAggregate> dftTextList = new List<DFTTextAggregate>();
        private AxesUsedRecord axesUsed;

        private AxisParentAggregate axisParent1, axisParent2;
        private CrtLayout12ARecord crt12A;
        private DatAggregate dat;
        private List<AttachedLabelAggregate> attachedLabelList = new List<AttachedLabelAggregate>();
        private CrtMlFrtAggregate crtMlFrt;
        private List<ChartFormatsAttachedLabelAggregate> cfalList = new List<ChartFormatsAttachedLabelAggregate>();
        private TextPropsAggregate textProps;
        private List<CrtMlFrtAggregate> mlfrtList = new List<CrtMlFrtAggregate>();

        public ChartFormatsAggregate(RecordStream rs, ChartRecordAggregate container)
            : base(RuleName_CHARTFOMATS, container)
        {
            Debug.Assert(rs.PeekNextChartSid() == ChartRecord.sid);
            chart = (ChartRecord)rs.GetNext();
            rs.GetNext();
            while (rs.PeekNextChartSid() == FrtFontListRecord.sid)
            {
                fontList.Add(new FontListAggregate(rs, this));
            }
            Debug.Assert(rs.PeekNextChartSid() == SCLRecord.sid);
            scl = (SCLRecord)rs.GetNext();
            plotGrowth = (PlotGrowthRecord)rs.GetNext();

            if (rs.PeekNextChartSid() == FrameRecord.sid)
            {
                frame = new FrameAggregate(rs, this);
            }

            while (rs.PeekNextChartSid() == SeriesRecord.sid)
            {
                seriesFormatList.Add(new SeriesFormatAggregate(rs, this));
            }

            while (rs.PeekNextChartSid() == DataFormatRecord.sid)
            {
                ssList.Add(new SSAggregate(rs, this));
            }

            Debug.Assert(rs.PeekNextChartSid() == ShtPropsRecord.sid);
            shtProps = (ShtPropsRecord)rs.GetNext();

            while (rs.PeekNextChartSid() == DefaultTextRecord.sid||
                rs.PeekNextChartSid() == DataLabExtRecord.sid)
            {
                dftTextList.Add(new DFTTextAggregate(rs, this));
            }

            Debug.Assert(rs.PeekNextChartSid() == AxesUsedRecord.sid);
            axesUsed = (AxesUsedRecord)rs.GetNext();

            Debug.Assert(rs.PeekNextChartSid() == AxisParentRecord.sid);
            axisParent1 = new AxisParentAggregate(rs, this);
            if (rs.PeekNextChartSid() == AxisParentRecord.sid)
            {
                axisParent2 = new AxisParentAggregate(rs, this);
            }

            if (rs.PeekNextChartSid() == CrtLayout12ARecord.sid)
                crt12A = (CrtLayout12ARecord)rs.GetNext();
            if (rs.PeekNextChartSid() == DatRecord.sid)
                dat = new DatAggregate(rs, container);

            if (rs.PeekNextChartSid() == TextRecord.sid)
            {
                while (rs.PeekNextChartSid() == TextRecord.sid)
                    attachedLabelList.Add(new AttachedLabelAggregate(rs, this));
            }

            if (rs.PeekNextChartSid() == CrtMlFrtRecord.sid)
                crtMlFrt = new CrtMlFrtAggregate(rs, container);

            while (rs.PeekNextChartSid() == DataLabExtRecord.sid || rs.PeekNextChartSid() == TextRecord.sid)
            {
                cfalList.Add(new ChartFormatsAttachedLabelAggregate(rs, this));
            }

            if (rs.PeekNextChartSid() == TextPropsStreamRecord.sid)
                textProps = new TextPropsAggregate(rs, container);

            while (rs.PeekNextChartSid() == CrtMlFrtRecord.sid)
            {
                mlfrtList.Add(new CrtMlFrtAggregate(rs, container));
            }

            Record r = rs.GetNext();//EndRecord
            Debug.Assert(r.GetType() == typeof(EndRecord));
        }

        public override void VisitContainedRecords(RecordVisitor rv)
        {
            rv.VisitRecord(chart);
            rv.VisitRecord(BeginRecord.instance);
            foreach (FontListAggregate f in fontList)
            {
                f.VisitContainedRecords(rv);
            }
            rv.VisitRecord(scl);
            rv.VisitRecord(plotGrowth);

            if (frame != null)
                frame.VisitContainedRecords(rv);

            short num = 0;
            foreach (SeriesFormatAggregate sf in seriesFormatList)
            {
                sf.VisitContainedRecords(rv);
                sf.SeriesIndex = num++;
            }
            foreach (SSAggregate ss in ssList)
                ss.VisitContainedRecords(rv);
            rv.VisitRecord(shtProps);
            foreach (DFTTextAggregate dft in dftTextList)
                dft.VisitContainedRecords(rv);
            rv.VisitRecord(axesUsed);

            axisParent1.VisitContainedRecords(rv);
            if (axisParent2 != null)
                axisParent2.VisitContainedRecords(rv);

            if (crt12A != null)
                rv.VisitRecord(crt12A);
            if (dat != null)
                dat.VisitContainedRecords(rv);

            foreach (AttachedLabelAggregate al in attachedLabelList)
                al.VisitContainedRecords(rv);

            if (crtMlFrt != null)
                crtMlFrt.VisitContainedRecords(rv);

            foreach (ChartFormatsAttachedLabelAggregate cfa in cfalList)
                cfa.VisitContainedRecords(rv);

            if (textProps != null)
                textProps.VisitContainedRecords(rv);

            foreach (CrtMlFrtAggregate c in mlfrtList)
                c.VisitContainedRecords(rv);

            WriteEndBlock(rv);
            rv.VisitRecord(EndRecord.instance);
        }
        private class ChartFormatsAttachedLabelAggregate : ChartRecordAggregate
        {
            private DataLabExtRecord dataLabExt;
            private ChartStartObjectRecord startObject;
            private AttachedLabelAggregate attachedLabel;
            private ChartEndObjectRecord endObject;
            public ChartFormatsAttachedLabelAggregate(RecordStream rs, ChartRecordAggregate container)
                : base("ChartFormatsAttachedLabel", container)
            {
                if (rs.PeekNextChartSid() == DataLabExtRecord.sid)
                {
                    dataLabExt = (DataLabExtRecord)rs.GetNext();
                    startObject = (ChartStartObjectRecord)rs.GetNext();
                }

                attachedLabel = new AttachedLabelAggregate(rs, this);

                if (startObject != null)
                {
                    endObject = (ChartEndObjectRecord)rs.GetNext();
                }
            }

            public override void VisitContainedRecords(RecordVisitor rv)
            {
                if (dataLabExt != null)
                {
                    rv.VisitRecord(dataLabExt);
                    rv.VisitRecord(startObject);
                    IsInStartObject = true;
                }
                attachedLabel.VisitContainedRecords(rv);
                if (endObject != null)
                {
                    IsInStartObject = false;
                    rv.VisitRecord(endObject);
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

require_once 'includes/config.php';
require_once 'includes/setup.php';
require_once 'Site/Smarty_Page_Builder.php';

$status = isset($_SERVER['REDIRECT_STATUS']) ? $_SERVER['REDIRECT_STATUS'] :
                                               'unknown';
$url = isset($_SERVER['REDIRECT_URL']) ? $_SERVER['REDIRECT_URL'] : '';

$builder = new Smarty_Page_Builder();
$smarty = $builder->build();
$smarty->display_error($status, $url);


text:
using System;
using System.Text;
using System.Collections;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
//using Oracle.DataAccess.Client;
using Approve.PersistBase;
using System.EnterpriseServices;

namespace Approve.PersistEnterprise
{
    /// <summary>
    /// PEnt µÄժҪ˵Ã÷¡£
    /// </summary>
    public class PEnt : PBase
    {
        public PEnt()
        {
            //
            // TODO: ÔÚ´Ë´¦Ìí¼Ó¹¹Ô캯ÊýÂß¼
            //
        }

    }
}


text:
// @flow
import React from 'react'
import utils from './utils'

const defaultValue = (props) => {
  // check if there is a value in the model, if there is, display it. Otherwise, check if
  // there is a default value, display it.
  let value
  if (props.form && props.form.key)
    value = utils.selectOrSet(props.form.key, props.model)

  // check if there is a default value
  if (value === null || value === undefined) {
    if (props.form.default) {
      value = props.form.default
    } else if (props.form.schema && props.form.schema.default) {
      value = props.form.schema.default
    }
  }
  return value
}

type Props = {
  errorText: any,
  form: any,
  showErrors: boolean,
  localization: any,
  onChange: any
}

const getDisplayName = (WrappedComponent) =>
  WrappedComponent.displayName || WrappedComponent.name || 'Component'

export default (ComposedComponent, defaultProps = {}) =>
  (class Composed extends React.Component<Props> {
    constructor(props) {
      super(props)
      this.displayName = `ComposedComponent(${getDisplayName(
        ComposedComponent
      )})`
      this.onChangeValidate = this.onChangeValidate.bind(this)
      this.state = this.constructor.getDerivedStateFromProps(this.props)
    }

    static getDerivedStateFromProps(nextProps: Props) {
      const { errorText, form, showErrors, localization } = nextProps
      const getLocalizedString = localization && localization.getLocalizedString
      const value = defaultValue(nextProps)
      if (!showErrors) {
        return {
          value,
          valid: true,
          error: ''
        }
      }

      const validationResult = utils.validate(
        form,
        value || undefined,
        getLocalizedString
      )

      const error = !validationResult.valid ? validationResult.error : undefined

      return {
        value,
        valid: validationResult.valid,
        error: (!validationResult.valid ? error.message : null) || errorText
      }
    }

    /**
     * Called when <input> value changes.
     * @param e The input element, or something.
     */
    onChangeValidate(e, v) {
            const { form, onChange, localization } = this.props; // eslint-disable-line
      const getLocalizedString = localization && localization.getLocalizedString
      let value = null
      // use the schema type so that we can have a limited number of types to handle. This
      // gives us the flexibility to create add-ons without touching the code of main project.
      const type = form.schema ? form.schema.type : form.type
      // console.log(type)
      switch (type) {
        case 'integer':
        case 'number': {
          value = e
          break
        }
        case 'boolean':
          value = e.target.checked
          break
        case 'array':
          value = e
          break
        case 'object':
          if (form.type === 'date') {
            if (e.target.value.length > 0) {
              value = new Date(e.target.value)
            } else {
              value = ''
            }
            break
          }
          ;({ value } = e.target)
          break
        default:
          // string goes here.
          ;({ value } = e.target)
      }

      const validationResult = utils.validate(form, value, getLocalizedString)
      this.setState({
        value,
        valid: validationResult.valid,
        error: validationResult.valid ? null : validationResult.error.message
      })

      onChange(form.key, value)
    }

    render() {
      return (
        <ComposedComponent
          {...defaultProps}
          {...this.props}
          {...this.state}
          onChangeValidate={this.onChangeValidate}
        />
      )
    }
  })


text:
/*
 Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl
 Copyright (C) 2003, 2004, 2005, 2006, 2007 StatPro Italia srl

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

package org.quantjlib.quotes;

import org.quantjlib.util.Observable;

/**
 * Relinkable handle to an observable
 * <p>
 * An instance of this class can be relinked so that it points to another
 * observable. The change will be propagated to all handles that were created as
 * copies of such instance.
 *
 * @author Richard Gomes
 */
//FIXME:
public class RelinkableHandle<T extends Observable> extends Handle<T> {

    public RelinkableHandle() {
        super();
    }

	public RelinkableHandle(final T observable) {
    	this(observable, true);
    }

    public RelinkableHandle(final T observable, final boolean isObserver) {
    	super(observable, isObserver);
    }

    @Override
    public final void linkTo(final T observable) {
    	super.internalLinkTo(observable, true);
    }

    @Override
    public final void linkTo(final T observable, final boolean isObserver) {
    	super.internalLinkTo(observable, isObserver);
    }

}


text:
module Booking
  module EntriesHelper
  end
end


text:
<?php

namespace App\Common\Models\Qyweixin\Media;

use App\Common\Models\Base\Base;

class Type extends Base
{

    function __construct()
    {
        $this->setModel(new \App\Common\Models\Qyweixin\Mysql\Media\Type());
    }

    /**
     * 获取所有列表
     *
     * @return array
     */
    public function getAll()
    {
        $list = $this->findAll(array(), array('_id' => 1));
        $options = array();
        foreach ($list as $item) {
            $options[$item['value']] = "{$item['value']}:{$item['name']}";
        }
        return $options;
    }
}


text:
cask 'find-any-file' do
  version '1.8.9'
  sha256 'fde3cd23b38f5baa626f557ac40148795a5afee6cc84ecb28b74b439bdae0189'

  # files.tempel.org.s3.amazonaws.com was verified as official when first introduced to the cask
  url "http://files.tempel.org.s3.amazonaws.com/FindAnyFile_#{version}.zip"
  appcast 'http://apps.tempel.org/FindAnyFile/appcast.xml',
          checkpoint: '5d25f92c40bee0bdf20067a321ae8d6718a5d8a3415e9067a1b7378de43905f6'
  name 'Find Any File'
  homepage 'http://apps.tempel.org/FindAnyFile/'

  app 'Find Any File.app'

  zap trash: '~/Library/Application Support/Find Any File'
end


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.CoreModules.Avatar.InstantMessage;
using OpenSim.Region.CoreModules.World.Permissions;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups;
using OpenSim.Tests.Common;

namespace OpenSim.Region.Framework.Scenes.Tests
{
    [TestFixture]
    public class SceneObjectUserGroupTests : OpenSimTestCase
    {
        /// <summary>
        /// Test share with group object functionality
        /// </summary>
        /// <remarks>This test is not yet fully implemented</remarks>
        [Test]
        public void TestShareWithGroup()
        {
            TestHelpers.InMethod();

            UUID userId = UUID.Parse("10000000-0000-0000-0000-000000000001");

            TestScene scene = new SceneHelpers().SetupScene();
            IConfigSource configSource = new IniConfigSource();

            IConfig startupConfig = configSource.AddConfig("Startup");
            startupConfig.Set("serverside_object_permissions", true);

            IConfig groupsConfig = configSource.AddConfig("Groups");
            groupsConfig.Set("Enabled", true);
            groupsConfig.Set("Module", "GroupsModule");
            groupsConfig.Set("DebugEnabled", true);

            SceneHelpers.SetupSceneModules(
                scene, configSource, new object[]
                   { new PermissionsModule(),
                     new GroupsModule(),
                     new MockGroupsServicesConnector() });

            IClientAPI client = SceneHelpers.AddScenePresence(scene, userId).ControllingClient;

            IGroupsModule groupsModule = scene.RequestModuleInterface<IGroupsModule>();

            groupsModule.CreateGroup(client, "group1", "To boldly go", true, UUID.Zero, 5, true, true, true);
        }
    }
}


text:
<?php

namespace helgart\RESTBundle\DependencyInjection;

use helgart\RESTBundle\Exception\MissingBundleConfigurationException;
use helgart\RESTBundle\Exception\MissingBundleException;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

class helgartRESTExtension extends Extension implements PrependExtensionInterface
{
    protected $mandatoryBundles = [
        'FOSRestBundle',
        'NelmioCorsBundle'
    ];

    protected $optionalBundles = [
        'NelmioApiDocBundle'
    ];

    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
    }

    public function prepend(ContainerBuilder $container)
    {
        $bundles = $container->getParameter('kernel.bundles');

        foreach ($this->mandatoryBundles as $mandatoryBundle) {
            if (!array_key_exists($mandatoryBundle, $bundles)) {
                throw new MissingBundleException("Bundle $mandatoryBundle is missing");
            }

            if (!file_exists(__DIR__ . '/../Resources/config/' . $mandatoryBundle . 'Config.yml')) {
                throw new MissingBundleConfigurationException('Configuration file ' . __DIR__ . '/../Resources/config/' . $mandatoryBundle . 'Config.yml is missing');
            }

            $bundleConfig = Yaml::parse(file_get_contents(__DIR__ . '/../Resources/config/' . $mandatoryBundle . 'Config.yml'));

            $this->prependBundleConfig($container, $bundleConfig);
        }

        foreach ($this->optionalBundles as $optionalBundle) {
            if (file_exists(__DIR__ . '/../Resources/config/' . $optionalBundle . 'Config.yml')) {
                $bundleConfig = Yaml::parse(file_get_contents(__DIR__ . '/../Resources/config/' . $optionalBundle . 'Config.yml'));

                $this->prependBundleConfig($container, $bundleConfig);
            }
        }
    }

    protected function prependBundleConfig(ContainerBuilder $container, array $bundleConfig)
    {
        foreach ($bundleConfig as $extension => $config) {
            $container->prependExtensionConfig($extension, $config);
        }
    }
}


text:
#import <UIKit/UIKit.h>
#import <Foundation/NSNetServices.h>
#import "SimpleEditViewController.h"

@class DomainViewController;

@protocol DomainViewControllerDelegate <NSObject>
@required
// This method will be invoked when the user selects one of the domains from the list.
// The domain parameter will be the selected domain or nil if the user taps the 'Cancel' button (if shown)
- (void) domainViewController:(DomainViewController*)dvc didSelectDomain:(NSString*)domain;
@end

@interface DomainViewController : UITableViewController <SimpleEditViewControllerDelegate, NSNetServiceBrowserDelegate> {
	id<DomainViewControllerDelegate> _delegate;
	BOOL _showDisclosureIndicators;
	NSMutableArray* _domains;
	NSMutableArray* _customs;
	NSString* _customTitle;
	NSString* _addDomainTitle;
	NSNetServiceBrowser* _netServiceBrowser;
	BOOL _showCancelButton;
}

@property(nonatomic, assign) id<DomainViewControllerDelegate> delegate;

- (id)initWithTitle:(NSString *)title showDisclosureIndicators:(BOOL)showDisclosureIndicators customsTitle:(NSString*)customsTitle customs:(NSMutableArray*)customs addDomainTitle:(NSString*)addDomainTitle showCancelButton:(BOOL)showCancelButton;
- (BOOL)searchForBrowsableDomains;
- (BOOL)searchForRegistrationDomains;

@end


text:
package com.betfair.cougar.util;

import java.util.Map;

import com.betfair.cougar.api.Validatable;

public class ValidationUtils {
	public static void validateMandatory(Object candidate) {
		if (candidate != null) {
			if (candidate instanceof Validatable) {
				((Validatable)candidate).validateMandatory();
			} else if (candidate instanceof Iterable<?>) {
				for (Object o: (Iterable<?>)candidate) {
					validateMandatory(o);
				}
			} else if (candidate instanceof Map<?,?>) {
				for (Object o: (Iterable<?>)((Map<?,?>) candidate).values()) {
					validateMandatory(o);
				}
			}

		}
	}
}


text:
namespace nimbus
{

namespace io
{

class IInputStream
{
public:
	virtual ~IInputStream();

	virtual uint64_t read(void* data, uint64_t size) = 0;
};

}

}


text:
package cz.cuni.mff.d3s.spl.test;

import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

import mockit.Mock;
import mockit.MockClass;
import mockit.Mockit;

import cz.cuni.mff.d3s.spl.agent.Access;
import cz.cuni.mff.d3s.spl.core.data.DataSource;
import cz.cuni.mff.d3s.spl.core.data.SerieDataSource;
import cz.cuni.mff.d3s.spl.core.data.Statistics;
import cz.cuni.mff.d3s.spl.core.data.artificial.ArtificialSerieDataSource;
import cz.cuni.mff.d3s.spl.core.data.segment.SlidingSerieDataSource;

public class SilidingSerieDataSourceTest {
	private static final double EPSILON = 0.0001;
	private static final long SEC_TO_MILLIS = 1000;
	private static final long MILLIS_TO_NANOS = 1000 * 1000;

	private static long suiteStartTimeMillis = 0;
	private static long suiteStartTimeNanos = 0;

	private ArtificialSerieDataSource source;

	@MockClass(realClass = System.class)
	public static class SystemMock {
		public static long mockClockMillis = 0;

		@Mock
		public static long currentTimeMillis() {
			return mockClockMillis;
		}
	}

	@BeforeClass
	public static void initTimeSources() {
		suiteStartTimeMillis = System.currentTimeMillis();
		suiteStartTimeNanos = System.nanoTime();
	}

	@Before
	public void prepareSource() {
		source = new ArtificialSerieDataSource("junit.test.sliding");
		/* Add sample where position in time is sample value. */
		for (int i = 0; i <= 100; i++) {
			source.addSample(i, i * SEC_TO_MILLIS);
		}
	}

	@Before
	public void mockSystemClass() {
		Mockit.setUpMock(SystemMock.class);
	}

	@After
	public void pseudoSyncMockedClock() {
		long currentTimeNanos = System.nanoTime();
		long diffNanos = currentTimeNanos - suiteStartTimeNanos;
		long diffMillis = diffNanos / MILLIS_TO_NANOS;
		long predictedClock = suiteStartTimeMillis + diffMillis;
		SystemMock.mockClockMillis = predictedClock;
	}

	@After
	public void clearCollectedSamples() {
		Access.clearAllSamples();
	}

	private void assertMockClock(long expectedTime) {
		long actualCurrentTime = System.currentTimeMillis();
		assertEquals(expectedTime, actualCurrentTime);
	}

	private void setMockedClock(long newCurrentTimeMillis) {
		SystemMock.mockClockMillis = newCurrentTimeMillis;
		assertMockClock(newCurrentTimeMillis);
	}

	@Test
	public void mockingCurrentTimeMillisWorks() {
		setMockedClock(0);
		setMockedClock(1000);
		setMockedClock(12345);
	}

	private void checkSourceStats(DataSource dataSource,
			int expectedSampleCount, double expectedMean) {
		Statistics stats = dataSource.get();
		assertEquals(expectedSampleCount, stats.getSampleCount());
		assertEquals(expectedMean, stats.getArithmeticMean(), EPSILON);
	}

	@Test
	public void slidingSourceOnTheWholeData() {
		setMockedClock(100 * SEC_TO_MILLIS + 1);
		SerieDataSource allData = SlidingSerieDataSource.create(source, 0, 100);
		checkSourceStats(allData, 100, 50.5);
		assertMockClock(100 * SEC_TO_MILLIS + 1);
	}

	@Test
	public void slidingSourceLastSeconds() {
		setMockedClock(100 * SEC_TO_MILLIS + 1);
		SerieDataSource allData = SlidingSerieDataSource.create(source, 0, 5);
		checkSourceStats(allData, 5, 98.0);
		assertMockClock(100 * SEC_TO_MILLIS + 1);
	}

	@Test
	public void slidingSourceInTheMiddleOfTheData() {
		setMockedClock(100 * SEC_TO_MILLIS + 1);
		SerieDataSource allData = SlidingSerieDataSource.create(source, 60, 10);
		checkSourceStats(allData, 10, 35.5);
		assertMockClock(100 * SEC_TO_MILLIS + 1);
	}
}


text:
<?php

namespace Phlexible\Bundle\QueueBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * Queue extension
 *
 * @author Stephan Wentz <sw@brainbits.net>
 */
class PhlexibleQueueExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $config, ContainerBuilder $container)
    {
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        $loader->load('doctrine.yml');
        $container->setAlias('phlexible_queue.job_manager', 'phlexible_queue.doctrine.job_manager');
    }
}


text:
package japsa.bio.misc.common;

import java.io.*;

abstract public class Mutation_1State extends Mutation_FSM {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private class FSM_Params implements Serializable {
		/**
		 *
		 */
		private static final long serialVersionUID = 1L;
		double indel_cost, diag_cost;
		Two_Seq_Model_Counts s;

		FSM_Params(Two_Seq_Model_Counts s, double indel_cost, double diag_cost) {
			this.s = s;
			this.indel_cost = indel_cost;
			this.diag_cost = diag_cost;

			normalize_costs();
		}

		FSM_Params(Two_Seq_Model_Counts s, Params p) {
			this.s = s;

			if (!p.exists("indel_cost")) {
				set_default_costs();
			} else {
				indel_cost = p.get("indel_cost");
				diag_cost = p.get("diag_cost");
			}

			normalize_costs();
		}

		void set_default_costs() {
			indel_cost = 1;
			diag_cost = 0;
		}

		void normalize_costs() {
			double sum = 2 * MyMath.exp2(-indel_cost) + MyMath.exp2(-diag_cost);
			indel_cost = indel_cost + MyMath.log2(sum);
			diag_cost = diag_cost + MyMath.log2(sum);
			// VNTRReadDepth.printf("ins_cost=%.5f del_cost=%.5f diag_cost=%.5f\n",
			// ins_cost, del_cost, diag_cost);
		}

		public String toString() {
			return "diag_cost=" + diag_cost + " indel_cost=" + indel_cost;
		}
	}

	FSM_Params p;

	double val;

	final protected int indelIndex = 0, diagIndex = 1;

	public Mutation_1State(Two_Seq_Model_Counts s, double indel_cost,
			double diag_cost, int numCounts, int countIndex) {
		super(numCounts, countIndex);
		p = new FSM_Params(s, indel_cost, diag_cost);
		reset();
	}

	public Mutation_1State(Two_Seq_Model_Counts s, Params par, int numCounts,
			int countIndex) {
		super(numCounts, countIndex);
		p = new FSM_Params(s, par);
		reset();
	}

	public Mutation_1State(FSM_Params p, int numCounts, int countIndex) {
		super(numCounts, countIndex);
		this.p = p;
		reset();
	}

	public void reset() {
		super.reset();
		val = MyMath.Big_Double;
		counts.zero();
	}

	public static int required_counts() {
		return 2;
	};

	// counts_to_params - convert counts into parameters.
	// Call the Two_Seq_Model to convert its own.
	// Note the 0.5* in the indel computation. This is cause there are 2 indel
	// arcs out
	// of each state, but we only have one count for them combined.
	public Params counts_to_params(Counts c) {
		double sum = c.counts[countIndex + indelIndex]
				+ c.counts[countIndex + diagIndex];
		Params par = new Params();
		par.put("indel_cost",
				-MyMath.log2(0.5 * c.counts[countIndex + indelIndex] / sum));
		par.put("diag_cost",
				-MyMath.log2(c.counts[countIndex + diagIndex] / sum));
		par.join(p.s.counts_to_params(c));
		return par;
	};

	public double encode_params() {
		Counts c = get_counts();

		// First encode match/change paramters. Pass the number of these events
		// to encode_params
		double len = p.s.encode_params(c.counts[countIndex + diagIndex]);

		double dataLen = c.counts[countIndex + diagIndex]
				+ c.counts[countIndex + indelIndex];

		len += Multinomial.MMLparameter_cost(
				new double[] { MyMath.exp2(-p.indel_cost),
						MyMath.exp2(-p.diag_cost) }, dataLen);
		return len;
	}

	public double alignmentLength() {
		Counts c = get_counts();
		return c.counts[countIndex + indelIndex]
				+ c.counts[countIndex + diagIndex];
	}

	public void init_val(double v) {
		val = v;
	};

	public double get_val() {
		return val;
	};

	public void normalise(double v) {
		val -= v;
	}

	public String paramsToString() {
		return this.getClass() + ": " + p + "\n";
	}

	public String toString() {
		return "val=" + val + " counts=" + counts + "\n";
	}

	public void add(double v, int cIndex) {
		val += v;
		if (cIndex >= 0)
			counts.inc(cIndex, 1);
	}

	public static class One extends Mutation_1State implements TraceBack_Info {
		/**
		 *
		 */
		private static final long serialVersionUID = 1L;
		TraceBack_Data id;
		TraceBack_Data from;

		public One(FSM_Params p, int numCounts, int countIndex) {
			super(p, numCounts, countIndex);
			id = null;
			from = null;
		}

		public One(Two_Seq_Model_Counts s, Params par, int numCounts,
				int countIndex) {
			super(s, par, numCounts, countIndex);
			id = null;
			from = null;
		}

		public void set_tbdata(TraceBack_Data id) {
			this.id = id;
		}

		public TraceBack_Data get_tbdata() {
			return id;
		}

		public TraceBack_Data get_from(TraceBack_Data td) {
			Misc.my_assert(td.i == id.i && td.j == id.j,
					"Not my traceback data!");
			return from;
		}

		public Object clone() {
			return new Mutation_1State.One(p, numCounts, countIndex);
		}

		public void calc(Mutation_FSM h, Mutation_FSM v, Mutation_FSM d,
				char a, char b, int i, int j) {
			Mutation_1State.One hcell = (Mutation_1State.One) h;
			Mutation_1State.One vcell = (Mutation_1State.One) v;
			Mutation_1State.One dcell = (Mutation_1State.One) d;

			Counts tcounts = (Counts) counts.clone();
			if (hcell != null) {
				double w = val + p.indel_cost + p.s.encB(b, j);

				tcounts.duplicate(counts);
				tcounts.inc(countIndex + indelIndex, 1);
				p.s.update_count_encB(tcounts, 1, b, j);

				hcell.or(w, tcounts, this);
			}

			if (vcell != null) {
				double w = val + p.indel_cost + p.s.encA(a, i);

				tcounts.duplicate(counts);
				tcounts.inc(countIndex + indelIndex, 1);
				p.s.update_count_encA(tcounts, 1, a, i);

				vcell.or(w, tcounts, this);
			}

			if (dcell != null) {
				double w = val + p.diag_cost + p.s.encBoth(a, b, i, j);

				tcounts.duplicate(counts);
				tcounts.inc(countIndex + diagIndex, 1);
				p.s.update_count_encBoth(tcounts, 1, a, b, i, j);

				dcell.or(w, tcounts, this);
			}
		};

		public void or(double d, Counts c) {
			or(d, c, null);
		}

		public void or(double d, Counts c, Mutation_FSM f) {
			if (d < val) {
				counts.duplicate(c);
				val = d;
				from = (f == null ? null : ((One) f).id);
			}
		}

	}

	public static class All extends Mutation_1State {
		private static final long serialVersionUID = 1L;

		public All(FSM_Params p, int numCounts, int countIndex) {
			super(p, numCounts, countIndex);
		}

		public All(Two_Seq_Model_Counts s, Params par, int numCounts,
				int countIndex) {
			super(s, par, numCounts, countIndex);
		}

		public Object clone() {
			return new Mutation_1State.All(p, numCounts, countIndex);
		}

		public void calc(Mutation_FSM h, Mutation_FSM v, Mutation_FSM d,
				char a, char b, int i, int j) {
			Mutation_1State.All hcell = (Mutation_1State.All) h;
			Mutation_1State.All vcell = (Mutation_1State.All) v;
			Mutation_1State.All dcell = (Mutation_1State.All) d;

			if (hcell != null) {
				double w = val + p.indel_cost + p.s.encB(b, j);
				double count_inc = 1.0 / (1.0 + MyMath.exp2(w - hcell.val));
				if (Double.isNaN(count_inc))
					count_inc = 0;
				hcell.or(w, counts);
				hcell.p.s.update_count_encB(hcell.counts, count_inc, b, j);
				hcell.counts.inc(countIndex + indelIndex, count_inc);
			}

			if (vcell != null) {
				double w = val + p.indel_cost + p.s.encA(a, i);
				double count_inc = 1.0 / (1.0 + MyMath.exp2(w - vcell.val));
				if (Double.isNaN(count_inc))
					count_inc = 0;
				vcell.or(w, counts);
				vcell.p.s.update_count_encA(vcell.counts, count_inc, a, i);
				vcell.counts.inc(countIndex + indelIndex, count_inc);
			}

			if (dcell != null) {
				double w = val + p.diag_cost + p.s.encBoth(a, b, i, j);
				double count_inc = 1.0 / (1.0 + MyMath.exp2(w - dcell.val));
				if (Double.isNaN(count_inc))
					count_inc = 0;
				dcell.or(w, counts);
				dcell.p.s.update_count_encBoth(dcell.counts, count_inc, a, b,
						i, j);
				dcell.counts.inc(countIndex + diagIndex, count_inc);
			}
		};

		public void or(double d, Counts c) {
			// Update the counts first
			counts.combine_with_lens(val, c, d);
			val = MyMath.logplus(val, d);
		}
	}

}


text:
package com.wandrell.tabletop.testing.punkapocalyptic.framework.framework.util.parser;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.LinkedList;

import org.jdom2.Document;
import org.jdom2.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wandrell.pattern.parser.Parser;
import com.wandrell.tabletop.testing.punkapocalyptic.framework.framework.conf.TestXMLConf;

public final class UpToHalfDocumentParser implements
        Parser<Document, Collection<Collection<Object>>> {

    private static final Logger logger = LoggerFactory
                                               .getLogger(UpToHalfDocumentParser.class);

    private static final Logger getLogger() {
        return logger;
    }

    public UpToHalfDocumentParser() {
        super();
    }

    @Override
    public final Collection<Collection<Object>> parse(final Document doc) {
        final Collection<Collection<Object>> colData;

        colData = new LinkedHashSet<>();
        for (final Element node : doc.getRootElement().getChildren()) {
            colData.add(readNode(node));
        }

        return colData;
    }

    private final Collection<Object> readNode(final Element node) {
        final Collection<Object> data;
        final Integer units;
        final Integer total;

        units = Integer.parseInt(node.getChild(TestXMLConf.NODE_UNITS)
                .getText());
        total = Integer.parseInt(node.getChild(TestXMLConf.NODE_GANG_SIZE)
                .getText());

        data = new LinkedList<>();
        data.add(units);
        data.add(total);

        getLogger().debug(
                String.format("Read constraint for %d units of a total of %d",
                        units, total));

        return data;
    }

}


text:
package org.vitrivr.adampro.utils

import org.apache.logging.log4j.Logger
import org.apache.logging.log4j.LogManager

/**
  * ADAMpro
  *
  * Ivan Giangreco
  * June 2016
  */
trait Logging {
  @transient private var log_ : Logger = null

  /**
    *
    * @return
    */
  protected def logName = {
    this.getClass.getName.stripSuffix("$")
  }

  /**
    *
    * @return
    */
  protected def log: Logger = {
    if (log_ == null) {
      log_ = LogManager.getLogger(logName)
    }
    log_
  }
}


text:
package com.ajayhao.simpleboot.common.exception;

import com.ajayhao.simpleboot.common.BaseResultType;

/**
 *

 * @author haozhenjie
 * @version $Id: BusinessBizException.java
 */
public class BusinessBizException extends RuntimeException {

    private static final long    serialVersionUID = 1L;

    private final BaseResultType type;

    /**
     * BusinessException
     *
     * @param type
     * @param args
     */
    public BusinessBizException(BaseResultType type, Object... args) {
        super(MessageBundle.getString(type, args));
        this.type = type;
    }

    /**
     * Gets code.
     *
     * @return the code
     */
    public String getCode() {
        return type.getCode();
    }

    /**
     *
     *

     * @return
     */
    public String getMsg() {
        return type.getMessage();
    }

    /**
     *
     *

     * @return
     */
    public BaseResultType getType() {
        return type;
    }
}


text:
namespace chainerx {

// Intermediate results from `BatchNormKernel::Call` can be stored in this construct and be reused in `BatchNormGradKernel::Call`.
// The objects to store may vary depending on backend so each backend should derive this class to define the actual set of intermediate
// results.
class BatchNormGradState {
public:
    BatchNormGradState() = default;

    virtual ~BatchNormGradState() = default;

    BatchNormGradState(const BatchNormGradState&) = default;
    BatchNormGradState(BatchNormGradState&&) = default;
    BatchNormGradState& operator=(const BatchNormGradState&) = default;
    BatchNormGradState& operator=(BatchNormGradState&&) = default;
};

class BatchNormKernel : public Kernel {
public:
    // The returned state should be a `nullptr` if `return_state` is `false`.
    virtual std::tuple<Array, std::unique_ptr<BatchNormGradState>> Call(
            const Array& x,
            const Array& gamma,
            const Array& beta,
            const Array& running_mean,
            const Array& running_var,
            Scalar eps,
            Scalar decay,
            const Axes& axis,
            bool return_state,
            const absl::optional<Array>& out) = 0;
};

class BatchNormGradKernel : public Kernel {
public:
    // Returns gx, ggamma, gbeta.
    virtual std::tuple<Array, Array, Array> Call(
            const Array& x,
            const Array& gamma,
            const Array& gout,
            Scalar eps,
            const Axes& axis,
            const std::shared_ptr<BatchNormGradState>& state,
            const absl::optional<Array>& gx,
            const absl::optional<Array>& ggamma,
            const absl::optional<Array>& gbeta) = 0;
};

class GenericBatchNormGradState : public BatchNormGradState {
public:
    GenericBatchNormGradState(Array x_mean, Array x_inv_std, Dtype beta_dtype)
        : x_mean_{std::move(x_mean)}, x_inv_std_{std::move(x_inv_std)}, beta_dtype_{beta_dtype} {}

    const Array& x_mean() const { return x_mean_; }
    const Array& x_inv_std() const { return x_inv_std_; }
    Dtype beta_dtype() const { return beta_dtype_; }

private:
    Array x_mean_;
    Array x_inv_std_;
    Dtype beta_dtype_;
};

class GenericBatchNormKernel : public BatchNormKernel {
public:
    std::tuple<Array, std::unique_ptr<BatchNormGradState>> Call(
            const Array& x,
            const Array& gamma,
            const Array& beta,
            const Array& running_mean,
            const Array& running_var,
            Scalar eps,
            Scalar decay,
            const Axes& axis,
            bool return_state,
            const absl::optional<Array>& out) override;
};

class GenericBatchNormGradKernel : public BatchNormGradKernel {
public:
    std::tuple<Array, Array, Array> Call(
            const Array& x,
            const Array& gamma,
            const Array& gout,
            Scalar eps,
            const Axes& axis,
            const std::shared_ptr<BatchNormGradState>& state,
            const absl::optional<Array>& gx,
            const absl::optional<Array>& ggamma,
            const absl::optional<Array>& gbeta) override;
};

class FixedBatchNormKernel : public Kernel {
public:
    virtual Array Call(
            const Array& x,
            const Array& gamma,
            const Array& beta,
            const Array& mean,
            const Array& var,
            Scalar eps,
            const Axes& axis,
            const absl::optional<Array>& out) = 0;
};

class GenericFixedBatchNormKernel : public FixedBatchNormKernel {
public:
    Array Call(
            const Array& x,
            const Array& gamma,
            const Array& beta,
            const Array& mean,
            const Array& var,
            Scalar eps,
            const Axes& axis,
            const absl::optional<Array>& out) override;
};

}  // namespace chainerx


text:
The player proposing a rule may score additional points if, during discussion (i.e. within comments in a Pull Request), he or she refrains from using the following strings (case insensitive):

* Rule
* Vote
* Score
* Proposal
* Repeal
* Amend

The player receives an additional half of total points earned for a successful proposal. For a defeated proposal, a player receives five points.


text:
//------------------------------------------------------------------------------
// <copyright file="CategoryAttribute.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

/*
 */
namespace System.ComponentModel {
    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Security.Permissions;

    /// <devdoc>
    ///    <para>Specifies the category in which the property or event will be displayed in a
    ///       visual designer.</para>
    /// </devdoc>
    [AttributeUsage(AttributeTargets.All)]
    public class CategoryAttribute : Attribute {
        private static volatile CategoryAttribute appearance;
        private static volatile CategoryAttribute asynchronous;
        private static volatile CategoryAttribute behavior;
        private static volatile CategoryAttribute data;
        private static volatile CategoryAttribute design;
        private static volatile CategoryAttribute action;
        private static volatile CategoryAttribute format;
        private static volatile CategoryAttribute layout;
        private static volatile CategoryAttribute mouse;
        private static volatile CategoryAttribute key;
        private static volatile CategoryAttribute focus;
        private static volatile CategoryAttribute windowStyle;
        private static volatile CategoryAttribute dragDrop;
        private static volatile CategoryAttribute defAttr;

        private bool localized;

        /// <devdoc>
        ///    <para>
        ///       Provides the actual category name.
        ///    </para>
        /// </devdoc>
        private string categoryValue;

        /// <devdoc>
        ///    <para>Gets the action category attribute.</para>
        /// </devdoc>
        public static CategoryAttribute Action {
            get {
                if (action == null) {
                    action = new CategoryAttribute("Action");
                }
                return action;
            }
        }

        /// <devdoc>
        ///    <para>Gets the appearance category attribute.</para>
        /// </devdoc>
        public static CategoryAttribute Appearance {
            get {
                if (appearance == null) {
                    appearance = new CategoryAttribute("Appearance");
                }
                return appearance;
            }
        }

        /// <devdoc>
        ///    <para>Gets the asynchronous category attribute.</para>
        /// </devdoc>
        public static CategoryAttribute Asynchronous {
            get {
                if (asynchronous == null) {
                    asynchronous = new CategoryAttribute("Asynchronous");
                }
                return asynchronous;
            }
        }

        /// <devdoc>
        ///    <para>Gets the behavior category attribute.</para>
        /// </devdoc>
        public static CategoryAttribute Behavior {
            get {
                if (behavior == null) {
                    behavior = new CategoryAttribute("Behavior");
                }
                return behavior;
            }
        }

        /// <devdoc>
        ///    <para>Gets the data category attribute.</para>
        /// </devdoc>
        public static CategoryAttribute Data {
            get {
                if (data == null) {
                    data = new CategoryAttribute("Data");
                }
                return data;
            }
        }

        /// <devdoc>
        ///    <para>Gets the default category attribute.</para>
        /// </devdoc>
        public static CategoryAttribute Default {
            get {
                if (defAttr == null) {
                    defAttr = new CategoryAttribute();
                }
                return defAttr;
            }
        }

        /// <devdoc>
        ///    <para>Gets the design category attribute.</para>
        /// </devdoc>
        public static CategoryAttribute Design {
            get {
                if (design == null) {
                    design = new CategoryAttribute("Design");
                }
                return design;
            }
        }

        /// <devdoc>
        ///    <para>Gets the drag and drop category attribute.</para>
        /// </devdoc>
        public static CategoryAttribute DragDrop {
            get {
                if (dragDrop == null) {
                    dragDrop = new CategoryAttribute("DragDrop");
                }
                return dragDrop;
            }
        }

        /// <devdoc>
        ///    <para>Gets the focus category attribute.</para>
        /// </devdoc>
        public static CategoryAttribute Focus {
            get {
                if (focus == null) {
                    focus = new CategoryAttribute("Focus");
                }
                return focus;
            }
        }

        /// <devdoc>
        ///    <para>Gets the format category attribute.</para>
        /// </devdoc>
        public static CategoryAttribute Format {
            get {
                if (format == null) {
                    format = new CategoryAttribute("Format");
                }
                return format;
            }
        }

        /// <devdoc>
        ///    <para>Gets the keyboard category attribute.</para>
        /// </devdoc>
        public static CategoryAttribute Key {
            get {
                if (key == null) {
                    key = new CategoryAttribute("Key");
                }
                return key;
            }
        }

        /// <devdoc>
        ///    <para>Gets the layout category attribute.</para>
        /// </devdoc>
        public static CategoryAttribute Layout {
            get {
                if (layout == null) {
                    layout = new CategoryAttribute("Layout");
                }
                return layout;
            }
        }

        /// <devdoc>
        ///    <para>Gets the mouse category attribute.</para>
        /// </devdoc>
        public static CategoryAttribute Mouse {
            get {
                if (mouse == null) {
                    mouse = new CategoryAttribute("Mouse");
                }
                return mouse;
            }
        }

        /// <devdoc>
        ///    <para> Gets the window style category
        ///       attribute.</para>
        /// </devdoc>
        public static CategoryAttribute WindowStyle {
            get {
                if (windowStyle == null) {
                    windowStyle = new CategoryAttribute("WindowStyle");
                }
                return windowStyle;
            }
        }

        /// <devdoc>
        /// <para>Initializes a new instance of the <see cref='System.ComponentModel.CategoryAttribute'/>
        /// class with the default category.</para>
        /// </devdoc>
        public CategoryAttribute() : this("Default") {
        }

        /// <devdoc>
        /// <para>Initializes a new instance of the <see cref='System.ComponentModel.CategoryAttribute'/> class with
        ///    the specified category name.</para>
        /// </devdoc>
        public CategoryAttribute(string category) {
            this.categoryValue = category;
            this.localized = false;
        }

        /// <devdoc>
        ///    <para>Gets the name of the category for the property or event
        ///       that this attribute is bound to.</para>
        /// </devdoc>
        public string Category {
            get {
                if (!localized) {
                    localized = true;
                    string localizedValue = GetLocalizedString(categoryValue);
                    if (localizedValue != null) {
                        categoryValue = localizedValue;
                    }
                }
                return categoryValue;
            }
        }

        /// <devdoc>
        /// </devdoc>
        /// <devdoc>
        /// </devdoc>
        /// <internalonly/>
        /// <internalonly/>
        public override bool Equals(object obj){
            if (obj == this) {
                return true;
            }

            if (obj is CategoryAttribute){
                return Category.Equals(((CategoryAttribute)obj).Category);
            }
            return false;
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public override int GetHashCode() {
            return Category.GetHashCode();
        }

        /// <devdoc>
        ///    <para>Looks up the localized name of a given category.</para>
        /// </devdoc>
        protected virtual string GetLocalizedString(string value) {
#if !SILVERLIGHT
#if MONO
            switch (value) {
            case "Action":
                return "PropertyCategoryAction";
            case "Appearance":
                return "PropertyCategoryAppearance";
            case "Behavior":
                return "PropertyCategoryBehavior";
            case "Data":
                return "PropertyCategoryData";
            case "DDE":
                return "PropertyCategoryDDE";
            case "Design":
                return "PropertyCategoryDesign";
            case "Focus":
                return "PropertyCategoryFocus";
            case "Font":
                return "PropertyCategoryFont";
            case "Key":
                return "PropertyCategoryKey";
            case "List":
                return "PropertyCategoryList";
            case "Layout":
                return "PropertyCategoryLayout";
            case "Mouse":
                return "PropertyCategoryMouse";
            case "Position":
                return "PropertyCategoryPosition";
            case "Text":
                return "PropertyCategoryText";
            case "Scale":
                return "PropertyCategoryScale";
            case "Config":
                return "PropertyCategoryConfig";
#if !MOBILE
            case "Default":
                return "PropertyCategoryDefault";
            case "DragDrop":
                return "PropertyCategoryDragDrop";
            case "WindowStyle":
                return "PropertyCategoryWindowStyle";
#endif
            }
            return value;
#else
            return (string)SR.GetObject("PropertyCategory" + value);
#endif
#else
            bool usedFallback;
            string localizedString = SR.GetString("PropertyCategory" + value, out usedFallback);
            if (usedFallback) {
                return null;
            }
            return localizedString;
#endif
        }

#if !SILVERLIGHT
        /// <devdoc>
        /// </devdoc>
        /// <devdoc>
        /// </devdoc>
        /// <internalonly/>
        /// <internalonly/>
        public override bool IsDefaultAttribute() {
            return Category.Equals(Default.Category);
        }
#endif
    }
}


text:
import pytest

from httpie.compat import is_windows
from httpie.output.streams import BINARY_SUPPRESSED_NOTICE
from .utils import StdinBytesIO, http, MockEnvironment
from .fixtures import BIN_FILE_CONTENT, BIN_FILE_PATH

# GET because httpbin 500s with binary POST body.

@pytest.mark.skipif(is_windows,
                    reason='Pretty redirect not supported under Windows')
def test_pretty_redirected_stream(httpbin):
    """Test that --stream works with prettified redirected output."""
    env = MockEnvironment(
        colors=256,
        stdin=StdinBytesIO(BIN_FILE_PATH.read_bytes()),
        stdin_isatty=False,
        stdout_isatty=False,
    )
    r = http('--verbose', '--pretty=all', '--stream', 'GET',
             httpbin.url + '/get', env=env)
    assert BINARY_SUPPRESSED_NOTICE.decode() in r

def test_encoded_stream(httpbin):
    """Test that --stream works with non-prettified
    redirected terminal output."""
    env = MockEnvironment(
        stdin=StdinBytesIO(BIN_FILE_PATH.read_bytes()),
        stdin_isatty=False,
    )
    r = http('--pretty=none', '--stream', '--verbose', 'GET',
             httpbin.url + '/get', env=env)
    assert BINARY_SUPPRESSED_NOTICE.decode() in r

def test_redirected_stream(httpbin):
    """Test that --stream works with non-prettified
    redirected terminal output."""
    env = MockEnvironment(
        stdout_isatty=False,
        stdin_isatty=False,
        stdin=StdinBytesIO(BIN_FILE_PATH.read_bytes()),
    )
    r = http('--pretty=none', '--stream', '--verbose', 'GET',
             httpbin.url + '/get', env=env)
    assert BIN_FILE_CONTENT in r


text:
#ifndef __ALPHA_JENSEN_H
#define __ALPHA_JENSEN_H

/*
 * Defines for the AlphaPC EISA IO and memory address space.
 */

/*
 * NOTE! The memory operations do not set any memory barriers, as it's
 * not needed for cases like a frame buffer that is essentially memory-like.
 * You need to do them by hand if the operations depend on ordering.
 *
 * Similarly, the port IO operations do a "mb" only after a write operation:
 * if an mb is needed before (as in the case of doing memory mapped IO
 * first, and then a port IO operation to the same device), it needs to be
 * done by hand.
 *
 * After the above has bitten me 100 times, I'll give up and just do the
 * mb all the time, but right now I'm hoping this will work out.  Avoiding
 * mb's may potentially be a noticeable speed improvement, but I can't
 * honestly say I've tested it.
 *
 * Handling interrupts that need to do mb's to synchronize to non-interrupts
 * is another fun race area.  Don't do it (because if you do, I'll have to
 * do *everything* with interrupts disabled, ugh).
 */

/*
 * EISA Interrupt Acknowledge address
 */
#define EISA_INTA		(IDENT_ADDR + 0x100000000UL)

/*
 * FEPROM addresses
 */
#define EISA_FEPROM0		(IDENT_ADDR + 0x180000000UL)
#define EISA_FEPROM1		(IDENT_ADDR + 0x1A0000000UL)

/*
 * VL82C106 base address
 */
#define EISA_VL82C106		(IDENT_ADDR + 0x1C0000000UL)

/*
 * EISA "Host Address Extension" address (bits 25-31 of the EISA address)
 */
#define EISA_HAE		(IDENT_ADDR + 0x1D0000000UL)

/*
 * "SYSCTL" register address
 */
#define EISA_SYSCTL		(IDENT_ADDR + 0x1E0000000UL)

/*
 * "spare" register address
 */
#define EISA_SPARE		(IDENT_ADDR + 0x1F0000000UL)

/*
 * EISA memory address offset
 */
#define EISA_MEM		(IDENT_ADDR + 0x200000000UL)

/*
 * EISA IO address offset
 */
#define EISA_IO			(IDENT_ADDR + 0x300000000UL)

/*
 * Change virtual addresses to bus addresses and vv.
 *
 * NOTE! On the Jensen, the physical address is the same
 * as the bus address, but this is not necessarily true on
 * other alpha hardware.
 */
#define virt_to_bus virt_to_phys
#define bus_to_virt phys_to_virt

#define HAE_ADDRESS	EISA_HAE

/*
 * Handle the "host address register". This needs to be set
 * to the high 7 bits of the EISA address.  This is also needed
 * for EISA IO addresses, which are only 16 bits wide (the
 * hae needs to be set to 0).
 *
 * HAE isn't needed for the local IO operations, though.
 */
#define __HAE_MASK 0x1ffffff
extern inline void __set_hae(unsigned long addr)
{
	/* hae on the Jensen is bits 31:25 shifted right */
	addr >>= 25;
	if (addr != hae.cache)
		set_hae(addr);
}

/*
 * IO functions
 *
 * The "local" functions are those that don't go out to the EISA bus,
 * but instead act on the VL82C106 chip directly.. This is mainly the
 * keyboard, RTC,  printer and first two serial lines..
 *
 * The local stuff makes for some complications, but it seems to be
 * gone in the PCI version. I hope I can get DEC suckered^H^H^H^H^H^H^H^H
 * convinced that I need one of the newer machines.
 */
extern inline unsigned int __local_inb(unsigned long addr)
{
	long result = *(volatile int *) ((addr << 9) + EISA_VL82C106);
	return 0xffUL & result;
}

extern inline void __local_outb(unsigned char b, unsigned long addr)
{
	*(volatile unsigned int *) ((addr << 9) + EISA_VL82C106) = b;
	mb();
}

extern unsigned int _bus_inb(unsigned long addr);

extern inline unsigned int __bus_inb(unsigned long addr)
{
	long result;

	__set_hae(0);
	result = *(volatile int *) ((addr << 7) + EISA_IO + 0x00);
	result >>= (addr & 3) * 8;
	return 0xffUL & result;
}

extern void _bus_outb(unsigned char b, unsigned long addr);

extern inline void __bus_outb(unsigned char b, unsigned long addr)
{
	__set_hae(0);
	*(volatile unsigned int *) ((addr << 7) + EISA_IO + 0x00) = b * 0x01010101;
	mb();
}

/*
 * It seems gcc is not very good at optimizing away logical
 * operations that result in operations across inline functions.
 * Which is why this is a macro.
 */
#define __is_local(addr) ( \
/* keyboard */	(addr == 0x60 || addr == 0x64) || \
/* RTC */	(addr == 0x170 || addr == 0x171) || \
/* mb COM2 */	(addr >= 0x2f8 && addr <= 0x2ff) || \
/* mb LPT1 */	(addr >= 0x3bc && addr <= 0x3be) || \
/* mb COM2 */	(addr >= 0x3f8 && addr <= 0x3ff))

extern inline unsigned int __inb(unsigned long addr)
{
	if (__is_local(addr))
		return __local_inb(addr);
	return _bus_inb(addr);
}

extern inline void __outb(unsigned char b, unsigned long addr)
{
	if (__is_local(addr))
		__local_outb(b, addr);
	else
		_bus_outb(b, addr);
}

extern inline unsigned int __inw(unsigned long addr)
{
	long result;

	__set_hae(0);
	result = *(volatile int *) ((addr << 7) + EISA_IO + 0x20);
	result >>= (addr & 3) * 8;
	return 0xffffUL & result;
}

extern inline unsigned int __inl(unsigned long addr)
{
	__set_hae(0);
	return *(volatile unsigned int *) ((addr << 7) + EISA_IO + 0x60);
}

extern inline void __outw(unsigned short b, unsigned long addr)
{
	__set_hae(0);
	*(volatile unsigned int *) ((addr << 7) + EISA_IO + 0x20) = b * 0x00010001;
	mb();
}

extern inline void __outl(unsigned int b, unsigned long addr)
{
	__set_hae(0);
	*(volatile unsigned int *) ((addr << 7) + EISA_IO + 0x60) = b;
	mb();
}

/*
 * Memory functions.
 */
extern inline unsigned long __readb(unsigned long addr)
{
	long result;

	__set_hae(addr);
	addr &= __HAE_MASK;
	result = *(volatile int *) ((addr << 7) + EISA_MEM + 0x00);
	result >>= (addr & 3) * 8;
	return 0xffUL & result;
}

extern inline unsigned long __readw(unsigned long addr)
{
	long result;

	__set_hae(addr);
	addr &= __HAE_MASK;
	result = *(volatile int *) ((addr << 7) + EISA_MEM + 0x20);
	result >>= (addr & 3) * 8;
	return 0xffffUL & result;
}

extern inline unsigned long __readl(unsigned long addr)
{
	__set_hae(addr);
	addr &= __HAE_MASK;
	return *(volatile unsigned int *) ((addr << 7) + EISA_MEM + 0x60);
}

extern inline void __writeb(unsigned short b, unsigned long addr)
{
	__set_hae(addr);
	addr &= __HAE_MASK;
	*(volatile unsigned int *) ((addr << 7) + EISA_MEM + 0x00) = b * 0x01010101;
}

extern inline void __writew(unsigned short b, unsigned long addr)
{
	__set_hae(addr);
	addr &= __HAE_MASK;
	*(volatile unsigned int *) ((addr << 7) + EISA_MEM + 0x20) = b * 0x00010001;
}

extern inline void __writel(unsigned int b, unsigned long addr)
{
	__set_hae(addr);
	addr &= __HAE_MASK;
	*(volatile unsigned int *) ((addr << 7) + EISA_MEM + 0x60) = b;
}

/*
 * The above have so much overhead that it probably doesn't make
 * sense to have them inlined (better icache behaviour).
 */
#define inb(port) \
(__builtin_constant_p((port))?__inb(port):_inb(port))

#define outb(x, port) \
(__builtin_constant_p((port))?__outb((x),(port)):_outb((x),(port)))

/*
 * The Alpha Jensen hardware for some rather strange reason puts
 * the RTC clock at 0x170 instead of 0x70. Probably due to some
 * misguided idea about using 0x70 for NMI stuff.
 *
 * These defines will override the defaults when doing RTC queries
 */
#define RTC_PORT(x)	(0x170+(x))
#define RTC_ADDR(x)	(x)
#define RTC_ALWAYS_BCD	0

#endif


text:
package org.cstamas.vertx.sisu.examples;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;

import io.vertx.core.DeploymentOptions;

@Named
@Singleton
public class MyComponent
{
  private final DeploymentOptions deploymentOptions;

  @Inject
  public MyComponent(final DeploymentOptions deploymentOptions)
  {
    this.deploymentOptions = deploymentOptions;
  }

  public String getReply() {
    return "Hello " + getReplyString();
  }

  public static final String DEFAULT_REPLY = "DEFAULT";

  private String getReplyString() {
    if (deploymentOptions.getConfig() != null) {
      return deploymentOptions.getConfig().getString("reply.test", DEFAULT_REPLY);
    }
    return DEFAULT_REPLY;
  }
}


text:
(function() {
  'use strict';
  var Cache, Resource, Verb, defaultOpts, deleteWarning, encode64, error, inheritExtend, s, stringify, validateOpts, validateStr;

  error = function(msg) {
    throw "ERROR: jquery.rest: " + msg;
  };

  s = function(n) {
    var t;

    t = "";
    while (n-- > 0) {
      t += "  ";
    }
    return t;
  };

  encode64 = function(s) {
    if (!window.btoa) {
      error("You need a polyfill for 'btoa' to use basic auth.");
    }
    return window.btoa(s);
  };

  stringify = function(obj) {
    if (!window.JSON) {
      error("You need a polyfill for 'JSON' to use stringify.");
    }
    return window.JSON.stringify(obj);
  };

  inheritExtend = function(a, b) {
    var F;

    F = function() {};
    F.prototype = a;
    return $.extend(true, new F(), b);
  };

  validateOpts = function(options) {
    if (!(options && $.isPlainObject(options))) {
      return false;
    }
    $.each(options, function(name) {
      if (defaultOpts[name] === undefined) {
        return error("Unknown option: '" + name + "'");
      }
    });
    return null;
  };

  validateStr = function(name, str) {
    if ('string' !== $.type(str)) {
      return error("'" + name + "' must be a string");
    }
  };

  deleteWarning = function() {
    return alert('"delete()" has been deprecated. Please use "destroy()" or "del()" instead.');
  };

  defaultOpts = {
    url: '',
    cache: 0,
    cachableMethods: ['GET'],
    stringifyData: false,
    stripTrailingSlash: false,
    password: null,
    username: null,
    verbs: {
      'create': 'POST',
      'read': 'GET',
      'update': 'PUT',
      'destroy': 'DELETE'
    },
    ajax: {
      dataType: 'json'
    }
  };

  Cache = (function() {
    function Cache(parent) {
      this.parent = parent;
      this.c = {};
    }

    Cache.prototype.valid = function(date) {
      var diff;

      diff = new Date().getTime() - date.getTime();
      return diff <= this.parent.opts.cache * 1000;
    };

    Cache.prototype.key = function(obj) {
      var key,
        _this = this;

      key = "";
      $.each(obj, function(k, v) {
        return key += k + "=" + ($.isPlainObject(v) ? "{" + _this.key(v) + "}" : v) + "|";
      });
      return key;
    };

    Cache.prototype.get = function(key) {
      var result;

      result = this.c[key];
      if (!result) {
        return;
      }
      if (this.valid(result.created)) {
        return result.data;
      }
    };

    Cache.prototype.put = function(key, data) {
      return this.c[key] = {
        created: new Date(),
        data: data
      };
    };

    Cache.prototype.clear = function(regexp) {
      var _this = this;

      if (regexp) {
        return $.each(this.c, function(k) {
          if (k.match(regexp)) {
            return delete _this.c[k];
          }
        });
      } else {
        return this.c = {};
      }
    };

    return Cache;

  })();

  Verb = (function() {
    function Verb(name, method, options, parent) {
      this.name = name;
      this.method = method;
      if (options == null) {
        options = {};
      }
      this.parent = parent;
      validateStr('name', this.name);
      validateStr('method', this.method);
      validateOpts(options);
      if (this.parent[this.name]) {
        error("Cannot add Verb: '" + name + "' already exists");
      }
      this.method = method.toUpperCase();
      if (!options.url) {
        options.url = '';
      }
      this.opts = inheritExtend(this.parent.opts, options);
      this.root = this.parent.root;
      this.custom = !defaultOpts.verbs[this.name];
      this.call = $.proxy(this.call, this);
      this.call.instance = this;
    }

    Verb.prototype.call = function() {
      var r;

      r = this.parent.extractUrlData(this.method, arguments);
      if (this.custom) {
        r.url += this.opts.url || this.name;
      }
      return this.parent.ajax.call(this, this.method, r.url, r.data);
    };

    Verb.prototype.show = function(d) {
      return console.log(s(d) + this.name + ": " + this.method);
    };

    return Verb;

  })();

  Resource = (function() {
    function Resource(nameOrUrl, options, parent) {
      if (options == null) {
        options = {};
      }
      validateOpts(options);
      if (parent && parent instanceof Resource) {
        this.name = nameOrUrl;
        validateStr('name', this.name);
        this.constructChild(parent, options);
      } else {
        this.url = nameOrUrl || '';
        validateStr('url', this.url);
        this.constructRoot(options);
      }
    }

    Resource.prototype.constructRoot = function(options) {
      this.opts = inheritExtend(defaultOpts, options);
      this.root = this;
      this.numParents = 0;
      this.urlNoId = this.url;
      this.cache = new Cache(this);
      this.parent = null;
      return this.name = this.opts.name || 'ROOT';
    };

    Resource.prototype.constructChild = function(parent, options) {
      this.parent = parent;
      validateStr('name', this.name);
      if (!(this.parent instanceof Resource)) {
        this.error("Invalid parent");
      }
      if (this.parent[this.name]) {
        this.error("'" + name + "' already exists");
      }
      if (!options.url) {
        options.url = '';
      }
      this.opts = inheritExtend(this.parent.opts, options);
      this.root = this.parent.root;
      this.numParents = this.parent.numParents + 1;
      this.urlNoId = this.parent.url + ("" + (this.opts.url || this.name) + "/");
      this.url = this.urlNoId + (":ID_" + this.numParents + "/");
      $.each(this.opts.verbs, $.proxy(this.addVerb, this));
      if (this.destroy) {
        this.del = this.destroy;
        return this["delete"] = deleteWarning;
      }
    };

    Resource.prototype.error = function(msg) {
      return error("Cannot add Resource: " + msg);
    };

    Resource.prototype.add = function(name, options) {
      return this[name] = new Resource(name, options, this);
    };

    Resource.prototype.addVerb = function(name, method, options) {
      return this[name] = new Verb(name, method, options, this).call;
    };

    Resource.prototype.show = function(d) {
      var _this = this;

      if (d == null) {
        d = 0;
      }
      if (d > 25) {
        error("Plugin Bug! Recursion Fail");
      }
      if (this.name) {
        console.log(s(d) + this.name + ": " + this.url);
      }
      $.each(this, function(name, fn) {
        if ($.type(fn) === 'function' && fn.instance instanceof Verb && name !== 'del') {
          return fn.instance.show(d + 1);
        }
      });
      $.each(this, function(name, res) {
        if (name !== "parent" && name !== "root" && res instanceof Resource) {
          return res.show(d + 1);
        }
      });
      return null;
    };

    Resource.prototype.toString = function() {
      return this.name;
    };

    Resource.prototype.extractUrlData = function(name, args) {
      var arg, canUrl, canUrlNoId, data, i, id, ids, msg, numIds, t, url, _i, _j, _len, _len1;

      ids = [];
      data = null;
      for (_i = 0, _len = args.length; _i < _len; _i++) {
        arg = args[_i];
        t = $.type(arg);
        if (t === 'string' || t === 'number') {
          ids.push(arg);
        } else if ($.isPlainObject(arg) && data === null) {
          data = arg;
        } else {
          error(("Invalid argument: " + arg + " (" + t + ").") + " Must be strings or ints (IDs) followed by one optional plain object (data).");
        }
      }
      numIds = ids.length;
      canUrl = name !== 'create';
      canUrlNoId = name !== 'update' && name !== 'delete';
      url = null;
      if (canUrl && numIds === this.numParents) {
        url = this.url;
      }
      if (canUrlNoId && numIds === this.numParents - 1) {
        url = this.urlNoId;
      }
      if (url === null) {
        if (canUrlNoId) {
          msg = this.numParents - 1;
        }
        if (canUrl) {
          msg = (msg ? msg + ' or ' : '') + this.numParents;
        }
        error("Invalid number of ID arguments, required " + msg + ", provided " + numIds);
      }
      for (i = _j = 0, _len1 = ids.length; _j < _len1; i = ++_j) {
        id = ids[i];
        url = url.replace(new RegExp("\/:ID_" + (i + 1) + "\/"), "/" + id + "/");
      }
      return {
        url: url,
        data: data
      };
    };

    Resource.prototype.ajax = function(method, url, data, headers) {
      var ajaxOpts, encoded, key, req, useCache,
        _this = this;

      if (headers == null) {
        headers = {};
      }
      if (!method) {
        error("method missing");
      }
      if (!url) {
        error("url missing");
      }
      if (this.opts.username && this.opts.password) {
        encoded = encode64(this.opts.username + ":" + this.opts.password);
        headers.Authorization = "Basic " + encoded;
      }
      if (data && this.opts.stringifyData) {
        data = stringify(data);
      }
      if (this.opts.stripTrailingSlash) {
        url = url.replace(/\/$/, "");
      }
      ajaxOpts = {
        url: url,
        type: method,
        headers: headers
      };
      if (data) {
        ajaxOpts.data = data;
      }
      ajaxOpts = $.extend(true, {}, this.opts.ajax, ajaxOpts);
      useCache = this.opts.cache && $.inArray(method, this.opts.cachableMethods) >= 0;
      if (useCache) {
        key = this.root.cache.key(ajaxOpts);
        req = this.root.cache.get(key);
        if (req) {
          return req;
        }
      }
      req = $.ajax(ajaxOpts);
      if (useCache) {
        req.done(function() {
          return _this.root.cache.put(key, req);
        });
      }
      return req;
    };

    return Resource;

  })();

  Resource.defaults = defaultOpts;

  $.RestClient = Resource;

}).call(this);


text:
<idea-plugin>

  <id>org.intellij.sdk.pycharm</id>

  <name>SDK: PyCharm Sample</name>

  <depends>com.intellij.modules.python</depends>

  <description>
    <![CDATA[
      Demonstrates how to configure a plugin project for a PyCharm plugin.
    ]]>
  </description>
  <change-notes>
    <![CDATA[
      0.1.0 First release v2019.1 IntelliJ Platform / PyCharm

    ]]>
  </change-notes>

  <vendor url="https://plugins.jetbrains.com">IntelliJ Platform SDK</vendor>

  <actions>

    <group id="org.intellij.sdk.pycharm.NewGroupedActions" text="SDK: Plugin" popup="true">
      <add-to-group group-id="MainMenu" anchor="last"/>

      <action id="org.intellij.sdk.pycharm.PopupDialogAction" class="org.intellij.sdk.pycharm.PopupDialogAction"
              text="Pop a Dialog" description="SDK PyCharm basics example" icon="SdkIcons.Sdk_default_icon">
      </action>
    </group>
  </actions>

</idea-plugin>


text:
title: API
---

`markdown:docs/api/graphLayout/guide.zh.md`


text:
//判断是否是array
/**
 * Usage
 *  var isArray = require('./isarray');
 *  console.log(isArray([])); // => true
 *  console.log(isArray({})); // => false
 */

let toString = {}.toString;

module.exports = Array.isArray || function(arr) {
  return toString.call(arr) == '[object Array]';
};


text:
module Nanoc::CLI::StreamCleaners
  # Removes ANSI color escape sequences.
  #
  # @api private
  class ANSIColors < Abstract
    # @see Nanoc::CLI::StreamCleaners::Abstract#clean
    def clean(s)
      s.is_a?(String) ? s.gsub(/\e\[.+?m/, '') : s
    end
  end
end


text:
<?php

namespace Ekyna\Bundle\UserBundle\Extension\Admin;

/**
 * Class ShowTab
 * @package Ekyna\Bundle\UserBundle\Extension\Admin
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class ShowTab implements ShowTabInterface
{
    /**
     * @var string
     */
    private $label;

    /**
     * @var array
     */
    private $data;

    /**
     * @var string
     */
    private $template;

    /**
     * @var integer
     */
    private $position;

    /**
     * Constructor.
     *
     * @param string  $label
     * @param array   $data
     * @param string  $template
     * @param integer $position
     */
    public function __construct($label, array $data, $template, $position = 0)
    {
        $this->label    = $label;
        $this->data     = $data;
        $this->template = $template;
        $this->position = $position;
    }

    /**
     * {@inheritdoc}
     */
    public function getLabel()
    {
        return $this->label;
    }

    /**
     * {@inheritdoc}
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * {@inheritdoc}
     */
    public function getTemplate()
    {
        return $this->template;
    }

    /**
     * {@inheritdoc}
     */
    public function getPosition()
    {
        return $this->position;
    }
}


text:
var models;
(function (models) {
    /// <reference path="../entities/betting.ts"/>
    (function (simulations) {
        var SimulationState;
        (function (SimulationState) {
            SimulationState[SimulationState["NewGame"] = 0] = "NewGame";
            SimulationState[SimulationState["ChooseHand"] = 1] = "ChooseHand";
            SimulationState[SimulationState["ChooseBets"] = 2] = "ChooseBets";
            SimulationState[SimulationState["ShowResult"] = 3] = "ShowResult";
            SimulationState[SimulationState["GameOver"] = 4] = "GameOver";
        })(SimulationState || (SimulationState = {}));

        var PlayerResult = (function () {
            function PlayerResult(player, score) {
                this.player = player;
                this.score = score;
            }
            return PlayerResult;
        })();
        simulations.PlayerResult = PlayerResult;

        var gameTypes = [
            [1, 2, 2, 2],
            [1, 2, 2, 2],
            [2, 1, 2, 2],
            [2, 1, 2, 2],
            [2, 2, 1, 2],
            [2, 2, 1, 2],
            [2, 2, 2, 1],
            [2, 2, 2, 1],
            [1, 3, 2, 2],
            [1, 3, 1, 1]
        ];

        var Simulation = (function () {
            function Simulation() {
                this.changingPlayer = new Signal();
                this.canCommitHat = new Signal();
                this.chooseBets = new Signal();
                this.turnReady = new Signal();
                this.turnResult = new Signal();
                this.gameOver = new Signal();
                this.gameType = gameTypes[Math.floor(Math.random() * gameTypes.length)];

                this.hat = new models.entities.Hat();
                this.players = [];
                this.players[0] = new models.entities.Player(0, this.gameType);
                this.players[1] = new models.entities.Player(1, this.gameType);

                this.currentPlayer = 0;
                this.simulationState = SimulationState.NewGame;
            }
            Simulation.prototype.StartGame = function () {
                this.simulationState = SimulationState.ChooseHand;
                this.changingPlayer.dispatch(this.players[this.currentPlayer]);
            };

            Simulation.prototype.AdvanceGame = function () {
                var nextRound = false;

                if (this.hat.IsDone() || this.HasPlayerWon()) {
                    this.simulationState = SimulationState.GameOver;
                    var results = this.GetGameResults();
                    this.gameOver.dispatch(results);
                } else {
                    for (var iPlayer in this.players) {
                        var player = this.players[iPlayer];
                        player.currentBet = null;
                    }
                    this.simulationState = SimulationState.ChooseBets;
                    this.chooseBets.dispatch(this.players);
                    nextRound = true;
                }

                return nextRound;
            };

            Simulation.prototype.GetGameResults = function () {
                var winningScore = Number.MIN_VALUE;
                var winningPlayer = null;
                for (var iPlayer in this.players) {
                    var player = this.players[iPlayer];
                    if (player.points > winningScore) {
                        winningPlayer = player;
                        winningScore = player.points;
                    } else if (player.points === winningScore) {
                        // A tie
                        winningPlayer = null;
                    }
                }

                return new PlayerResult(winningPlayer, winningScore);
            };

            Simulation.prototype.AreAllPlayersReady = function () {
                var allPlayersReady = true;
                for (var iPlayer in this.players) {
                    var player = this.players[iPlayer];
                    if (player.currentBet === null) {
                        allPlayersReady = false;
                        break;
                    }
                }
                return allPlayersReady;
            };

            Simulation.prototype.MakeBet = function (playerId, betType) {
                var player = this.players[playerId];
                var previousBet = player.currentBet;

                player.MakeBet(betType);

                if ((null === previousBet) && this.AreAllPlayersReady()) {
                    this.turnReady.dispatch();
                }

                return previousBet;
            };

            Simulation.prototype.TakeTurn = function () {
                var bet = this.hat.GetNextBet();
                var winningPlayer = null;
                for (var iPlayer in this.players) {
                    var player = this.players[iPlayer];
                    if (player.currentBet === bet) {
                        if (null !== winningPlayer) {
                            // A tie
                            winningPlayer = null;
                            break;
                        }
                        winningPlayer = player;
                    }
                }
                if (winningPlayer) {
                    winningPlayer.AddPoint(1);
                }
                this.simulationState = SimulationState.ShowResult;
                this.turnResult.dispatch(winningPlayer, bet, this.players);
            };

            Simulation.prototype.AddBetToHat = function (betType) {
                var hand = this.players[this.currentPlayer].GetHand();
                var beforeCount = hand.GetBetCount();
                hand.AddBetToHat(betType);
                var afterCount = hand.GetBetCount();
                if (((beforeCount === 5) || (afterCount === 5)) && (beforeCount !== afterCount)) {
                    this.canCommitHat.dispatch(afterCount === 5);
                }
            };

            Simulation.prototype.RemoveBetFromHat = function (betType) {
                var hand = this.players[this.currentPlayer].GetHand();
                var beforeCount = hand.GetBetCount();
                hand.RemoveBetFromHat(betType);
                var afterCount = hand.GetBetCount();
                if (((beforeCount === 5) || (afterCount === 5)) && (beforeCount !== afterCount)) {
                    this.canCommitHat.dispatch(afterCount === 5);
                }
            };

            Simulation.prototype.CommitHat = function () {
                var newBets = this.players[this.currentPlayer].GetHand().GetBets();
                for (var iBet in newBets) {
                    var newBet = newBets[iBet];
                    this.hat.AddBet(newBet);
                }
                this.currentPlayer = (this.currentPlayer + 1) % this.players.length;
                if (0 == this.currentPlayer) {
                    this.simulationState = SimulationState.ChooseBets;
                    this.hat.ShuffleBets();
                    this.chooseBets.dispatch(this.players);
                } else {
                    this.simulationState = SimulationState.ChooseHand;
                    this.changingPlayer.dispatch(this.players[this.currentPlayer]);
                }
            };

            Simulation.prototype.GetChoosingPlayer = function () {
                if (this.simulationState === SimulationState.ChooseHand) {
                    return this.players[this.currentPlayer];
                }

                return null;
            };

            Simulation.prototype.GetAvailableBets = function () {
                return this.players[this.currentPlayer].GetHand().GetAvailableBets();
            };

            Simulation.prototype.GetCurrentPlayers = function () {
                var ret = new Array();
                var totalScore = 0;
                for (var i = 0, col = this.players, c = col.length; i < c; ++i) {
                    var player = col[i];
                    totalScore += player.points;
                }

                for (var i = 0, col = this.players, c = col.length; i < c; ++i) {
                    var player = col[i];
                    ret.push(new PlayerResult(player, totalScore - player.points));
                }

                return ret;
            };

            Simulation.prototype.HasPlayerWon = function () {
                var ret = false;
                for (var i = 0, col = this.players, c = col.length; i < c; ++i) {
                    var player = col[i];
                    if (player.points >= 3) {
                        ret = true;
                        break;
                    }
                }

                return ret;
            };
            return Simulation;
        })();
        simulations.Simulation = Simulation;
    })(models.simulations || (models.simulations = {}));
    var simulations = models.simulations;
})(models || (models = {}));
//# sourceMappingURL=simulation.js.map


text:
<?php

/**
 * Public interface of ownCloud for apps to use.
 * User Interface version 2
 *
 */

// use OCP namespace for all classes that are considered public.
// This means that they should be used by apps instead of the internal ownCloud classes
namespace OCP;

/**
 * Interface IUserBackend
 *
 * @package OCP
 * @since 8.0.0
 */
interface IUserBackend {

	/**
	 * Backend name to be shown in user management
	 * @return string the name of the backend to be shown
	 * @since 8.0.0
	 */
	public function getBackendName();
}