text:
r360.photonPlaceAutoCompleteControl = function (options) {
    return new r360.PhotonPlaceAutoCompleteControl(options);
};

r360.PhotonPlaceAutoCompleteControl = L.Control.extend({

    initialize: function(options){

        this.options = JSON.parse(JSON.stringify(r360.config.photonPlaceAutoCompleteOptions));

        if ( typeof options !== "undefined" ) {

            if ( _.has(options, 'position'))    this.options.position    = options.position;
            if ( _.has(options, 'label'))       this.options.label       = options.label;
            if ( _.has(options, 'country'))     this.options.country     = options.country;
            if ( _.has(options, 'reset'))       this.options.reset       = options.reset;
            if ( _.has(options, 'serviceUrl'))  this.options.serviceUrl       = options.serviceUrl;
            if ( _.has(options, 'reverse'))     this.options.reverse     = options.reverse;
            if ( _.has(options, 'placeholder')) this.options.placeholder = options.placeholder;
            if ( _.has(options, 'width'))       this.options.width       = options.width;
            if ( _.has(options, 'maxRows'))     this.options.maxRows     = options.maxRows;
            if ( _.has(options, 'image'))       this.options.image       = options.image;
            if ( _.has(options, 'index'))       this.options.index       = options.index;
            if ( _.has(options, 'options')) {

                 this.options.options    = options.options;
                 this.options.travelType = _.has(this.options.options, 'init') ? this.options.options.init : 'walk';
            }
        }
    },

    onAdd: function(map){

        var that = this;
        var i18n            = r360.config.i18n;
        var countrySelector =  "";
        var nameContainer   = L.DomUtil.create('div', that._container);
        that.options.map    = map;
        that.options.id     = $(map._container).attr("id") + r360.Util.generateId(10);

        map.on("resize", that.onResize.bind(that));

        // calculate the width in dependency to the number of buttons attached to the field
        var width = that.options.width;
        // if ( that.options.reset ) width += 44;
        // if ( that.options.reverse ) width += 37;
        var style = 'style="width:'+ width +'px;"';

        that.options.input =
            '
 \
                <input id="autocomplete-'+that.options.id+'" style="color: black;width:'+width+'" \
                type="text" class="form-control r360-autocomplete" placeholder="' + that.options.placeholder + '" onclick="this.select()">';

        if ( that.options.image ) {

            that.options.input +=
                ' \
                     \
                 ';
        }

        var optionsHtml = [];
        // if ( that.options.options ) {

            that.options.input +=
                ' \
                    <button class="btn btn-autocomplete" type="button" title="' + i18n.get('settings') + '"></button> \
                ';

            optionsHtml.push('
');
            optionsHtml.push('
');

            if ( that.options.options && that.options.options.walk )
                optionsHtml.push('<button type="button" class="btn btn-default travel-type-button '
                    + (this.options.travelType == 'walk' ? 'active' : '') +
                    '" travel-type="walk"> Walkzu Fuß</button>');

            if ( that.options.options && that.options.options.bike )
                optionsHtml.push('<button type="button" class="btn btn-default travel-type-button '
                    + (this.options.travelType == 'bike' ? 'active' : '') +
                    '" travel-type="bike"> BikeFahrrad</button>');

            if ( that.options.options && that.options.options.hirebike )
                optionsHtml.push('<button type="button" class="btn btn-default travel-type-button '
                    + (this.options.travelType == 'hirebike' ? 'active' : '') +
                    '" travel-type="hirebike"> \
                             Hire BikeLeihfahrrad\
                        </button>');

            if ( that.options.options && that.options.options.transit )
                optionsHtml.push('<button type="button" class="btn btn-default travel-type-button '
                    + (this.options.travelType == 'transit' ? 'active' : '') +
                    '" travel-type="transit"> TransitÖPNV</button>');

            if ( that.options.options && that.options.options.car )
                optionsHtml.push('<button type="button" class="btn btn-default travel-type-button '
                    + (this.options.travelType == 'car' ? 'active' : '') +
                    '" travel-type="car"> CarAuto</button>');

            optionsHtml.push('
');
            optionsHtml.push('
');
        // }

        // add a reset button to the input field
        // if ( that.options.reset ) {

             that.options.input +=
                ' \
                    <button class="btn btn-autocomplete" type="button" title="' + i18n.get('reverse') + '"></button> \
                ';

            that.options.input +=
                ' \
                    <button class="btn btn-autocomplete" type="button" title="' + i18n.get('reset') + '"></button> \
                ';
        // }
        // if ( that.options.reverse ) {

        // }

        that.options.input += '
';
        if ( that.options.options ) that.options.input += optionsHtml.join('');

        // add the control to the map
        $(nameContainer).append(that.options.input);

        $(nameContainer).find('#' + that.options.id + '-reset').click(function(){ that.options.onReset(); });
        $(nameContainer).find('#' + that.options.id + '-reverse').click(function(){ that.options.onReverse(); });
        $(nameContainer).find('#' + that.options.id + '-options-button').click(
            function(){
                // slide in or out on the click of the options button
                $('#' + that.options.id + '-options').slideToggle();
            });

        $(nameContainer).find('.travel-type-button').click(function(){

            $(nameContainer).find('.travel-type-button').removeClass('active');
            $(this).addClass('active');

            setTimeout(function() {
                  $('#' + that.options.id + '-options').slideToggle();
            }, 300);

            that.options.travelType = $(this).attr('travel-type');
            that.options.onTravelTypeChange();
        });

        // no click on the map, if click on container
        L.DomEvent.disableClickPropagation(nameContainer);

        if ( _.has(that.options, 'country' ) ) countrySelector += " AND country:" + that.options.country;

        $(nameContainer).find("#autocomplete-" + that.options.id).autocomplete({

            source: function( request, response ) {

                that.source = this;

                var requestElements = request.term.split(" ");
                var numbers = new Array();
                var requestString = request.term;
                var numberString = "";

                // for(var i = 0; i < requestElements.length; i++){

                //     if(requestElements[i].search(".*[0-9].*") != -1)
                //         numbers.push(requestElements[i]);
                //     else
                //         requestString += requestElements[i] + " ";
                // }

                // if ( numbers.length > 0 ) {
                //     numberString += " OR ";

                //     for(var j = 0; j < numbers.length; j++){
                //         var n = "(postcode : " + numbers[j] + " OR housenumber : " + numbers[j] + " OR street : " + numbers[j] + ") ";
                //         numberString +=  n;
                //     }
                // }

                $.ajax({
                    url: that.options.serviceUrl,
                    // dataType: "jsonp",
                    // jsonp: 'json.wrf',
                    async: false,
                    data: {
                      // wt:'json',
                      // indent : true,
                      // rows: that.options.maxRows,
                      // qt: 'en',
                      // q:  "(" + requestString + numberString + ")" + countrySelector
                      q : requestString,
                      limit : that.options.maxRows
                      // lat : that.options.map.getCenter().lat,
                      // lon : that.options.map.getCenter().lng
                    },
                    success: function( data ) {

                        var places = new Array();
                        response( $.map( data.features, function( feature ) {

                            if ( feature.osm_key == "boundary" ) return;

                            var place           = {};
                            var firstRow        = [];
                            var secondRow       = [];
                            place.name          = feature.properties.name;
                            place.city          = feature.properties.city;
                            place.street        = feature.properties.street;
                            place.housenumber   = feature.properties.housenumber;
                            place.country       = feature.properties.country;
                            place.postalCode    = feature.properties.postcode;
                            if (place.name)       firstRow.push(place.name);
                            if (place.city)       firstRow.push(place.city);
                            if (place.street)     secondRow.push(place.street);
                            if (place.housenumber) secondRow.push(place.housenumber);
                            if (place.postalCode) secondRow.push(place.postalCode);
                            if (place.city)       secondRow.push(place.city);

                            // only show country if undefined
                            // if ( !_.has(that.options, 'country') && place.country )
                                secondRow.push(place.country);

                            // if same looking object is in list already: return
                            if ( _.contains(places, firstRow.join() + secondRow.join()) ) return;
                            else places.push(firstRow.join() + secondRow.join());

                            return {
                                label       : firstRow.join(", "),
                                value       : firstRow.join(", "),
                                firstRow    : firstRow.join(", "),
                                secondRow   : secondRow.join(" "),
                                term        : request.term,
                                index       : that.options.index,
                                latlng      : new L.LatLng(feature.geometry.coordinates[1], feature.geometry.coordinates[0])
                            }
                        }));
                    }
                });
            },
            minLength: 2,

            select: function( event, ui ) {
                that.options.value = ui.item;
                that.options.onSelect(ui.item);
            }
        })
        .data("ui-autocomplete")._renderItem = function( ul, item ) {

            // this has been copied from here: https://github.com/angular-ui/bootstrap/blob/master/src/typeahead/typeahead.js
            // thank you angular bootstrap team
            function escapeRegexp(queryToEscape) {
                return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
            }

            var highlightedFirstRow =
                item.term ? (item.firstRow).replace(new RegExp(escapeRegexp(item.term), 'gi'), '$&') : item.firstRow;

            var highlightedSecondRow =
                item.term ? (item.secondRow).replace(new RegExp(escapeRegexp(item.term), 'gi'), '$&') : item.secondRow;

            var html = ""+ highlightedFirstRow + "
  " + highlightedSecondRow + "";

            return $( "
" ).append(html).appendTo(ul);
        };

        this.onResize();

        return nameContainer;
    },

    onSelect: function(onSelect){

        this.options.onSelect = onSelect;
    },

    onReset: function(onReset){

        this.options.onReset = onReset;
    },

    onReverse: function(onReverse){

       this.options.onReverse = onReverse;
    },

    onTravelTypeChange: function(onTravelTypeChange){

        this.options.onTravelTypeChange = onTravelTypeChange;
    },

    reset : function(){

        this.options.value = {};
        this.setFieldValue("");
    },

    update : function(latLng, fieldValue) {

        this.setLatLng(latLng);
        this.setFieldValue(fieldValue);
    },

    setLatLng : function(latLng) {

        this.options.value.latlng = latLng
    },

    setFieldValue : function(value){

        var that = this;
        $("#autocomplete-" + that.options.id).val(value);
    },

    getFieldValue : function(){

        var that = this;
        return $("#autocomplete-" + that.options.id).val();
    },

    getTravelType : function(){

        return this.options.travelType;
    },

    setValue : function(value){
        this.options.value = value;
    },

    getValue : function(){
        return this.options.value;
    },

    getIndex : function(){
        return this.options.index;
    },

    onResize: function(){

        var that = this;
        if ( this.options.map.getSize().x < 550) $(that.options.input).css({'width':'45px'});
        else $(that.options.input).css({'width':''});
    }
})


text:
<?php

namespace mushroom\component\cache;

class Cache {

	private $cache = null;

	private $config = array();

	private function getCacheObject() {
		switch($this->config['driver']) {
			case 'File':
				$this->cache = new File($this->config);
				break;
			case 'Mysql':
				$this->cache = new Mysql($this->config);
				break;
			case 'Redis':
				$this->cache = new Redis($this->config);
				break;
			case 'Memcache':
				$this->cache = new Memcache($this->config);
				break;
		}
	}

	public function __construct($config) {
		$this->config = $config;
		$this->getCacheObject();
	}

	public function set($key, $value, $expire = 3600) {
		return $this->cache->set($key, $value, $expire);
	}

	public function get($key) {
		return $this->cache->get($key);
	}

	public function delete($key) {
		return $this->cache->delete($key);
	}
}

redpajama_set_name: RedPajamaGithub


text:
set -o errexit
set -o pipefail
set -o nounset

celery -A awesome_app.taskapp worker -l INFO


text:
using System;
using Plugin.DeviceInfo;

namespace CoCore.Base
{
	public static class Device
	{
		public static T OnPlatform<T>(Func<T> iosFunc, Func<T> androidFunc,Func<T> windowsFunc){
			switch (CrossDeviceInfo.Current.Platform) {
			case Plugin.DeviceInfo.Abstractions.Platform.Android:
				return androidFunc();
			case Plugin.DeviceInfo.Abstractions.Platform.iOS:
				return iosFunc();
			case Plugin.DeviceInfo.Abstractions.Platform.Windows:
				return windowsFunc();
			default:
				return default(T);
			}
		}
	}
}


text:
package epic.models

import epic.trees.AnnotatedLabel
import epic.parser.Parser
import scala.reflect.ClassTag

/**
 * TODO
 *
 * @author dlwh
 **/
object ParserSelector extends ModelSelector[Parser[AnnotatedLabel, String], ParserModelLoader] {
  override protected def manifest: ClassTag[ParserModelLoader] = scala.reflect.classTag[ParserModelLoader]

  def loadParser(language: String = "en"): Option[Parser[AnnotatedLabel, String]] = this.findModel(s"language:$language").map(_.load())
}

trait ParserModelLoader extends ModelLoader[Parser[AnnotatedLabel,String]];


text:
#ifndef SMT_KERNEL_H_
#define SMT_KERNEL_H_

#include"ast.h"
#include"params.h"
#include"model.h"
#include"lbool.h"
#include"statistics.h"
#include"smt_failure.h"

struct smt_params;
class progress_callback;

namespace smt {

    class enode;
    class context;

    class kernel {
        struct imp;
        imp *  m_imp;
    public:
        kernel(ast_manager & m, smt_params & fp, params_ref const & p = params_ref());

        ~kernel();

        static void copy(kernel& src, kernel& dst);

        ast_manager & m() const;

        /**
           \brief Set logic. It must be invoked before any assertions.
           Return true if succeeded.
        */
        bool set_logic(symbol logic);

        /**
           brief Set progress meter. Kernel will invoke the callback from time to time.
        */
        void set_progress_callback(progress_callback * callback);

        /**
           \brief Assert the given assetion into the logical context.
           This method uses the "asserted" proof as a justification for e.
        */
        void assert_expr(expr * e);

        /**
           \brief Assert the given assertion with the given proof as a justification.
        */
        void assert_expr(expr * e, proof * pr);

        /**
           \brief Return the number of asserted formulas in the kernel.
        */
        unsigned size() const;

        /**
           \brief Return the array of asserted formulas.
        */
        expr * const * get_formulas() const;

        /**
           \brief Create a backtracking point (aka scope level).
        */
        void push();

        /**
           \brief Backtrack the given number of scope levels.
        */
        void pop(unsigned num_scopes);

        /**
           \brief Return the number of backtracking points.
        */
        unsigned get_scope_level() const;

        /**
           \brief Reset the kernel.
           All assertions are erased.
        */
        void reset();

        /**
           \brief Return true if the set of asserted formulas is known to be inconsistent.
        */
        bool inconsistent();

        /**
           \brief Setup the logical context and invoke check.
        */
        lbool setup_and_check();

        /**
           \brief Satisfiability check.
        */
        lbool check(unsigned num_assumptions = 0, expr * const * assumptions = 0);

        lbool check(expr_ref_vector const& asms) { return check(asms.size(), asms.c_ptr()); }

        lbool check(app_ref_vector const& asms) { return check(asms.size(), (expr* const*)asms.c_ptr()); }

        /**
           \brief Return the model associated with the last check command.
        */
        void get_model(model_ref & m) const;

        /**
           \brief Return the proof of unsatisfiability associated with the last check command.
        */
        proof * get_proof();

        /**
           \brief Return the size of the unsat core associated with the last check command.
        */
        unsigned get_unsat_core_size() const;

        /**
           \brief Return the i-th expression in the unsat core associated with the last check command.

           \pre i < get_unsat_core_size()
        */
        expr * get_unsat_core_expr(unsigned i) const;

        /**
           \brief Return the reason for failure for the last check command.
           Failure means, it returned l_undef
        */
        failure last_failure() const;

        /**
           \brief Return a string describing the failure.
        */
        std::string last_failure_as_string() const;

        /**
           \brief Set the reason for unknown.
        */
        void set_reason_unknown(char const* msg);

        /**
           \brief Return the set of formulas assigned by the kernel.
        */
        void get_assignments(expr_ref_vector & result);

        /**
           \brief Return the set of relevant labels in the last check command.
        */
        void get_relevant_labels(expr * cnstr, buffer<symbol> & result);

        /**
           \brief Return the relevant labeled_literals in the last check command.
        */
        void get_relevant_labeled_literals(bool at_lbls, expr_ref_vector & result);

        /**
           \brief Return the relevant literals in the last check command.
        */
        void get_relevant_literals(expr_ref_vector & result);

        /**
           \brief Return the set of guessed literals (decisions) performed in the last check command.
        */
        void get_guessed_literals(expr_ref_vector & result);

        /**
           \brief (For debubbing purposes) Prints the state of the kernel
        */
        void display(std::ostream & out) const;

        /**
           \brief Collect runtime statistics.
         */
        void collect_statistics(::statistics & st) const;

        /**
           \brief Reset kernel statistics.
        */
        void reset_statistics();

        /**
           \brief Display statistics.
        */
        void display_statistics(std::ostream & out) const;

        /**
           \brief Display statistics in low level format.
        */
        void display_istatistics(std::ostream & out) const;

        /**
           \brief Return true if the kernel was interrupted.
        */
        bool canceled() const;

        /**
           \brief Update configuration parameters.
        */
        void updt_params(params_ref const & p);

        /**
           \brief Collect a description of the configuration parameters.
        */
        static void collect_param_descrs(param_descrs & d);

        /**
           \brief Return a reference to smt::context.
           This is a temporary hack to support user theories.
           TODO: remove this hack.
           We need to revamp user theories too.

           This method breaks the abstraction barrier.

           \warning We should not use this method
        */
        context & get_context();
    };
};

#endif


text:
import React, { Component, PropTypes } from 'react';
import { pushState } from 'redux-router';
import { connect } from 'react-redux';
import { fetchItemThreadsIfNeeded } from '../actions';
import { MAX_THREAD_NUMBER, BASE_API_URL } from '../constants';
// import components
import ItemThread from '../components/ItemThread';
import NewsHeader from '../components/NewsHeader';
import CommentThread from '../components/CommentThread';

import '../public/stylesheets/list.css';

class ItemThreadList extends Component {

    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.props.dispatch(fetchItemThreadsIfNeeded());
    }

    getMore(selectedPath,page) {
        return (

                <a className="newsList-moreLink" href={`/${selectedPath}?p=${parseInt(page)+1}`}>More

        );
    }

    getFooter() {
        return (

        );
    }

    getSpinning() {
        return (

                Loading ...

        )
    }

    render() {
        const { ids, selectedPath, page, isLoading } = this.props;
        let iThread = [],
            rank = 1 + MAX_THREAD_NUMBER * (page - 1),
            isComment = selectedPath === 'newcomments';

        for (let [ key, value ] of ids) {
            iThread = [...iThread, (
                isComment ?
                    <CommentThread key={key} context={value} />
                          :
                    <ItemThread key={rank} selectedPath={selectedPath} rank={rank++} threadId={key} context={value} />
            )];
        }

        return (

                <NewsHeader selectedPath={selectedPath} />
                { isLoading && this.getSpinning() }

                    {iThread}

                { ids.size > 0 && this.getMore(selectedPath, page) }
                { ids.size > 0 && this.getFooter() }

        );
    }
}

ItemThreadList.propTypes = {
    dispatch: PropTypes.func.isRequired
};

export default connect(state => ({
    ids: state.thread.ids || new Map(),
    isLoading: state.thread.isLoading === true,
    selectedPath: state.router.location.pathname.replace('/',''),
    page: parseInt(state.router.location.query.p) || 1
}))(ItemThreadList);


text:
namespace prefs {

// NOTE: This file does not contain all content settings related pref names as
// some of these are generated by WebsiteSettingsInfo from content settings
// names.

extern const char kCookieControlsMode[];

extern const char kContentSettingsVersion[];
extern const char kContentSettingsWindowLastTabIndex[];

extern const char kManagedDefaultAdsSetting[];
extern const char kManagedDefaultCookiesSetting[];
extern const char kManagedDefaultImagesSetting[];
extern const char kManagedDefaultInsecureContentSetting[];
extern const char kManagedDefaultJavaScriptSetting[];
extern const char kManagedDefaultPopupsSetting[];
extern const char kManagedDefaultGeolocationSetting[];
extern const char kManagedDefaultNotificationsSetting[];
extern const char kManagedDefaultMediaStreamSetting[];
extern const char kManagedDefaultSensorsSetting[];
extern const char kManagedDefaultWebBluetoothGuardSetting[];
extern const char kManagedDefaultWebUsbGuardSetting[];
extern const char kManagedDefaultFileHandlingGuardSetting[];
extern const char kManagedDefaultFileSystemReadGuardSetting[];
extern const char kManagedDefaultFileSystemWriteGuardSetting[];
extern const char kManagedDefaultSerialGuardSetting[];
extern const char kManagedDefaultInsecurePrivateNetworkSetting[];
extern const char kManagedDefaultJavaScriptJitSetting[];
extern const char kManagedDefaultWebHidGuardSetting[];
extern const char kManagedDefaultWindowPlacementSetting[];

extern const char kManagedCookiesAllowedForUrls[];
extern const char kManagedCookiesBlockedForUrls[];
extern const char kManagedCookiesSessionOnlyForUrls[];
extern const char kManagedImagesAllowedForUrls[];
extern const char kManagedImagesBlockedForUrls[];
extern const char kManagedInsecureContentAllowedForUrls[];
extern const char kManagedInsecureContentBlockedForUrls[];
extern const char kManagedJavaScriptAllowedForUrls[];
extern const char kManagedJavaScriptBlockedForUrls[];
extern const char kManagedPopupsAllowedForUrls[];
extern const char kManagedPopupsBlockedForUrls[];
extern const char kManagedNotificationsAllowedForUrls[];
extern const char kManagedNotificationsBlockedForUrls[];
extern const char kManagedSensorsAllowedForUrls[];
extern const char kManagedSensorsBlockedForUrls[];
extern const char kManagedAutoSelectCertificateForUrls[];
extern const char kManagedWebUsbAllowDevicesForUrls[];
extern const char kManagedWebUsbAskForUrls[];
extern const char kManagedWebUsbBlockedForUrls[];
extern const char kManagedFileHandlingAllowedForUrls[];
extern const char kManagedFileHandlingBlockedForUrls[];
extern const char kManagedFileSystemReadAskForUrls[];
extern const char kManagedFileSystemReadBlockedForUrls[];
extern const char kManagedFileSystemWriteAskForUrls[];
extern const char kManagedFileSystemWriteBlockedForUrls[];
extern const char kManagedLegacyCookieAccessAllowedForDomains[];
extern const char kManagedSerialAskForUrls[];
extern const char kManagedSerialBlockedForUrls[];
extern const char kManagedInsecurePrivateNetworkAllowedForUrls[];
extern const char kManagedJavaScriptJitAllowedForSites[];
extern const char kManagedJavaScriptJitBlockedForSites[];
extern const char kManagedWebHidAskForUrls[];
extern const char kManagedWebHidBlockedForUrls[];
extern const char kManagedWindowPlacementAllowedForUrls[];
extern const char kManagedWindowPlacementBlockedForUrls[];

extern const char kEnableQuietNotificationPermissionUi[];
extern const char kQuietNotificationPermissionUiEnablingMethod[];
extern const char kQuietNotificationPermissionUiDisabledTime[];

#if BUILDFLAG(IS_ANDROID)
extern const char kNotificationsVibrateEnabled[];
#endif

}  // namespace prefs

#endif  // COMPONENTS_CONTENT_SETTINGS_CORE_COMMON_PREF_NAMES_H_


text:
from setuptools import setup, find_packages
from gaas import __version__

tests_require = [
    'nose',
    'mock',
    'coverage',
    'rednose',
    'preggy',
    'tox',
    'ipdb',
    'coveralls',
    'sphinx',
    'factory_boy',
    'alembic',
    'nose_focus',
    'mysql-python',
]

setup(
    name='gaas',
    version=__version__,
    description="gaas is an acronym for Git as a service.",
    long_description="""gaas is an acronym for Git as a service.""",
    keywords='git repository management web saas',
    author='Bernardo Heynemann',
    author_email='heynemann@gmail.com',
    url='https://github.com/heynemann/gaas',
    license='MIT',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Operating System :: MacOS',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4',
    ],
    packages=find_packages(),
    include_package_data=True,

    install_requires=[
        'pymongo==2.7',
        'pycurl',
        'cow-framework',
        'motorengine',
        'pygit2',
        'gittornado',
        'python-slugify'
    ],

    extras_require={
        'tests': tests_require,
    },

    entry_points={
        'console_scripts': [
            'gaas=gaas.server:main',
        ],
    }
)


text:
bool did_all_hw(const Student_info& s);
double average_analysis(const std::vector<Student_info>& students);
double median_analysis(const std::vector<Student_info>& students);
double optimistic_median_analysis(const std::vector<Student_info>& students);
void write_analysis(std::ostream& out, const std::string& name,
                    double analysis(const std::vector<Student_info>&),
                    const std::vector<Student_info>& did,
                    const std::vector<Student_info>& didnt);

#endif


text:
<meta>
    <info name="Welcome Messages" type="script" />
    <script src="welcomemessages.cs" />
</meta>


text:
<?php

namespace Task\Application\Service\DataSourceService;

class JsonDataSourceService implements DataSourceServiceInterface
{
    /**
     * @var string
     */
    protected $sPath;

    /**
     * @var integer
     */
    protected $iMaxDepth;

    /**
     * @param string $sPath
     * @param integer $iMaxDepth
     */
    public function __construct($sPath, $iMaxDepth = 512)
    {
        $this->sPath = $this->ensureTrailingSlash($sPath);
        $this->iMaxDepth = $iMaxDepth;
    }

    /**
     * @param integer $iDataId
     * @return array|null
     */
    public function collectDataById($iDataId)
    {
        $sFile = sprintf('%s%d.json', $this->sPath, $iDataId);

        if (!file_exists($sFile)) {
            return null;
        }

        $sData = file_get_contents($sFile);

        $oResult = json_decode($sData, true, $this->iMaxDepth);

        return $oResult
            ? $oResult
            : null;
    }

    private function ensureTrailingSlash($sPath)
    {
        $sPath = rtrim($sPath, DIRECTORY_SEPARATOR);

        return $sPath . '/';
    }
}


text:
<?php

namespace CB\FairBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class RuleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('description')
            ->add('numberOfTimes')
            ->add('numberOfBakedItems')
            ->add('numberOfAuctionItems')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'CB\FairBundle\Entity\Rule'
        ));
    }

    public function getName()
    {
        return 'cb_fairbundle_ruletype';
    }
}


text:
Gravity Placeholders
====================

A quick-and-dirty jQuery plugin that hides the labels of the selected
inputs and uses the contained text as a placeholder. Specifically designed
for Gravity Forms.

Using the Plugin
----------------

This plugin is designed for text-style inputs and textareas only. To target all
support Gravity Forms inputs, use the following:

    $('.gfield input[type=text],.gfield input[type=email],.gfield input[type=tel],.gfield input[type=url],.gfield textarea').gravityPlaceholders();

To target only standard text inputs:

    $('.gfield input[type=text]').gravityPlaceholders();

For more information on targeting specific inputs, refer to the
[Gravity Forms Documentation][1].

Changelog
---------

### 1.2.1

* Added better placeholders for complex inputs
* Verified support for Gravity Forms through v1.7.6.10

### 1.2.0

* Added native placeholder support with a `value` fallback for older browsers

### 1.1.0

* Complete overhaul of the plugin structure

### 1.0.0

* Initial release

Authors
-------

**Jason Lengstorf**

* http://twitter.com/jlengstorf
* http://github.com/jlengstorf

Copyright and license
---------------------

Copyright (c) 2012 Jason Lengstorf

Licensed under the MIT License (the "License"); you may not use this work
except in compliance with the License. You may obtain a copy of the License in
the license.txt file, or at:

http://opensource.org/licenses/mit-license.php

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.

[1]: http://www.gravityhelp.com/documentation/page/CSS_Targeting_Samples


text:
package plan

import (
	"bytes"
	"encoding/json"
	"fmt"

	"github.com/juju/errors"
	"github.com/pingcap/tidb/context"
	"github.com/pingcap/tidb/expression"
	"github.com/pingcap/tidb/util/codec"
	"github.com/pingcap/tidb/util/types"
)

const (
	// Sel is the type of Selection.
	Sel = "Selection"
	// St is the type of Set.
	St = "Set"
	// Proj is the type of Projection.
	Proj = "Projection"
	// Agg is the type of Aggregation.
	Agg = "Aggregation"
	// Jn is the type of Join.
	Jn = "Join"
	// Un is the type of Union.
	Un = "Union"
	// Tbl is the type of TableScan.
	Tbl = "TableScan"
	// Idx is the type of IndexScan.
	Idx = "IndexScan"
	// Srt is the type of Sort.
	Srt = "Sort"
	// Lim is the type of Limit.
	Lim = "Limit"
	// App is the type of Apply.
	App = "Apply"
	// MOR is the type of MaxOneRow.
	MOR = "MaxOneRow"
	// Ext is the type of Exists.
	Ext = "Exists"
	// Dual is the type of TableDual.
	Dual = "TableDual"
	// Lock is the type of SelectLock.
	Lock = "SelectLock"
	// Load is the type of LoadData.
	Load = "LoadData"
	// Ins is the type of Insert
	Ins = "Insert"
	// Up is the type of Update.
	Up = "Update"
	// Del is the type of Delete.
	Del = "Delete"
	// Aly is the type of Analyze.
	Aly = "Analyze"
)

// Plan is the description of an execution flow.
// It is created from ast.Node first, then optimized by the optimizer,
// finally used by the executor to create a Cursor which executes the statement.
type Plan interface {
	// AddParent means appending a parent for plan.
	AddParent(parent Plan)
	// AddChild means appending a child for plan.
	AddChild(children Plan)
	// ReplaceParent means replacing a parent with another one.
	ReplaceParent(parent, newPar Plan) error
	// ReplaceChild means replacing a child with another one.
	ReplaceChild(children, newChild Plan) error
	// Get all the parents.
	Parents() []Plan
	// Get all the children.
	Children() []Plan
	// Set the schema.
	SetSchema(schema *expression.Schema)
	// Get the schema.
	Schema() *expression.Schema
	// Get the ID.
	ID() string
	// SetParents sets the parents for the plan.
	SetParents(...Plan)
	// SetParents sets the children for the plan.
	SetChildren(...Plan)

	context() context.Context

	extractCorrelatedCols() []*expression.CorrelatedColumn
}

type columnProp struct {
	col  *expression.Column
	desc bool
}

func (c *columnProp) equal(nc *columnProp, ctx context.Context) bool {
	return c.col.Equal(nc.col, ctx) && c.desc == nc.desc
}

type requiredProperty struct {
	props      []*columnProp
	sortKeyLen int
	limit      *Limit
}

// getHashKey encodes a requiredProperty to a unique hash code.
func (p *requiredProperty) getHashKey() ([]byte, error) {
	datums := make([]types.Datum, 0, len(p.props)*3+1)
	datums = append(datums, types.NewDatum(p.sortKeyLen))
	for _, c := range p.props {
		datums = append(datums, types.NewDatum(c.desc), types.NewDatum(c.col.FromID), types.NewDatum(c.col.Index))
	}
	bytes, err := codec.EncodeValue(nil, datums...)
	return bytes, errors.Trace(err)
}

// String implements fmt.Stringer interface. Just for test.
func (p *requiredProperty) String() string {
	ret := "Prop{"
	for _, colProp := range p.props {
		ret += fmt.Sprintf("col: %s, desc %v, ", colProp.col, colProp.desc)
	}
	ret += fmt.Sprintf("}, Len: %d", p.sortKeyLen)
	if p.limit != nil {
		ret += fmt.Sprintf(", Limit: %d,%d", p.limit.Offset, p.limit.Count)
	}
	return ret
}

type physicalPlanInfo struct {
	p     PhysicalPlan
	cost  float64
	count uint64
}

// LogicalPlan is a tree of logical operators.
// We can do a lot of logical optimizations to it, like predicate pushdown and column pruning.
type LogicalPlan interface {
	Plan

	// PredicatePushDown pushes down the predicates in the where/on/having clauses as deeply as possible.
	// It will accept a predicate that is an expression slice, and return the expressions that can't be pushed.
	// Because it might change the root if the having clause exists, we need to return a plan that represents a new root.
	PredicatePushDown([]expression.Expression) ([]expression.Expression, LogicalPlan, error)

	// PruneColumns prunes the unused columns.
	PruneColumns([]*expression.Column)

	// ResolveIndicesAndCorCols resolves the index for columns and initializes the correlated columns.
	ResolveIndicesAndCorCols()

	// convert2PhysicalPlan converts the logical plan to the physical plan.
	// It is called recursively from the parent to the children to create the result physical plan.
	// Some logical plans will convert the children to the physical plans in different ways, and return the one
	// with the lowest cost.
	convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error)

	// buildKeyInfo will collect the information of unique keys into schema.
	buildKeyInfo()
}

// PhysicalPlan is a tree of the physical operators.
type PhysicalPlan interface {
	json.Marshaler
	Plan

	// matchProperty calculates the cost of the physical plan if it matches the required property.
	// It's usually called at the end of convert2PhysicalPlan. Some physical plans do not implement it because there is
	// no property to match, these plans just do the cost calculation directly.
	// If the cost of the physical plan does not match the required property, the cost will be set to MaxInt64
	// so it will not be chosen as the result physical plan.
	// childrenPlanInfo are used to calculate the result cost of the plan.
	// The returned *physicalPlanInfo will be chosen as the final plan if it has the lowest cost.
	// For the lowest level *PhysicalTableScan and *PhysicalIndexScan, even though it doesn't have childPlanInfo, we
	// create an initial *physicalPlanInfo to pass the row count.
	matchProperty(prop *requiredProperty, childPlanInfo ...*physicalPlanInfo) *physicalPlanInfo

	// Copy copies the current plan.
	Copy() PhysicalPlan
}

type baseLogicalPlan struct {
	basePlan
	planMap map[string]*physicalPlanInfo
	self    LogicalPlan
}

func (p *baseLogicalPlan) getPlanInfo(prop *requiredProperty) (*physicalPlanInfo, error) {
	key, err := prop.getHashKey()
	if err != nil {
		return nil, errors.Trace(err)
	}
	return p.planMap[string(key)], nil
}

func (p *baseLogicalPlan) convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error) {
	info, err := p.getPlanInfo(prop)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if info != nil {
		return info, nil
	}
	if len(p.children) == 0 {
		return &physicalPlanInfo{p: p.self.(PhysicalPlan)}, nil
	}
	child := p.children[0].(LogicalPlan)
	info, err = child.convert2PhysicalPlan(prop)
	if err != nil {
		return nil, errors.Trace(err)
	}
	info = addPlanToResponse(p.self.(PhysicalPlan), info)
	return info, p.storePlanInfo(prop, info)
}

func (p *baseLogicalPlan) storePlanInfo(prop *requiredProperty, info *physicalPlanInfo) error {
	key, err := prop.getHashKey()
	if err != nil {
		return errors.Trace(err)
	}
	newInfo := *info // copy it
	p.planMap[string(key)] = &newInfo
	return nil
}

func (p *baseLogicalPlan) buildKeyInfo() {
	for _, child := range p.Children() {
		child.(LogicalPlan).buildKeyInfo()
	}
	if len(p.children) == 1 {
		switch p.self.(type) {
		case *Exists, *Aggregation, *Projection:
			p.schema.Keys = nil
		case *SelectLock:
			p.schema.Keys = p.children[0].Schema().Keys
		default:
			p.schema.Keys = p.children[0].Schema().Clone().Keys
		}
	} else {
		p.schema.Keys = nil
	}
}

func newBaseLogicalPlan(tp string, a *idAllocator) baseLogicalPlan {
	return baseLogicalPlan{
		planMap: make(map[string]*physicalPlanInfo),
		basePlan: basePlan{
			tp:        tp,
			allocator: a,
		},
	}
}

// PredicatePushDown implements LogicalPlan interface.
func (p *baseLogicalPlan) PredicatePushDown(predicates []expression.Expression) ([]expression.Expression, LogicalPlan, error) {
	if len(p.Children()) == 0 {
		return predicates, p.self, nil
	}
	child := p.children[0].(LogicalPlan)
	rest, _, err := child.PredicatePushDown(predicates)
	if err != nil {
		return nil, nil, errors.Trace(err)
	}
	if len(rest) > 0 {
		err = addSelection(p, child, rest, p.allocator)
		if err != nil {
			return nil, nil, errors.Trace(err)
		}
	}
	return nil, p.self, nil
}

func (p *basePlan) extractCorrelatedCols() []*expression.CorrelatedColumn {
	var corCols []*expression.CorrelatedColumn
	for _, child := range p.children {
		corCols = append(corCols, child.extractCorrelatedCols()...)
	}
	return corCols
}

// ResolveIndicesAndCorCols implements LogicalPlan interface.
func (p *baseLogicalPlan) ResolveIndicesAndCorCols() {
	for _, child := range p.children {
		child.(LogicalPlan).ResolveIndicesAndCorCols()
	}
}

// PruneColumns implements LogicalPlan interface.
func (p *baseLogicalPlan) PruneColumns(parentUsedCols []*expression.Column) {
	if len(p.children) == 0 {
		return
	}
	child := p.children[0].(LogicalPlan)
	child.PruneColumns(parentUsedCols)
	p.SetSchema(child.Schema())
}

func (p *basePlan) initIDAndContext(ctx context.Context) {
	p.id = p.tp + p.allocator.allocID()
	p.ctx = ctx
}

// basePlan implements base Plan interface.
// Should be used as embedded struct in Plan implementations.
type basePlan struct {
	parents  []Plan
	children []Plan

	schema    *expression.Schema
	tp        string
	id        string
	allocator *idAllocator
	ctx       context.Context
}

// MarshalJSON implements json.Marshaler interface.
func (p *basePlan) MarshalJSON() ([]byte, error) {
	children := make([]string, 0, len(p.children))
	for _, child := range p.children {
		children = append(children, child.ID())
	}
	childrenStrs, err := json.Marshal(children)
	if err != nil {
		return nil, errors.Trace(err)
	}
	buffer := bytes.NewBufferString("{")
	buffer.WriteString(fmt.Sprintf("\"children\": %s", childrenStrs))
	buffer.WriteString("}")
	return buffer.Bytes(), nil
}

// ID implements Plan ID interface.
func (p *basePlan) ID() string {
	return p.id
}

// SetSchema implements Plan SetSchema interface.
func (p *basePlan) SetSchema(schema *expression.Schema) {
	p.schema = schema
}

// Schema implements Plan Schema interface.
func (p *basePlan) Schema() *expression.Schema {
	return p.schema
}

// AddParent implements Plan AddParent interface.
func (p *basePlan) AddParent(parent Plan) {
	p.parents = append(p.parents, parent)
}

// AddChild implements Plan AddChild interface.
func (p *basePlan) AddChild(child Plan) {
	p.children = append(p.children, child)
}

// ReplaceParent means replace a parent for another one.
func (p *basePlan) ReplaceParent(parent, newPar Plan) error {
	for i, par := range p.parents {
		if par.ID() == parent.ID() {
			p.parents[i] = newPar
			return nil
		}
	}
	return SystemInternalErrorType.Gen("ReplaceParent Failed!")
}

// ReplaceChild means replace a child with another one.
func (p *basePlan) ReplaceChild(child, newChild Plan) error {
	for i, ch := range p.children {
		if ch.ID() == child.ID() {
			p.children[i] = newChild
			return nil
		}
	}
	return SystemInternalErrorType.Gen("ReplaceChildren Failed!")
}

// Parents implements Plan Parents interface.
func (p *basePlan) Parents() []Plan {
	return p.parents
}

// Children implements Plan Children interface.
func (p *basePlan) Children() []Plan {
	return p.children
}

// RemoveAllParents implements Plan RemoveAllParents interface.
func (p *basePlan) SetParents(pars ...Plan) {
	p.parents = pars
}

// RemoveAllParents implements Plan RemoveAllParents interface.
func (p *basePlan) SetChildren(children ...Plan) {
	p.children = children
}

func (p *basePlan) context() context.Context {
	return p.ctx
}


text:
package com.miao.bean;

public class GlobalInfo {
	private int version;
	private String versionStr;
	private String termBegin;
	private int yearFrom;
	private int yearTo;
	private int term;
	private int isFirstUse;
	private int activeUserUid;

	public int getVersion() {
		return version;
	}
	public void setVersion(int version) {
		this.version = version;
	}
	public String getVersionStr() {
		return versionStr;
	}
	public void setVersionStr(String versionStr) {
		this.versionStr = versionStr;
	}
	public String getTermBegin() {
		return termBegin;
	}
	public void setTermBegin(String termBegin) {
		this.termBegin = termBegin;
	}
	public int getYearFrom() {
		return yearFrom;
	}
	public void setYearFrom(int yearFrom) {
		this.yearFrom = yearFrom;
	}
	public int getYearTo() {
		return yearTo;
	}
	public void setYearTo(int yearTo) {
		this.yearTo = yearTo;
	}
	public int getTerm() {
		return term;
	}
	public void setTerm(int term) {
		this.term = term;
	}
	public int isFirstUse() {
		return isFirstUse;
	}
	public void setFirstUse(int isFirstUse) {
		this.isFirstUse = isFirstUse;
	}
	public int getActiveUserUid() { return activeUserUid;	}
	public void setActiveUserUid(int activeUserUid) {
		this.activeUserUid = activeUserUid;
	}
}


text:
class Bonus

  def pop(json)

  end

  def stack(json)

  end

  def clear(json)

  end

end


text:
package org.ardverk.dht.message;

import java.net.SocketAddress;

import org.ardverk.dht.routing.Contact;
import org.ardverk.dht.rsrc.Value;

/**
 * An abstract implementation of {@link LookupResponse}.
 */
abstract class AbstractLookupResponse extends AbstractResponseMessage
    implements LookupResponse {

  public AbstractLookupResponse(MessageId messageId,
      Contact contact, SocketAddress address) {
    super(messageId, contact, address);
  }

  public AbstractLookupResponse(MessageId messageId, Contact contact,
      SocketAddress address, Value value) {
    super(messageId, contact, address, value);
  }
}


text:
<!DOCTYPE html>

Test passes if it does not crash.


text:
<?php

namespace DTS\eBaySDK\BulkDataExchange\Types;

/**
 *
 * @property \DTS\eBaySDK\BulkDataExchange\Types\GetItemJobActionType $jobAction
 * @property \DTS\eBaySDK\BulkDataExchange\Enums\ItemEventType $filterType
 * @property boolean $includeAttributes
 * @property boolean $includeDescription
 * @property \DateTime $reportDateFrom
 * @property \DateTime $reportDateTo
 * @property string[] $timeFrame
 * @property string[] $changedFieldSelector
 */
class GetItemInfoReportFilter extends \DTS\eBaySDK\Types\BaseType
{
    /**
     * @var array Properties belonging to objects of this class.
     */
    private static $propertyTypes = array(
        'jobAction' => array(
            'type' => 'DTS\eBaySDK\BulkDataExchange\Types\GetItemJobActionType',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'jobAction'
        ),
        'filterType' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'filterType'
        ),
        'includeAttributes' => array(
            'type' => 'boolean',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'includeAttributes'
        ),
        'includeDescription' => array(
            'type' => 'boolean',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'includeDescription'
        ),
        'reportDateFrom' => array(
            'type' => 'DateTime',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'reportDateFrom'
        ),
        'reportDateTo' => array(
            'type' => 'DateTime',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'reportDateTo'
        ),
        'timeFrame' => array(
            'type' => 'string',
            'unbound' => true,
            'attribute' => false,
            'elementName' => 'timeFrame'
        ),
        'changedFieldSelector' => array(
            'type' => 'string',
            'unbound' => true,
            'attribute' => false,
            'elementName' => 'changedFieldSelector'
        )
    );

    /**
     * @param array $values Optional properties and values to assign to the object.
     */
    public function __construct(array $values = array())
    {
        list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);

        parent::__construct($parentValues);

        if (!array_key_exists(__CLASS__, self::$properties)) {
            self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
        }

        if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
            self::$xmlNamespaces[__CLASS__] = 'http://www.ebay.com/marketplace/services';
        }

        $this->setValues(__CLASS__, $childValues);
    }
}


text:
/**
 * Keep track of view changes
 */
// This is only needed for UIView type reference
import UIView = require('./UI/UIView');

var stack: UIView[] = [];

export function pop() {
	var currentView = stack.pop(),
		lastView = stack.slice(-1)[0];
	if (lastView) {
	// lastView.navigate(lastView);
		history.back();
	}
	console.log('pop:', stack);
}

export function push(view: UIView) {
	stack.push(view);
	console.log('push:', stack);
}

export function purge() {
	stack.splice(0, stack.length);
}

export function replace(view: UIView, checkOlder: boolean = false) {
	if (stack.length == 0) {
		return;
	}

	if (checkOlder) {
		// remove older view already on stack
		for (var i = stack.length - 1; i >= 0; i++) {
			if (view == stack[i]) {
				stack.splice(i + 1);
				console.log('replace:', stack);
				return;
			}
		}
	}

	stack[stack.length - 1] = view;
	console.log('replace:', stack);
}


text:
<?php

namespace Kunstmaan\MultiDomainBundle\Controller;

use Kunstmaan\MultiDomainBundle\Helper\DomainConfiguration;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class SiteSwitchController extends Controller
{
    /**
     * @Route("/switch-site", name="KunstmaanMultiDomainBundle_switch_site")
     * @Method({"GET"})
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     *
     * @return Response
     * @throws AccessDeniedException
     * @throws NotFoundHttpException
     */
    public function switchAction(Request $request)
    {
        $domainConfiguration = $this->get('kunstmaan_admin.domain_configuration');
        $host = $request->query->get('host');
        $hosts = $domainConfiguration->getFullHostConfig();
        if (!array_key_exists($host, $hosts)) {
            throw $this->createNotFoundException('Invalid host specified');
        }

        $currentHost = $domainConfiguration->getHost();

        $session = $request->getSession();
        if ($request->get('from_url_chooser')) {
            $session->set(DomainConfiguration::SWITCH_HOST, $host);
        } else {
            $session->set(DomainConfiguration::OVERRIDE_HOST, $host);
        }

        /**
         * If current host type is different then the host going to, redirect to it's homepage.
         * If coming from url chooser, don't redirect to homepage if other host.
         */
        if ((($hosts[$host]['type'] !== $hosts[$currentHost]['type']) || (!$request->query->has('route'))) && (!$request->get('from_url_chooser'))) {
            $route = "KunstmaanAdminBundle_homepage";
            $defaultLocale = $this->get('kunstmaan_admin.domain_configuration')->getDefaultLocale();
        } else {
            $route = $request->query->get('route');
            $routeParams = $request->query->get('route_params');
            $defaultLocale = $hosts[$host]['default_locale'];
        }

        $routeParams['_locale'] = $defaultLocale;

        $response = new RedirectResponse(
            $this->get('router')->generate($route, $routeParams)
        );

        return $response;
    }
}


text:
namespace NWindows {
namespace NFile {
namespace NDirectory {

#ifdef WIN_LONG_PATH
bool GetLongPaths(LPCWSTR s1, LPCWSTR s2, UString &d1, UString &d2);
#endif

bool MyGetWindowsDirectory(CSysString &path);
bool MyGetSystemDirectory(CSysString &path);
#ifndef _UNICODE
bool MyGetWindowsDirectory(UString &path);
bool MyGetSystemDirectory(UString &path);
#endif

bool SetDirTime(LPCWSTR fileName, const FILETIME *cTime, const FILETIME *aTime, const FILETIME *mTime);

bool MySetFileAttributes(LPCTSTR fileName, DWORD fileAttributes);
bool MyMoveFile(LPCTSTR existFileName, LPCTSTR newFileName);
bool MyRemoveDirectory(LPCTSTR pathName);
bool MyCreateDirectory(LPCTSTR pathName);
bool CreateComplexDirectory(LPCTSTR pathName);
bool DeleteFileAlways(LPCTSTR name);
bool RemoveDirectoryWithSubItems(const CSysString &path);

#ifndef _UNICODE
bool MySetFileAttributes(LPCWSTR fileName, DWORD fileAttributes);
bool MyMoveFile(LPCWSTR existFileName, LPCWSTR newFileName);
bool MyRemoveDirectory(LPCWSTR pathName);
bool MyCreateDirectory(LPCWSTR pathName);
bool CreateComplexDirectory(LPCWSTR pathName);
bool DeleteFileAlways(LPCWSTR name);
bool RemoveDirectoryWithSubItems(const UString &path);
#endif

bool GetOnlyDirPrefix(LPCTSTR fileName, CSysString &resultName);
bool GetOnlyName(LPCTSTR fileName, CSysString &resultName);
#ifdef UNDER_CE
bool MyGetFullPathName(LPCWSTR fileName, UString &resultPath);
bool MyGetFullPathName(LPCWSTR fileName, UString &resultPath, int &fileNamePartStartIndex);
#else
bool MyGetShortPathName(LPCTSTR longPath, CSysString &shortPath);

bool MyGetFullPathName(LPCTSTR fileName, CSysString &resultPath, int &fileNamePartStartIndex);
bool MyGetFullPathName(LPCTSTR fileName, CSysString &resultPath);
#ifndef _UNICODE
bool MyGetFullPathName(LPCWSTR fileName, UString &resultPath,
    int &fileNamePartStartIndex);
bool MyGetFullPathName(LPCWSTR fileName, UString &resultPath);
bool GetOnlyName(LPCWSTR fileName, UString &resultName);
bool GetOnlyDirPrefix(LPCWSTR fileName, UString &resultName);
#endif

inline bool MySetCurrentDirectory(LPCTSTR path)
  { return BOOLToBool(::SetCurrentDirectory(path)); }
bool MyGetCurrentDirectory(CSysString &resultPath);
#ifndef _UNICODE
bool MySetCurrentDirectory(LPCWSTR path);
bool MyGetCurrentDirectory(UString &resultPath);
#endif

bool MySearchPath(LPCTSTR path, LPCTSTR fileName, LPCTSTR extension, CSysString &resultPath, UINT32 &filePart);
#ifndef _UNICODE
bool MySearchPath(LPCWSTR path, LPCWSTR fileName, LPCWSTR extension, UString &resultPath, UINT32 &filePart);
#endif

inline bool MySearchPath(LPCTSTR path, LPCTSTR fileName, LPCTSTR extension, CSysString &resultPath)
{
  UINT32 value;
  return MySearchPath(path, fileName, extension, resultPath, value);
}

#ifndef _UNICODE
inline bool MySearchPath(LPCWSTR path, LPCWSTR fileName, LPCWSTR extension, UString &resultPath)
{
  UINT32 value;
  return MySearchPath(path, fileName, extension, resultPath, value);
}
#endif

#endif

bool MyGetTempPath(CSysString &resultPath);
#ifndef _UNICODE
bool MyGetTempPath(UString &resultPath);
#endif

UINT MyGetTempFileName(LPCTSTR dirPath, LPCTSTR prefix, CSysString &resultPath);
#ifndef _UNICODE
UINT MyGetTempFileName(LPCWSTR dirPath, LPCWSTR prefix, UString &resultPath);
#endif

class CTempFile
{
  bool _mustBeDeleted;
  CSysString _fileName;
public:
  CTempFile(): _mustBeDeleted(false) {}
  ~CTempFile() { Remove(); }
  void DisableDeleting() { _mustBeDeleted = false; }
  UINT Create(LPCTSTR dirPath, LPCTSTR prefix, CSysString &resultPath);
  bool Create(LPCTSTR prefix, CSysString &resultPath);
  bool Remove();
};

#ifdef _UNICODE
typedef CTempFile CTempFileW;
#else
class CTempFileW
{
  bool _mustBeDeleted;
  UString _fileName;
public:
  CTempFileW(): _mustBeDeleted(false) {}
  ~CTempFileW() { Remove(); }
  void DisableDeleting() { _mustBeDeleted = false; }
  UINT Create(LPCWSTR dirPath, LPCWSTR prefix, UString &resultPath);
  bool Create(LPCWSTR prefix, UString &resultPath);
  bool Remove();
};
#endif

bool CreateTempDirectory(LPCTSTR prefixChars, CSysString &dirName);

class CTempDirectory
{
  bool _mustBeDeleted;
  CSysString _tempDir;
public:
  const CSysString &GetPath() const { return _tempDir; }
  CTempDirectory(): _mustBeDeleted(false) {}
  ~CTempDirectory() { Remove();  }
  bool Create(LPCTSTR prefix) ;
  bool Remove()
  {
    if (!_mustBeDeleted)
      return true;
    _mustBeDeleted = !RemoveDirectoryWithSubItems(_tempDir);
    return (!_mustBeDeleted);
  }
  void DisableDeleting() { _mustBeDeleted = false; }
};

#ifdef _UNICODE
typedef CTempDirectory CTempDirectoryW;
#else
class CTempDirectoryW
{
  bool _mustBeDeleted;
  UString _tempDir;
public:
  const UString &GetPath() const { return _tempDir; }
  CTempDirectoryW(): _mustBeDeleted(false) {}
  ~CTempDirectoryW() { Remove();  }
  bool Create(LPCWSTR prefix) ;
  bool Remove()
  {
    if (!_mustBeDeleted)
      return true;
    _mustBeDeleted = !RemoveDirectoryWithSubItems(_tempDir);
    return (!_mustBeDeleted);
  }
  void DisableDeleting() { _mustBeDeleted = false; }
};
#endif

}}}

#endif


text:
package org.apache.flink.runtime.state.ttl;

import org.apache.flink.runtime.state.StateEntry;
import org.apache.flink.runtime.state.internal.InternalKvState.StateIncrementalVisitor;
import org.apache.flink.util.FlinkRuntimeException;

import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;

import java.util.Collection;

/**
 * Incremental cleanup of state with TTL.
 *
 * @param <K> type of state key
 * @param <N> type of state namespace
 */
class TtlIncrementalCleanup<K, N, S> {
    /** Global state entry iterator is advanced for {@code cleanupSize} entries. */
    @Nonnegative private final int cleanupSize;

    /**
     * Particular state with TTL object is used to check whether currently iterated entry has
     * expired.
     */
    private AbstractTtlState<K, N, ?, S, ?> ttlState;

    /**
     * Global state entry iterator, advanced for {@code cleanupSize} entries every state and/or
     * record processing.
     */
    private StateIncrementalVisitor<K, N, S> stateIterator;

    /**
     * TtlIncrementalCleanup constructor.
     *
     * @param cleanupSize max number of queued keys to incrementally cleanup upon state access
     */
    TtlIncrementalCleanup(@Nonnegative int cleanupSize) {
        this.cleanupSize = cleanupSize;
    }

    void stateAccessed() {
        initIteratorIfNot();
        try {
            runCleanup();
        } catch (Throwable t) {
            throw new FlinkRuntimeException("Failed to incrementally clean up state with TTL", t);
        }
    }

    private void initIteratorIfNot() {
        if (stateIterator == null || !stateIterator.hasNext()) {
            stateIterator = ttlState.original.getStateIncrementalVisitor(cleanupSize);
        }
    }

    private void runCleanup() {
        int entryNum = 0;
        Collection<StateEntry<K, N, S>> nextEntries;
        while (entryNum < cleanupSize
                && stateIterator.hasNext()
                && !(nextEntries = stateIterator.nextEntries()).isEmpty()) {

            for (StateEntry<K, N, S> state : nextEntries) {
                S cleanState = ttlState.getUnexpiredOrNull(state.getState());
                if (cleanState == null) {
                    stateIterator.remove(state);
                } else if (cleanState != state.getState()) {
                    stateIterator.update(state, cleanState);
                }
            }

            entryNum += nextEntries.size();
        }
    }

    /**
     * As TTL state wrapper depends on this class through access callback, it has to be set here
     * after its construction is done.
     */
    public void setTtlState(@Nonnull AbstractTtlState<K, N, ?, S, ?> ttlState) {
        this.ttlState = ttlState;
    }

    int getCleanupSize() {
        return cleanupSize;
    }
}


text:
<?php

namespace Oro\Bundle\ReportBundle\Migrations\Schema\v1_4;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\MigrationBundle\Migration\QueryBag;
use Oro\Bundle\MigrationBundle\Migration\Migration;

class OroReportBundle implements Migration
{
    /**
     * @inheritdoc
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        $queries->addPostQuery(new UpdateReportJsonArrayQuery());
    }
}


text:
class RepeatedTimer(object):
    def __init__(self, interval, function, *args, **kwargs):
        self._timer = None
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.is_running = False

	#monitor the timer running
    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)

	#start the timer
    def start(self):
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.start()
            self.is_running = True

	#stop the timer
    def stop(self):
        self._timer.cancel()
        self.is_running = False


text:
print(__doc__)

import time as time
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets.samples_generator import make_swiss_roll

###############################################################################
# Generate data (swiss roll dataset)
n_samples = 1500
noise = 0.05
X, _ = make_swiss_roll(n_samples, noise)
# Make it thinner
X[:, 1] *= .5

###############################################################################
# Compute clustering
print("Compute unstructured hierarchical clustering...")
st = time.time()
ward = AgglomerativeClustering(n_clusters=6, linkage='ward').fit(X)
elapsed_time = time.time() - st
label = ward.labels_
print("Elapsed time: %.2fs" % elapsed_time)
print("Number of points: %i" % label.size)

###############################################################################
# Plot result
fig = plt.figure()
ax = p3.Axes3D(fig)
ax.view_init(7, -80)
for l in np.unique(label):
    ax.plot3D(X[label == l, 0], X[label == l, 1], X[label == l, 2],
              'o', color=plt.cm.jet(np.float(l) / np.max(label + 1)))
plt.title('Without connectivity constraints (time %.2fs)' % elapsed_time)

###############################################################################
# Define the structure A of the data. Here a 10 nearest neighbors
from sklearn.neighbors import kneighbors_graph
connectivity = kneighbors_graph(X, n_neighbors=10, include_self=False)

###############################################################################
# Compute clustering
print("Compute structured hierarchical clustering...")
st = time.time()
ward = AgglomerativeClustering(n_clusters=6, connectivity=connectivity,
                               linkage='ward').fit(X)
elapsed_time = time.time() - st
label = ward.labels_
print("Elapsed time: %.2fs" % elapsed_time)
print("Number of points: %i" % label.size)

###############################################################################
# Plot result
fig = plt.figure()
ax = p3.Axes3D(fig)
ax.view_init(7, -80)
for l in np.unique(label):
    ax.plot3D(X[label == l, 0], X[label == l, 1], X[label == l, 2],
              'o', color=plt.cm.jet(float(l) / np.max(label + 1)))
plt.title('With connectivity constraints (time %.2fs)' % elapsed_time)

plt.show()


text:
package utils;

public class UnitConverter {
	/**
	 *Method that returns the numbers of cycles the counter need to pass between
	 *interrupts to measure the provided mph given a specified wheel diameter
	 * @param mph the mph to be converted.
	 * @param wheelDiameterInches the diameter of the wheel in inches.
	 * @return the number of cycles (AT unit)
	 */
	public static final int mphToATu(double mph, double wheelDiameterInches) {
		double atu = (1/mph)*ATuFactor(wheelDiameterInches);
		return (int) atu;
	}

	/**
	 * Method that converts from ATu to MPH. The result has up to 2 decimal figures.
	 * @param atu reading from the tachometer's counter
	 * @param wheelDiameterInches
	 * @return
	 */
	public static final double ATuToMPH(double atu, double wheelDiameterInches) {
		double mph = (1/atu) * ATuFactor(wheelDiameterInches);
		return mph;
	}

	private static final double ATuFactor(double wheelDiameterInches) {
		return (3600.0/63360.0)*(wheelDiameterInches*Math.PI/5.0)*(1000000.0/32.0);
	}

//	public static final double weightToVoltage(double voltage) {
//		double x = voltage;
//		double force = (2.345/227.84*((x-226.8)*(x-158.8))) + (2.29/-217.6*(x-230.0)*(x-158.8)) + (1.93/4841.6*(x-230.0)*(x-226.8));
//		return force;
//	}

	 public static String bitString(byte value)
	  {
	    String str = "";

	    long bitHolder = 1L;
	    for (int i = 0; i < 8; ++i)
	    {
	      if ((value & bitHolder) > 0L)
	        str = "1" + str;
	      else
	        str = "0" + str;
	      bitHolder <<= 1;
	    }
	    return str;
	  }

	 public static final double weightToVoltage(double weight) {
		 //calculation of the weight to voltage conversion.
		 double voltage = 3.3 - 3.3 * Math.exp(-0.005391158 * weight);
		 return voltage;
	 }

	 public static final double voltageToWeight(double voltage) {
		 double weight= Math.log(((voltage - 3.3)/-3.3)) / (-0.005391158);
		 return weight;
	 }

	 public static int voltageToADC (double voltage) {
		 int adc =  (int) Math.round(adcConstant() * voltage);
		 return adc;
	 }

	 public static double adcToVoltage(int adc) {
		 double voltage = ((double)adc)/adcConstant();
		 return voltage;
	 }

	 private static final double adcConstant() {
		 return Math.round(((Math.pow(2, 10))/3.3));
	 }

}


text:
import {ILinkedListItem} from "./Interfaces/ILinkedListItem";
export class LinkedList<T> {
    public head:ILinkedListItem<T> = LinkedList.emptyListItem<T>();
    public length:number = 0;
    public tail:ILinkedListItem<T> = LinkedList.emptyListItem<T>();

    public static emptyListItem<T> ():ILinkedListItem<T> {
        return <ILinkedListItem<T>>({ prev:null, value:null, next:null });
    }

    public static newItem<T> (prev:ILinkedListItem<T>, next:ILinkedListItem<T>, value: T):ILinkedListItem<T> {
        return <ILinkedListItem<T>>({ prev: prev, next: next, value: value });
    }

    constructor () {
        this.tail.prev = this.head;
        this.head.next = this.tail;
    }

    public forEach(callback: (item: T, index:number, list:LinkedList<T>) => void, thisArg:any = null): void {
        var currentItem = this.head.next;
        var counter = 0;
        while(currentItem !== this.tail) {
            callback.call(thisArg, currentItem.value, counter, this);
            counter++;
            currentItem = currentItem.next;
        }
    }

    public isEmpty():boolean {
        return this.head.next === this.tail;
    }

    public push(value:T): void {
        this.addAfter(value, this.tail.prev);
    }

    public pop(): T{
        var currentItem = this.tail.prev;
        if(this.isEmpty()) {
            throw new Error(`The linked list is empty.`);
        }
        this.removeItem(currentItem);
        return currentItem.value;
    }

    public remove(value:T): void{
        var currentItem = this.search(value);
        if (currentItem) {
            this.removeItem(currentItem);
        } else {
            throw new Error(`Cannot remove the value ${value}, it's not present in the linked list.`);
        }
    }

    public shift(): T{
        var item = this.head.next;
        if(this.isEmpty()) {
            throw new Error(`The linked list is empty.`);
        }
        this.removeItem(item);
        return item.value;
    }

    public unshift(value:T): void{
        this.addAfter(value, this.head);
    }

    private addAfter(value:T, itemAfter:ILinkedListItem<T>): void{
        var newItem = LinkedList.newItem(itemAfter, itemAfter.next, value);
        itemAfter.next.prev = newItem;
        itemAfter.next = newItem;
        this.length++;
    }

    private removeItem(item:ILinkedListItem<T>): void{
        item.prev.next = item.next;
        item.next.prev = item.prev;
        this.length--;
    }

    private search(value:T): ILinkedListItem<T>{
        var currentItem = this.head.next;
        while(currentItem !== this.tail) {
            if (value === currentItem.value) {
                return currentItem;
            }
            currentItem = currentItem.next;
        }
        return null;
    }
}


text:
chown vagrant:vagrant /home/vagrant -Rf

apt-get install -y vim git tree zip unzip ack-grep python-pip


text:
using namespace cv::gpu;

CVAPI(ORB_GPU*) gpu_ORB_GPU_new(
    int nFeatures, float scaleFactor, int nLevels, int edgeThreshold,
    int firstLevel, int WTA_K, int scoreType, int patchSize)
{
    return new ORB_GPU(nFeatures, scaleFactor, nLevels, edgeThreshold,
        firstLevel, WTA_K, scoreType, patchSize);
}

CVAPI(void) gpu_ORB_GPU_delete(ORB_GPU *obj)
{
    delete obj;
}

CVAPI(void) gpu_ORB_GPU_operator1(ORB_GPU *obj, GpuMat *image, GpuMat *mask, GpuMat *keypoints)
{
    (*obj)(*image, *mask, *keypoints);
}
CVAPI(void) gpu_ORB_GPU_operator2(ORB_GPU *obj, GpuMat *image, GpuMat *mask, std::vector<cv::KeyPoint> *keypoints)
{
    (*obj)(*image, *mask, *keypoints);
}

CVAPI(void) gpu_ORB_GPU_operator3(ORB_GPU *obj, GpuMat *image, GpuMat *mask, std::vector<cv::KeyPoint> *keypoints, GpuMat *descriptors)
{
    (*obj)(*image, *mask, *keypoints, *descriptors);
}
CVAPI(void) gpu_ORB_GPU_operator4(ORB_GPU *obj, GpuMat *image, GpuMat *mask, GpuMat *keypoints, GpuMat *descriptors)
{
    (*obj)(*image, *mask, *keypoints, *descriptors);
}

CVAPI(void) gpu_ORB_GPU_downloadKeyPoints(ORB_GPU *obj, GpuMat *d_keypoints, std::vector<cv::KeyPoint> *keypoints)
{
    obj->downloadKeyPoints(*d_keypoints, *keypoints);
}

CVAPI(void) gpu_ORB_GPU_convertKeyPoints(ORB_GPU *obj, cv::Mat *h_keypoints, std::vector<cv::KeyPoint> *keypoints)
{
    obj->convertKeyPoints(*h_keypoints, *keypoints);
}

CVAPI(int) gpu_ORB_GPU_descriptorSize(ORB_GPU *obj)
{
    return obj->descriptorSize();
}

CVAPI(void) gpu_ORB_GPU_release(ORB_GPU *obj)
{
    obj->release();
}

CVAPI(void) gpu_ORB_GPU_setFastParams(ORB_GPU *obj, int threshold, int nonmaxSuppression)
{
    obj->setFastParams(threshold, nonmaxSuppression != 0);
}

CVAPI(int) gpu_ORB_GPU_blurForDescriptor_get(ORB_GPU *obj)
{
    return obj->blurForDescriptor ? 1 : 0;
}
CVAPI(void) gpu_ORB_GPU_blurForDescriptor_set(ORB_GPU *obj, int value)
{
    obj->blurForDescriptor = (value != 0);
}

#endif


text:
use std::ops::{Add, Sub, Mul, Div, Rem, Index};

use crate::{context::{Container, Context}, value::Value, types::*};

pub enum Execute {}

include! {
    concat!(env!("OUT_DIR"), "/execute.rs")
}

impl Context for Execute {}


text:
#include "FilterLocator.h"
#include "MixParam.h"
#include "KeyBinding.h"

#include "MackieControl.h"
#include "MackieControlInformation.h"
#include "MackieControlState.h"
#include "MackieControlBase.h"

#include "MackieControlLCDDisplay.h"
#include "MackieControlVPotDisplay.h"
#include "MackieControlFader.h"
#include "MackieControlXT.h"

#include "MackieControl7SegmentDisplay.h"
#include "MackieControlMaster.h"
#include "MackieControlMasterPropPage.h"

/////////////////////////////////////////////////////////////////////////////

void CMackieControlMaster::OnRefreshSurface(DWORD fdwRefresh, bool bForceSend)
{
//	TRACE("CMackieControlMaster::OnRefreshSurface()\n");

	// First see if there's any temp text we need to display
	CheckForTempDisplayText();

	// Make sure the parameter offset is always in range too
//	ShiftParamNumOffset(0);		// Maybe not such a good idea

	// Update the XT section
	CMackieControlXT::OnRefreshSurface(fdwRefresh, bForceSend);

	// Now update the master section
	CCriticalSectionAuto csa(m_cState.GetCS());

	if (!GetUseHUIProtocol())
		ReconfigureMaster(bForceSend);

	// Do the reconfigure before this so that the setup is up to date
	UpdateToolbarDisplay(bForceSend);

	UpdateLEDs(bForceSend);
	UpdateTransportLEDs(bForceSend);
	UpdateVSelectDisplay(bForceSend);
	UpdateTimeCodeDisplay(bForceSend);

	if (!m_cState.GetDisableFaders() && !GetUseHUIProtocol())
		UpdateMasterFader(bForceSend);
}

/////////////////////////////////////////////////////////////////////////////

void CMackieControlMaster::CheckForTempDisplayText()
{
	CCriticalSectionAuto csa(m_cState.GetCS());

	char *szText  = m_cState.GetTempDisplayText();

	if (szText[0] != 0)
	{
		TempDisplay(TEMP_DISPLAY_TIMEOUT, szText);

		m_cState.SetTempDisplayText("");
	}
}

/////////////////////////////////////////////////////////////////////////////

void CMackieControlMaster::UpdateLEDs(bool bForceSend)
{
	SetLED(MC_PARAM,		m_cState.GetAssignment() == MCS_ASSIGNMENT_PARAMETER,	bForceSend);
	SetLED(MC_SEND,			m_cState.GetAssignment() == MCS_ASSIGNMENT_SEND,		bForceSend);
	SetLED(MC_PAN,			m_cState.GetAssignment() == MCS_ASSIGNMENT_PAN,			bForceSend);
	SetLED(MC_PLUG_INS,		m_cState.GetAssignment() == MCS_ASSIGNMENT_PLUGIN,		bForceSend);
	SetLED(MC_EQ,			m_cState.GetAssignment() == MCS_ASSIGNMENT_EQ_FREQ_GAIN ||
							m_cState.GetAssignment() == MCS_ASSIGNMENT_EQ,			bForceSend);
	SetLED(MC_DYNAMICS,		m_cState.GetAssignment() == MCS_ASSIGNMENT_DYNAMICS,	bForceSend);

	if (MCS_FLIP_NORMAL == m_cState.GetFlipMode())
		SetLED(MC_FLIP,		0,														bForceSend);
	else if (MCS_FLIP_DUPLICATE == m_cState.GetFlipMode())
		SetLED(MC_FLIP,		2,														bForceSend);
	else
		SetLED(MC_FLIP,		1,														bForceSend);

	if (m_cState.GetModifiers(MCS_MODIFIER_EDIT))
		SetLED(MC_EDIT,		1,														bForceSend);
	else if (m_cState.GetModifiers(MCS_MODIFIER_NUMERIC))
		SetLED(MC_EDIT,		2,														bForceSend);
	else
		SetLED(MC_EDIT,		0,														bForceSend);

	SetLED(MC_READ_OFF,		m_bSwitches[MC_READ_OFF],								bForceSend);
	SetLED(MC_SNAPSHOT,		m_bSwitches[MC_SNAPSHOT],								bForceSend);
	SetLED(MC_DISARM,		m_bSwitches[MC_DISARM],									bForceSend);
	SetLED(MC_OFFSET,		m_bSwitches[MC_OFFSET],									bForceSend);

	SetLED(MC_TRACK,		m_cState.GetMixerStrip() == MIX_STRIP_TRACK,			bForceSend);
	SetLED(MC_AUX,			m_cState.GetMixerStrip() == m_cState.BusType(),			bForceSend);
	SetLED(MC_MAIN,			m_cState.GetMixerStrip() == m_cState.MasterType(),		bForceSend);

	SetLED(MC_SAVE,			m_bSwitches[MC_SAVE],									bForceSend);

	SetLED(MC_MARKER,		m_cState.GetNavigationMode() == MCS_NAVIGATION_MARKER,	bForceSend);
	SetLED(MC_LOOP,			m_cState.GetNavigationMode() == MCS_NAVIGATION_LOOP,	bForceSend);
	SetLED(MC_SELECT,		m_cState.GetNavigationMode() == MCS_NAVIGATION_SELECT,	bForceSend);
	SetLED(MC_PUNCH,		m_cState.GetNavigationMode() == MCS_NAVIGATION_PUNCH,	bForceSend);

	SetLED(MC_JOG_PRM,		m_cState.GetJogParamMode(),								bForceSend);
	SetLED(MC_HOME,			m_bSwitches[MC_HOME],									bForceSend);

	SetLED(MC_CURSOR_ZOOM,	(BYTE)m_cState.GetModifiers(MCS_MODIFIER_ZOOM),				bForceSend);

	SetLED(MC_SMPTE,		m_cState.GetDisplaySMPTE(),								bForceSend);
	SetLED(MC_BEATS,		!m_cState.GetDisplaySMPTE(),							bForceSend);

	SetLED(MC_RUDE,			GetRudeSoloStatus() ? 2 : 0,							bForceSend);
}

/////////////////////////////////////////////////////////////////////////////

void CMackieControlMaster::UpdateTransportLEDs(bool bForceSend)
{
	bool bPlaying = GetTransportState(TRANSPORT_STATE_PLAY);

	SetLED(MC_LOOP_ON_OFF,	GetTransportState(TRANSPORT_STATE_LOOP),	bForceSend);
	SetLED(MC_REWIND,		m_bSwitches[MC_REWIND],						bForceSend);
	SetLED(MC_FAST_FORWARD,	m_bSwitches[MC_FAST_FORWARD],				bForceSend);
	SetLED(MC_STOP,			!bPlaying,									bForceSend);
	SetLED(MC_PLAY,			bPlaying,									bForceSend);
	SetLED(MC_RECORD,		GetTransportState(TRANSPORT_STATE_REC),		bForceSend);
	SetLED(MC_SCRUB,		GetTransportState(TRANSPORT_STATE_SCRUB),	bForceSend);
}

/////////////////////////////////////////////////////////////////////////////

void CMackieControlMaster::UpdateVSelectDisplay(bool bForceSend)
{
	if (UsingHUIProtocol())
		return;

	bool bDot = (m_cState.GetAssignmentMode() == MCS_ASSIGNMENT_CHANNEL_STRIP);

	switch (m_cState.GetAssignment())
	{
		case MCS_ASSIGNMENT_PARAMETER:
			switch (m_cState.GetMixerStrip())
			{
				case MIX_STRIP_TRACK:
					m_cVSelectDisplay[0].SetChar('T', false, bForceSend);
					m_cVSelectDisplay[1].SetChar('r', bDot, bForceSend);
					break;

				case MIX_STRIP_AUX:
					m_cVSelectDisplay[0].SetChar('A', false, bForceSend);
					m_cVSelectDisplay[1].SetChar('u', bDot, bForceSend);
					break;

				case MIX_STRIP_MAIN:
					m_cVSelectDisplay[0].SetChar('V', false, bForceSend);
					m_cVSelectDisplay[1].SetChar('m', bDot, bForceSend);
					break;

				case MIX_STRIP_BUS:
					m_cVSelectDisplay[0].SetChar('B', false, bForceSend);
					m_cVSelectDisplay[1].SetChar('u', bDot, bForceSend);
					break;

				case MIX_STRIP_MASTER:
					m_cVSelectDisplay[0].SetChar('O', false, bForceSend);
					m_cVSelectDisplay[1].SetChar('p', bDot, bForceSend);
					break;

				default:
					break;
			}
			break;

		case MCS_ASSIGNMENT_PAN:
			m_cVSelectDisplay[0].SetChar('P', false, bForceSend);
			m_cVSelectDisplay[1].SetChar('n', bDot, bForceSend);
			break;

		case MCS_ASSIGNMENT_SEND:
			m_cVSelectDisplay[0].SetChar('S', false, bForceSend);
			m_cVSelectDisplay[1].SetChar('e', bDot, bForceSend);
			break;

		case MCS_ASSIGNMENT_PLUGIN:
			if ( m_cState.GetMixerStrip() == MIX_STRIP_RACK )
			{
				m_cVSelectDisplay[0].SetChar( 'S', false, bForceSend );
				m_cVSelectDisplay[1].SetChar( 'y', false, bForceSend );
			}
			else
			{
				m_cVSelectDisplay[0].SetChar( 'P', false, bForceSend );
				m_cVSelectDisplay[1].SetChar( 'l', false, bForceSend );
			}
			break;

		case MCS_ASSIGNMENT_EQ:
			m_cVSelectDisplay[0].SetChar('E', false, bForceSend);
			m_cVSelectDisplay[1].SetChar('q', false, bForceSend );
			break;

		case MCS_ASSIGNMENT_EQ_FREQ_GAIN:
			m_cVSelectDisplay[0].SetChar( 'F', false, bForceSend );
			m_cVSelectDisplay[1].SetChar( 'g', false, bForceSend );
			break;

		case MCS_ASSIGNMENT_DYNAMICS:
			m_cVSelectDisplay[0].SetChar( 'D', false, bForceSend );
			m_cVSelectDisplay[1].SetChar( 'y', false, bForceSend );
			break;

		default:
			break;
	}
}

/////////////////////////////////////////////////////////////////////////////

void CMackieControlMaster::UpdateTimeCodeDisplay(bool bForceSend)
{
	MFX_TIME timeCurrent;

	// First check to see if it's changed
	timeCurrent.timeFormat = TF_SECONDS;
	HRESULT hr = m_pTransport->GetTransportTime(TRANSPORT_TIME_CURSOR, &timeCurrent);

	if (FAILED(hr) || m_cState.GetLastDisplayTime() == timeCurrent.dSeconds)
		return;

	m_cState.SetLastDisplayTime(timeCurrent.dSeconds);

	// It has...

	char sBuf[32];

	if (m_cState.GetDisplaySMPTE())
	{
		timeCurrent.timeFormat = TF_SMPTE_REL;
		HRESULT hr = m_pTransport->GetTransportTime(TRANSPORT_TIME_CURSOR, &timeCurrent);

		if (FAILED(hr))
			return;

//		TRACE("SMPTE: %d %d %d %d %d\n", timeCurrent.smpte.nHour, timeCurrent.smpte.nMin,
//										timeCurrent.smpte.nSec, timeCurrent.smpte.nFrame,
//										timeCurrent.smpte.nSub400);

		if (timeCurrent.smpte.nSub400 >= 200)
			timeCurrent.smpte.nFrame++;

		char cFrameMax = 0;
		switch (timeCurrent.smpte.fps)
		{
			case FPS_24:			cFrameMax = 24;		break;
			case FPS_25:			cFrameMax = 25;		break;
			case FPS_2997:			cFrameMax = 29;		break;
			case FPS_2997_DROP:		cFrameMax = 29;		break;
			case FPS_30:			cFrameMax = 30;		break;
			case FPS_30_DROP:		cFrameMax = 30;		break;

			default:
				return;
		}

		if (timeCurrent.smpte.nFrame >= cFrameMax)
		{
			timeCurrent.smpte.nFrame = 0;
			timeCurrent.smpte.nSec++;
		}
		if (timeCurrent.smpte.nSec >= 60)
		{
			timeCurrent.smpte.nSec = 0;
			timeCurrent.smpte.nMin++;
		}
		if (timeCurrent.smpte.nMin >= 60)
		{
			timeCurrent.smpte.nMin = 0;
			timeCurrent.smpte.nHour++;
		}

		char sHour[8];
		snprintf(sHour, sizeof(sHour), "%02d", timeCurrent.smpte.nHour);

		char sFrame[8];
		snprintf(sFrame, sizeof(sFrame), "%02d", timeCurrent.smpte.nFrame);

		if (UsingHUIProtocol())
			snprintf(sBuf, sizeof(sBuf), "%2s.%02d.%02d.%2s", sHour, timeCurrent.smpte.nMin, timeCurrent.smpte.nSec, sFrame);
		else
			snprintf(sBuf, sizeof(sBuf), "%3s.%02d.%02d.%3s", sHour, timeCurrent.smpte.nMin, timeCurrent.smpte.nSec, sFrame);
	}
	else
	{
		timeCurrent.timeFormat = TF_MBT;
		HRESULT hr = m_pTransport->GetTransportTime(TRANSPORT_TIME_CURSOR, &timeCurrent);

		if (FAILED(hr))
			return;

		if (UsingHUIProtocol())
			snprintf(sBuf, sizeof(sBuf), "%03d.%02d.%03d", timeCurrent.mbt.nMeas, timeCurrent.mbt.nBeat, timeCurrent.mbt.nTick);
		else
			snprintf(sBuf, sizeof(sBuf), "%3d%02d  %03d", timeCurrent.mbt.nMeas, timeCurrent.mbt.nBeat, timeCurrent.mbt.nTick);
	}

	char *s = sBuf;

	if (UsingHUIProtocol())
	{
		// HUI timecode display
		// TODO: Make this more efficient. We shouldn't have to send out the whole 8 chars every time.

		for (int n = 0; n < NUM_HUI_TIME_CODE_DISPLAY_CELLS; n++)
		{
			if (*s)
			{
				bool bDot = (s[1] == '.') && (n < 7);

				// buffer is populated right to left
				m_bHuiTimeCodeSysExBuff[(14 - n)] = bDot ? (*s - 0x20) : (*s - 0x30);

				if (bDot)
					s++;
				s++;
			}
			else
			{
				m_bHuiTimeCodeSysExBuff[14 - n] = 0;
			}
		}

		SendMidiLong(16, &m_bHuiTimeCodeSysExBuff[0]);
	}
	else
	{
		// MCU timecode display
		for (int n = 0; n < NUM_TIME_CODE_DISPLAY_CELLS; n++)
		{
			if (*s)
			{
				bool bDot = (s[1] == '.');

				m_cTimeCodeDisplay[n].SetChar(*s, bDot, bForceSend);

				if (bDot)
					s++;
				s++;
			}
			else
			{
				m_cTimeCodeDisplay[n].SetChar(' ', false, bForceSend);
			}
		}
	}
}

/////////////////////////////////////////////////////////////////////////////

void CMackieControlMaster::UpdateMasterFader(bool bForceSend)
{
	if (!HaveMixerStrips())
		return;

	if (UsingHUIProtocol())
		return;

	float fVal;

	HRESULT hr = m_SwMasterFader.GetNormalizedVal(&fVal);

	if (FAILED(hr))
		fVal = 0.0f;

	m_HwMasterFader.SetVal(fVal, bForceSend);
}

/////////////////////////////////////////////////////////////////////////////


text:
from django.test import TestCase
from relation.models import Relationship
from account.models import User
from relation.utility import build_model

class TestFamilyBuild(TestCase):

    def setUp(self):
        build_model.build_model()
        pass


text:
from .abstract import ServerElement

class Tournament (ServerElement):
    # CONTINUE FROM HERE
    ...