text:
#ifndef CPP2_PROTOCOL_DEBUGPROTOCOL_H_
#define CPP2_PROTOCOL_DEBUGPROTOCOL_H_

#include <thrift/lib/cpp2/protocol/Protocol.h>
#include <folly/Format.h>
#include <thrift/lib/cpp2/Thrift.h>

namespace apache { namespace thrift {

template <class T>
std::string debugString(const T& obj);

class DebugProtocolWriter {
 public:
  DebugProtocolWriter();

  static inline ProtocolType protocolType() {
    return ProtocolType::T_DEBUG_PROTOCOL;
  }

  void setOutput(folly::IOBufQueue* queue,
                 size_t maxGrowth = std::numeric_limits<size_t>::max());

  uint32_t writeMessageBegin(const std::string& name,
                             MessageType messageType,
                             int32_t seqid);
  uint32_t writeMessageEnd();
  uint32_t writeStructBegin(const char* name);
  uint32_t writeStructEnd();
  uint32_t writeFieldBegin(const char* name, TType fieldType, int16_t fieldId);
  uint32_t writeFieldEnd();
  uint32_t writeFieldStop();
  uint32_t writeMapBegin(TType keyType, TType valType, uint32_t size);
  uint32_t writeMapEnd();
  uint32_t writeListBegin(TType elemType, uint32_t size);
  uint32_t writeListEnd();
  uint32_t writeSetBegin(TType elemType, uint32_t size);
  uint32_t writeSetEnd();
  uint32_t writeBool(bool value);
  uint32_t writeByte(int8_t byte);
  uint32_t writeI16(int16_t i16);
  uint32_t writeI32(int32_t i32);
  uint32_t writeI64(int64_t i64);
  uint32_t writeDouble(double dub);
  uint32_t writeFloat(float flt);
  template <typename StrType>
  uint32_t writeString(const StrType& str) { writeSP(str); return 0; }
  template <typename StrType>
  uint32_t writeBinary(const StrType& str) { writeSP(str); return 0; }
  uint32_t writeBinary(const std::unique_ptr<folly::IOBuf>& str);
  uint32_t writeBinary(const folly::IOBuf& str);
  uint32_t writeSerializedData(const std::unique_ptr<folly::IOBuf>& data) {
    //TODO
    return 0;
  }

 private:
  void indentUp();
  void indentDown();
  void startItem();
  void endItem();

  void writeSP(folly::StringPiece sp);

  void writeRaw(folly::StringPiece sp) {
    out_->append(sp.data(), sp.size());
  }

  template <class... Args>
  void writePlain(Args&&... args) {
    const auto& fmt = folly::format(std::forward<Args>(args)...);
    auto cb = [this] (folly::StringPiece sp) { this->writeRaw(sp); };
    fmt(cb);
  }

  void writeIndent() { writeRaw(indent_); }

  template <class... Args>
  void writeIndented(Args&&... args) {
    writeIndent();
    writePlain(std::forward<Args>(args)...);
  }

  template <class... Args>
  void writeItem(Args&&... args) {
    startItem();
    writePlain(std::forward<Args>(args)...);
    endItem();
  }

  enum ItemType {
    STRUCT,
    SET,
    MAP_KEY,
    MAP_VALUE,
    LIST
  };

  struct WriteState {
    /* implicit */ WriteState(ItemType t) : type(t), index(0) { }

    ItemType type;
    int index;
  };

  void pushState(ItemType t);
  void popState();

  folly::IOBufQueue* out_;
  std::string indent_;
  std::vector<WriteState> writeState_;
};

template <class T>
std::string debugString(const T& obj) {
  folly::IOBufQueue queue;
  DebugProtocolWriter proto;
  proto.setOutput(&queue);
  Cpp2Ops<T>::write(&proto, &obj);
  auto buf = queue.move();
  auto br = buf->coalesce();
  return std::string(reinterpret_cast<const char*>(br.data()), br.size());
}

}}  // namespace thrift

#endif /* CPP2_PROTOCOL_DEBUGPROTOCOL_H_ */


text:
import numpy as np
from numpy.random import uniform

from kheppy.utils.misc import to_str

def _relu(x):
    return np.maximum(x, 0)

def _sigmoid(x):
    return 1 / (1 + np.exp(-x))

def _linear(x):
    return x

class Layer:
    def __init__(self, w_shape, b_shape, activation, activation_name):
        self.W = w_shape
        self.b = b_shape
        self.activation = activation
        self.activation_name = activation_name

class NeuralNet:
    ACTIVATIONS = {
        'relu': _relu,
        'tanh': np.tanh,
        'sigmoid': _sigmoid,
        'linear': _linear,
    }

    def __init__(self, input_len):
        self.layers = []
        self.output_len = input_len

    def add_layer(self, output_len, activation):
        layer = Layer((self.output_len, output_len), (1, output_len), NeuralNet.ACTIVATIONS[activation], activation)
        self.layers.append(layer)
        self.output_len = output_len
        return self

    def predict(self, inputs, weights_by_layer, biases_by_layer):
        inputs = np.asarray([inputs])
        for layer, weights, biases in zip(self.layers, weights_by_layer, biases_by_layer):
            inputs = layer.activation(inputs.dot(weights) + biases)
        return inputs[0]

    def random_matrix(self, func, init_limits):
        weights = []
        for layer in self.layers:
            shape = func(layer)
            inits = uniform(init_limits[0], init_limits[1], shape)
            weights.append(inits)

        return weights

    def random_weights_list(self, init_limits):
        return self.random_matrix(lambda layer: layer.W, init_limits)

    def random_biases_list(self, init_limits):
        return self.random_matrix(lambda layer: layer.b, init_limits)

    def save(self, path, weights, biases):
        with open(path, 'w') as f:
            f.write(str(len(self.layers)) + '\n')
            for layer, w, b in zip(self.layers, weights, biases):
                b = b[0]
                f.write(str(layer.activation_name) + '\n')
                f.write(to_str(w.shape) + '\n')
                for w_row in w:
                    f.write(to_str(w_row) + '\n')
                f.write(to_str(b.shape) + '\n')
                f.write(to_str(b) + '\n')

redpajama_set_name: RedPajamaGithub


text:
package cn.smart.bean;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

/**
 * Created by shu on 2017/3/24.
 *对请求消息的封装
 */

public class Request {
    //请求方法
    private String requestMethod;
    //请求路径
    private String requestPath;

    public Request(String requestMethod, String requestPath) {
        this.requestMethod = requestMethod;
        this.requestPath = requestPath;
    }

    public String getRequestMethod() {
        return requestMethod;
    }

    public void setRequestMethod(String requestMethod) {
        this.requestMethod = requestMethod;
    }

    public String getRequestPath() {
        return requestPath;
    }

    public void setRequestPath(String requestPath) {
        this.requestPath = requestPath;
    }

    @Override
    public boolean equals(Object o) {
        return EqualsBuilder.reflectionEquals(this, o);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }
}


text:
const appState = {
  callback: null,
  setState: function(state) {
    if (typeof this.callback === 'function') {
      this.callback(state);
    }
  }
};

export default appState;


text:
    /**
     * an interceptor for <%= scriptAppName %> module
     *
     */
    $httpProvider.interceptors.push(function($q)
    {
        return {
            'request': function(config)
            {

                return config;
            },
            'requestError': function(rejection)
            {

                return $q.reject(rejection);
            },
            'response': function(response)
            {
                return response;
            },
            'responseError': function(rejection)
            {
                return $q.reject(rejection);
            }
        };
    });


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Goods */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'code')->textInput() ?>

    <?= $form->field($model, 'id_rubric')->textInput() ?>

    <?= $form->field($model, 'ost')->textInput() ?>

    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'package')->textInput() ?>

    <?= $form->field($model, 'volume')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'price')->textInput() ?>

    <?= $form->field($model, 'vkor')->textInput() ?>

    <?= $form->field($model, 'day')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
smscountry gem is useful for sending sms with Ruby on Rails or any Ruby Application.

You need to create an account with the http://www.smscountry.com in order to send sms using this Gem.

## Installation

Add this line to your application's Gemfile:

```
gem 'smscountry'
```

And then execute:

    $ bundle install

Or install it yourself as:

    $ gem install smscountry

## Usage
First create an instance of the Services class using the below code and access the instance methods

	smsobj = Smscountry::Services.new("YourSmsCoountryUserName", "YourSmsCountryPassword", "SenderID") #SenderID is optional.
## To Send SMS:
	smsobj.sendsms("Your Message","Mobile Nums as Comma Separated String", meesage_type="N","Y")
## To Check Your Account Balance
	smsobj.check_account_balance
## To Get SMS Reports
	smsobj.get_bulk_reports(fromdate,todate) #Dates should be in "DD/MM/YYYY". You can access the reports of at max 7 days at once.
## To Schedule SMS
	smsobj.schedule_bulk_message(message,mobile_nums,meesage_type,req_delivery_report,interval,schedulerName,scheduledDateTime,systemcurrenttime)
Example:

	smsobj.schedule_bulk_message("Sample Msg","919848022338",N","Y",0,"Festiva lWishes","DD/MM/YYYY","DD/MM/YYYY HH:MM AM/PM") # Mobile Nums in comma separated string.
## View a Scheduled SMS
	smsobj.view_single_scheduled_sms(reminder_id) # You will get a reminder ID when you schedule an SMS.reminder_id is an Integer.
Example:

	smsobj.view_single_scheduled_sms(123456)

## View All Scheduled SMS
You can view all the Scheduled SMSes.
	smsobj.view_all_scheduled_sms()

## To Delete a Scheduled SMS
	smsobj.delete_scheduled_sms(reminder_id) # You will get a reminder ID when you schedule an SMS.reminder_id is an Integer.
Example:

	smsobj.delete_scheduled_sms(123456)

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/sriram15690/smscountry. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
$(document).ready(function(){

           $('.flexslider').flexslider({
			animation: "slide",
			slideshow: true,
			slideshowSpeed: 7000,
			animationSpeed: 600,
			prevText: 'Prev',
			nextText: 'Next'
			});

		   $(".slides li:not(.clone) a[rel^='prettyPhoto']").prettyPhoto({
						animation_speed: 'normal',
						autoplay_slideshow: true,
						slideshow: 3000
					});

});


text:
import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import com.twilio.sdk.resource.instance.Participant;
import com.twilio.sdk.resource.list.ParticipantList;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

public class Example {

  // Find your Account Sid and Token at twilio.com/user/account
  public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  public static final String AUTH_TOKEN = "your_auth_token";

  public static void main(String[] args) throws TwilioRestException {
    TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);

    // Get an object from its sid. If you do not have a sid,
    // check out the list resource examples on this page
    Participant participant = client.getAccount().getConference("CFbbe4632a3c49700934481addd5ce1659").getParticipant("CA386025c9bf5d6052a1d1ea42b4d16662");
    // Build a filter for the ParticipantList
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("Muted", "True"));
    participant.update(params);

  }
}


text:
<?php
	/**
	 * @package toolkit
	 */
	/**
	 * The DatasourceManager class is responsible for managing all Datasource objects
	 * in Symphony. Datasources's are stored on the file system either in the
	 * `WORKSPACE . /data-sources` folder or provided by an extension in `EXTENSIONS . /./data-sources` folder.
	 * Datasources are run from the Frontend to commonly output Entries and parameters,
	 * however there any different types of Datasource that query external sources for data.
	 * Typically, a Datasource returns XML.
	 */

	require_once(TOOLKIT . '/class.datasource.php');
	require_once(FACE . '/interface.fileresource.php');

	Class DatasourceManager implements FileResource {

		/**
		 * Given the filename of a Datasource, return its handle. This will remove
		 * the Symphony convention of `data.*.php`
		 *
		 * @param string $filename
		 *  The filename of the Datasource
		 * @return string
		 */
		public static function __getHandleFromFilename($filename){
			return preg_replace(array('/^data./i', '/.php$/i'), '', $filename);
		}

		/**
		 * Given a name, returns the full class name of an Datasources. Datasources
		 * use a 'datasource' prefix.
		 *
		 * @param string $handle
		 *  The Datasource handle
		 * @return string
		 */
		public static function __getClassName($handle){
			return 'datasource' . $handle;
		}

		/**
		 * Finds a Datasource by name by searching the data-sources folder in the
		 * workspace and in all installed extension folders and returns the path
		 * to it's folder.
		 *
		 * @param string $handle
		 *  The handle of the Datasource free from any Symphony conventions
		 *  such as `data.*.php`
		 * @return mixed
		 *  If the datasource is found, the function returns the path it's folder, otherwise false.
		 */
		public static function __getClassPath($handle){
			if(is_file(DATASOURCES . "/data.$handle.php")) return DATASOURCES;
			else{
				$extensions = Symphony::ExtensionManager()->listInstalledHandles();

				if(is_array($extensions) && !empty($extensions)){
					foreach($extensions as $e){
						if(is_file(EXTENSIONS . "/$e/data-sources/data.$handle.php")) return EXTENSIONS . "/$e/data-sources";
					}
				}
			}

			return false;
		}

		/**
		 * Given a name, return the path to the Datasource class
		 *
		 * @see DatasourceManager::__getClassPath()
		 * @param string $handle
		 *  The handle of the Datasource free from any Symphony conventions
		 *  such as `data.*.php`
		 * @return string
		 */
		public static function __getDriverPath($handle){
			return self::__getClassPath($handle) . "/data.$handle.php";
		}

		/**
		 * Finds all available Datasources by searching the data-sources folder in
		 * the workspace and in all installed extension folders. Returns an
		 * associative array of data-sources.
		 *
		 * @see toolkit.Manager#about()
		 * @return array
		 *  Associative array of Datasources with the key being the handle of the
		 *  Datasource and the value being the Datasource's `about()` information.
		 */
		public static function listAll(){
			$result = array();
			$structure = General::listStructure(DATASOURCES, '/data.[\\w-]+.php/', false, 'ASC', DATASOURCES);

			if(is_array($structure['filelist']) && !empty($structure['filelist'])){
				foreach($structure['filelist'] as $f){
					$f = self::__getHandleFromFilename($f);

					if($about = self::about($f)){

						$classname = self::__getClassName($f);
						$path = self::__getDriverPath($f);

						$can_parse = false;
						$type = null;

						if(method_exists($classname,'allowEditorToParse')) {
							$can_parse = call_user_func(array($classname, 'allowEditorToParse'));
						}

						if(method_exists($classname,'getSource')) {
							$type = call_user_func(array($classname, 'getSource'));
						}

						$about['can_parse'] = $can_parse;
						$about['source'] = $type;
						$result[$f] = $about;
					}
				}
			}

			$extensions = Symphony::ExtensionManager()->listInstalledHandles();

			if(is_array($extensions) && !empty($extensions)){
				foreach($extensions as $e){
					if(!is_dir(EXTENSIONS . "/$e/data-sources")) continue;

					$tmp = General::listStructure(EXTENSIONS . "/$e/data-sources", '/data.[\\w-]+.php/', false, 'ASC', EXTENSIONS . "/$e/data-sources");

					if(is_array($tmp['filelist']) && !empty($tmp['filelist'])){
						foreach($tmp['filelist'] as $f){
							$f = self::__getHandleFromFilename($f);

							if($about = self::about($f)){
								$about['can_parse'] = false;
								$about['source'] = null;
								$result[$f] = $about;
							}
						}
					}
				}
			}

			ksort($result);
			return $result;
		}

		public static function about($name) {
			$classname = self::__getClassName($name);
			$path = self::__getDriverPath($name);

			if(!@file_exists($path)) return false;

			require_once($path);

			$handle = self::__getHandleFromFilename(basename($path));

			if(is_callable(array($classname, 'about'))){
				$about = call_user_func(array($classname, 'about'));
				return array_merge($about, array('handle' => $handle));
			}
		}

		/**
		 * Creates an instance of a given class and returns it.
		 *
		 * @param string $handle
		 *  The handle of the Datasource to create
		 * @param array $env
		 *  The environment variables from the Frontend class which includes
		 *  any params set by Symphony or Events or by other Datasources
		 * @param boolean $process_params
		 * @return Datasource
		 */
		public static function create($handle, array $env = null, $process_params=true){
			$classname = self::__getClassName($handle);
			$path = self::__getDriverPath($handle);

			if(!is_file($path)){
				throw new Exception(
					__('Could not find Data Source %s.', array('<code>' . $handle . '</code>'))
					. ' ' . __('If it was provided by an Extension, ensure that it is installed, and enabled.')
				);
			}

			if(!class_exists($classname)) require_once($path);

			return new $classname($env, $process_params);
		}

	}


text:
ALTER TABLE allele ADD FOREIGN KEY (subsnp_id) REFERENCES subsnp_handle(subsnp_id);
ALTER TABLE allele ADD FOREIGN KEY (variation_id) REFERENCES variation(variation_id);
ALTER TABLE allele ADD FOREIGN KEY (sample_id) REFERENCES population(sample_id);

ALTER TABLE allele_group ADD FOREIGN KEY (source_id) REFERENCES source(source_id);
ALTER TABLE allele_group ADD FOREIGN KEY (variation_group_id) REFERENCES variation_group(variation_group_id);
ALTER TABLE allele_group ADD FOREIGN KEY (sample_id) REFERENCES population(sample_id);

ALTER TABLE allele_group_allele ADD FOREIGN KEY (variation_id) REFERENCES variation(variation_id);
ALTER TABLE allele_group_allele ADD FOREIGN KEY (allele_group_id) REFERENCES allele_group(allele_group_id);

ALTER TABLE associate_study ADD FOREIGN KEY (study1_id) REFERENCES study(study_id);
ALTER TABLE associate_study ADD FOREIGN KEY (study2_id) REFERENCES study(study_id);

ALTER TABLE attrib ADD FOREIGN KEY (attrib_type_id) REFERENCES attrib_type(attrib_type_id);

ALTER TABLE attrib_set ADD FOREIGN KEY (attrib_id) REFERENCES attrib(attrib_id);

ALTER TABLE compressed_genotype_single_bp ADD FOREIGN KEY (sample_id) REFERENCES individual(sample_id);
ALTER TABLE compressed_genotype_single_bp ADD FOREIGN KEY (seq_region_id) REFERENCES seq_region(seq_region_id);

ALTER TABLE failed_allele ADD FOREIGN KEY (allele_id) REFERENCES allele(allele_id);
ALTER TABLE failed_allele ADD FOREIGN KEY (failed_description_id) REFERENCES failed_description(failed_description_id);

ALTER TABLE failed_variation ADD FOREIGN KEY (variation_id) REFERENCES variation(variation_id);
ALTER TABLE failed_variation ADD FOREIGN KEY (failed_description_id) REFERENCES failed_description(failed_description_id);

ALTER TABLE flanking_sequence ADD FOREIGN KEY (variation_id) REFERENCES variation(variation_id);
ALTER TABLE flanking_sequence ADD FOREIGN KEY (seq_region_id) REFERENCES seq_region(seq_region_id);

ALTER TABLE httag ADD FOREIGN KEY (source_id) REFERENCES source(source_id);
ALTER TABLE httag ADD FOREIGN KEY (variation_group_id) REFERENCES variation_group(variation_group_id);

ALTER TABLE individual ADD FOREIGN KEY (sample_id) REFERENCES sample(sample_id);
ALTER TABLE individual ADD FOREIGN KEY (father_individual_sample_id) REFERENCES individual(sample_id);
ALTER TABLE individual ADD FOREIGN KEY (mother_individual_sample_id) REFERENCES individual(sample_id);
ALTER TABLE individual ADD FOREIGN KEY (individual_type_id) REFERENCES individual_type(individual_type_id);

ALTER TABLE individual_genotype_multiple_bp ADD FOREIGN KEY (subsnp_id) REFERENCES subsnp_handle(subsnp_id);
ALTER TABLE individual_genotype_multiple_bp ADD FOREIGN KEY (variation_id) REFERENCES variation(variation_id);
ALTER TABLE individual_genotype_multiple_bp ADD FOREIGN KEY (sample_id) REFERENCES individual(sample_id);

ALTER TABLE individual_population ADD FOREIGN KEY (individual_sample_id) REFERENCES individual(sample_id);
ALTER TABLE individual_population ADD FOREIGN KEY (population_sample_id) REFERENCES population(sample_id);

ALTER TABLE polyphen_prediction ADD FOREIGN KEY (protein_position_id) REFERENCES protein_position(protein_position_id);

ALTER TABLE population ADD FOREIGN KEY (sample_id) REFERENCES sample(sample_id);

ALTER TABLE population_genotype ADD FOREIGN KEY (subsnp_id) REFERENCES subsnp_handle(subsnp_id);
ALTER TABLE population_genotype ADD FOREIGN KEY (variation_id) REFERENCES variation(variation_id);
ALTER TABLE population_genotype ADD FOREIGN KEY (sample_id) REFERENCES population(sample_id);

ALTER TABLE population_structure ADD FOREIGN KEY (super_population_sample_id) REFERENCES population(sample_id);
ALTER TABLE population_structure ADD FOREIGN KEY (sub_population_sample_id) REFERENCES population(sample_id);

ALTER TABLE protein_position ADD FOREIGN KEY (protein_info_id) REFERENCES protein_info(protein_info_id);

ALTER TABLE read_coverage ADD FOREIGN KEY (sample_id) REFERENCES individual(sample_id);
ALTER TABLE read_coverage ADD FOREIGN KEY (seq_region_id) REFERENCES seq_region(seq_region_id);

ALTER TABLE sample_synonym ADD FOREIGN KEY (source_id) REFERENCES source(source_id);
ALTER TABLE sample_synonym ADD FOREIGN KEY (sample_id) REFERENCES sample(sample_id);

ALTER TABLE sift_prediction ADD FOREIGN KEY (protein_position_id) REFERENCES protein_position(protein_position_id);

ALTER TABLE structural_variation ADD FOREIGN KEY (source_id) REFERENCES source(source_id);
ALTER TABLE structural_variation ADD FOREIGN KEY (seq_region_id) REFERENCES seq_region(seq_region_id);
ALTER TABLE structural_variation ADD FOREIGN KEY (study_id) REFERENCES study(study_id);
ALTER TABLE structural_variation ADD FOREIGN KEY (class_attrib_id) REFERENCES attrib(attrib_id);

ALTER TABLE study ADD FOREIGN KEY (source_id) REFERENCES source(source_id);

ALTER TABLE supporting_structural_variation ADD FOREIGN KEY (structural_variation_id) REFERENCES structural_variation(structural_variation_id);

ALTER TABLE tagged_variation_feature ADD FOREIGN KEY (variation_feature_id) REFERENCES variation_feature(variation_feature_id);
ALTER TABLE tagged_variation_feature ADD FOREIGN KEY (sample_id) REFERENCES sample(sample_id);

ALTER TABLE transcript_variation ADD FOREIGN KEY (variation_feature_id) REFERENCES variation_feature(variation_feature_id);

ALTER TABLE variation ADD FOREIGN KEY (source_id) REFERENCES source(source_id);
ALTER TABLE variation ADD FOREIGN KEY (class_attrib_id) REFERENCES attrib(attrib_id);

ALTER TABLE variation_annotation ADD FOREIGN KEY (study_id) REFERENCES study(study_id);
ALTER TABLE variation_annotation ADD FOREIGN KEY (variation_id) REFERENCES variation(variation_id);
ALTER TABLE variation_annotation ADD FOREIGN KEY (phenotype_id) REFERENCES phenotype(phenotype_id);

ALTER TABLE variation_feature ADD FOREIGN KEY (source_id) REFERENCES source(source_id);
ALTER TABLE variation_feature ADD FOREIGN KEY (variation_id) REFERENCES variation(variation_id);
ALTER TABLE variation_feature ADD FOREIGN KEY (seq_region_id) REFERENCES seq_region(seq_region_id);
ALTER TABLE variation_feature ADD FOREIGN KEY (class_attrib_id) REFERENCES attrib(attrib_id);

ALTER TABLE variation_group ADD FOREIGN KEY (source_id) REFERENCES source(source_id);

ALTER TABLE variation_group_feature ADD FOREIGN KEY (variation_group_id) REFERENCES variation_group(variation_group_id);
ALTER TABLE variation_group_feature ADD FOREIGN KEY (seq_region_id) REFERENCES seq_region(seq_region_id);

ALTER TABLE variation_group_variation ADD FOREIGN KEY (variation_group_id) REFERENCES variation_group(variation_group_id);
ALTER TABLE variation_group_variation ADD FOREIGN KEY (variation_id) REFERENCES variation(variation_id);

ALTER TABLE variation_set ADD FOREIGN KEY (short_name_attrib_id) REFERENCES attrib(attrib_id);

ALTER TABLE variation_set_structure ADD FOREIGN KEY (variation_set_super) REFERENCES variation_set(variation_set_id);
ALTER TABLE variation_set_structure ADD FOREIGN KEY (variation_set_sub) REFERENCES variation_set(variation_set_id);

ALTER TABLE variation_set_variation ADD FOREIGN KEY (variation_id) REFERENCES variation(variation_id);
ALTER TABLE variation_set_variation ADD FOREIGN KEY (variation_set_id) REFERENCES variation_set(variation_set_id);

ALTER TABLE variation_synonym ADD FOREIGN KEY (subsnp_id) REFERENCES subsnp_handle(subsnp_id);
ALTER TABLE variation_synonym ADD FOREIGN KEY (source_id) REFERENCES source(source_id);
ALTER TABLE variation_synonym ADD FOREIGN KEY (variation_id) REFERENCES variation(variation_id);


text:
const fs = require('fs');
const _ = require('lodash');
const shuffleSeed = require('shuffle-seed');

function extractColumns(data, columnNames) {
  const headers = _.first(data);
  const indexes = _.map(columnNames, column => headers.indexOf(column));
  const extracted = _.map(data, row => _.pullAt(row, indexes));
  return extracted;
}

module.exports = function loadCSV(
  filename, {
    converters = {},
    dataColumns = [],
    labelColumns = [],
    shuffle = true,
    splitTest = false
  }
) {
  let data = fs.readFileSync(filename, { encoding: 'utf-8' });
  data = data.split('\n').map(row => row.split(','));
  data = data.map(row => _.dropRightWhile(row, value => value === ''))
  const headers = _.first(data);
  data = data.map((row, index) => {
    if (index === 0) {
      return row;
    }
    return row.map((element, index) => {
      let result;
      if (converters[headers[index]]) {
        result = converters[headers[index]](element);
      } else {
        result = parseFloat(element);
      }
      return _.isNaN(result) ? element : result;
    })
  })

  let labels = extractColumns(data, labelColumns);
  data = extractColumns(data, dataColumns);

  labels.shift();
  data.shift();

  if (shuffle) {
    labels = shuffleSeed.shuffle(labels, 'phrase');
    data = shuffleSeed.shuffle(data, 'phrase');
  }

  if (splitTest) {
    const trainSize = _.isNumber(splitTest) ? splitTest : Math.floor(data.length / 2);
    return {
      features: data.splice(trainSize),
      labels: labels.splice(trainSize),
      testFeatures: data.splice(0, trainSize),
      testLabels: labels.splice(0, trainSize)
    };
  } else {
    return { features: data, labels };
  }
}


text:
namespace GG
{
	//typedef CIwModel Model;
	typedef StaticGeometryBuffer Model;
}


text:
const {describe, it} = global;
import {expect} from 'chai';
import {shallow} from 'enzyme';
import proxyquire from 'proxyquire';
import { spy, stub } from 'sinon';

const Materialize = {
  toast: spy(),
};

const filepicker = {
  setKey: spy(),
  pick: spy(),
}

// Get the component
const { SettingsAvatar } = proxyquire('../settings_avatar', {
  'meteor/poetic:materialize-scss': { Materialize, '@noCallThru': true },
  'filepicker-js': { filepicker, '@noCallThru': true },
});

describe('users.components.settings_avatar', () => {
  it('should do something');
});


text:
package edu.clemson.resolve.semantics.symbol;

import edu.clemson.resolve.proving.absyn.PSelector;
import edu.clemson.resolve.proving.absyn.PSymbol;
import edu.clemson.resolve.semantics.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.antlr.v4.runtime.ParserRuleContext;
import edu.clemson.resolve.semantics.programtype.ProgGenericType;
import edu.clemson.resolve.semantics.programtype.ProgType;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class ProgParameterSymbol extends Symbol {

    public static enum ParameterMode {
        ALTERS {
            @Override
            public ParameterMode[] getValidImplementationModes() {
                return new ParameterMode[]{ALTERS, CLEARS};
            }
        },
        UPDATES {
            @Override
            public ParameterMode[] getValidImplementationModes() {
                return new ParameterMode[]{UPDATES, CLEARS, RESTORES, PRESERVES};
            }
        },
        REPLACES {
            @Override
            public ParameterMode[] getValidImplementationModes() {
                return new ParameterMode[]{REPLACES, CLEARS};
            }
        },
        CLEARS {
            @Override
            public ParameterMode[] getValidImplementationModes() {
                return new ParameterMode[]{CLEARS};
            }
        },
        RESTORES {
            @Override
            public ParameterMode[] getValidImplementationModes() {
                return new ParameterMode[]{RESTORES, PRESERVES};
            }
        },
        PRESERVES {
            @Override
            public ParameterMode[] getValidImplementationModes() {
                return new ParameterMode[]{PRESERVES};
            }
        },
        EVALUATES {
            @Override
            public ParameterMode[] getValidImplementationModes() {
                return new ParameterMode[]{EVALUATES};
            }
        },
        INVALID {
            @Override
            public ParameterMode[] getValidImplementationModes() {
                return new ParameterMode[]{};
            }
        },
        TYPE {
            @Override
            public ParameterMode[] getValidImplementationModes() {
                return new ParameterMode[]{TYPE};
            }
        };

        public boolean canBeImplementedWith(ParameterMode o) {
            return contains(getValidImplementationModes(), o);
        }

        private static boolean contains(Object[] os, Object o) {
            boolean result = false;
            int i = 0;
            int osLength = os.length;
            while (!result && i < osLength) {
                result = os[i].equals(o);
                i++;
            }
            return result;
        }

        public abstract ParameterMode[] getValidImplementationModes();
    }

    public static Map<String, ParameterMode> getModeMapping() {
        Map<String, ParameterMode> result = new HashMap<>();
        ParameterMode[] modes = ParameterMode.values();
        for (ParameterMode mode : modes) {
            result.put(mode.toString().toLowerCase(), mode);
        }
        return Collections.unmodifiableMap(result);
    }

    private final ParameterMode mode;
    private final ProgType declaredType;
    private final DumbMathClssftnHandler typeGraph;

    private MathClssftnWrappingSymbol mathSymbolAlterEgo;
    private final ProgVariableSymbol progVariableAlterEgo;

    @Nullable
    private String typeQualifier;

    public ProgParameterSymbol(@NotNull DumbMathClssftnHandler g, @NotNull String name,
                               @NotNull ParameterMode mode,
                               @NotNull ProgType type,
                               @Nullable ParserRuleContext definingTree,
                               @NotNull ModuleIdentifier moduleIdentifier) {
        super(name, definingTree, moduleIdentifier);
        this.typeGraph = g;
        this.declaredType = type;
        this.mode = mode;

        this.mathSymbolAlterEgo = null;
        if (mode == ParameterMode.TYPE) {
            this.mathSymbolAlterEgo =
                    new MathClssftnWrappingSymbol(g, name, Quantification.NONE, type.toMath(),
                            definingTree, moduleIdentifier);
        }
        else {
            int level = type.toMath().getTypeRefDepth();
            this.mathSymbolAlterEgo =
                    new MathClssftnWrappingSymbol(g, name, Quantification.NONE,
                            new MathNamedClssftn(g, name, level, type.toMath()),
                            definingTree, moduleIdentifier);
        }
        this.progVariableAlterEgo =
                new ProgVariableSymbol(getName(), getDefiningTree(), declaredType, getModuleIdentifier());
    }

    public void setTypeQualifierString(String typeQualifier) {
        this.typeQualifier = typeQualifier;
    }

    @Nullable
    public String getTypeQualifier() {
        return typeQualifier;
    }

    @NotNull
    public ProgType getDeclaredType() {
        return declaredType;
    }

    @NotNull
    public ParameterMode getMode() {
        return mode;
    }

    @NotNull
    @Override
    public MathClssftnWrappingSymbol toMathSymbol() {
        return mathSymbolAlterEgo;
    }

    @NotNull
    @Override
    public ProgVariableSymbol toProgVariableSymbol() {
        return progVariableAlterEgo;
    }

    @NotNull
    @Override
    public ProgParameterSymbol toProgParameterSymbol() {
        return this;
    }

    @NotNull
    @Override
    public ProgTypeSymbol toProgTypeSymbol()
            throws UnexpectedSymbolException {
        ProgTypeSymbol result = null;

        if (!mode.equals(ParameterMode.TYPE)) {
            //This will throw an appropriate error
            result = super.toProgTypeSymbol();
        }
        else {
            result =
                    new ProgTypeSymbol(typeGraph, getName(), new ProgGenericType(
                            typeGraph, getName()),
                            mathSymbolAlterEgo.getClassification(),
                            getDefiningTree(), getModuleIdentifier());
        }
        return result;
    }

    @NotNull
    public PSymbol asPSymbol() {
        return new PSymbol.PSymbolBuilder(getName())
                .progType(declaredType)
                .mathClssfctn(declaredType.toMath()).build();
    }

    @NotNull
    public PSelector asConceptualSymbol() {
        return asConceptualSymbol(false);
    }

    @NotNull
    public PSelector asConceptualSymbol(boolean incoming) {
        return new PSelector(
                new PSymbol.PSymbolBuilder("conc").mathClssfctn(typeGraph.BOOLEAN)
                        .incoming(incoming).build(),
                new PSymbol.PSymbolBuilder(getName())
                        .mathClssfctn(declaredType.toMath()).build());
    }

    @NotNull
    @Override
    public String getSymbolDescription() {
        return "a parameter";
    }

    @NotNull
    @Override
    public Symbol instantiateGenerics(@NotNull Map<String, ProgType> genericInstantiations,
                                      @Nullable FacilitySymbol instantiatingFacility) {
        return new ProgParameterSymbol(typeGraph, getName(), mode,
                declaredType.instantiateGenerics(genericInstantiations,
                        instantiatingFacility), getDefiningTree(), getModuleIdentifier());
    }

    @Override
    public String toString() {
        return "<" + mode.toString().toLowerCase() + ">" + getName();
    }
}


text:
#if WINDOWS_UWP
using Windows.UI.Xaml;
#else
using System.Windows;
#endif

namespace ReactNative.UIManager
{
    interface IPropertySetter
    {
        string Name { get; }

        string PropertyType { get; }

        void UpdateShadowNodeProperty(ReactShadowNode shadowNode, ReactStylesDiffMap value);

        void UpdateViewManagerProperty(IViewManager viewManager, DependencyObject view, ReactStylesDiffMap value);
    }
}


text:
package com.busqueumlugar.dao;

import java.util.Date;
import java.util.List;

import com.busqueumlugar.form.AdministracaoForm;
import com.busqueumlugar.form.ImovelindicadoForm;
import com.busqueumlugar.model.Imovelindicado;

public interface ImovelindicadoDao extends GenericDAO<Imovelindicado, Long> {

	Imovelindicado findImovelindicadoById(Long id);

	List<Imovelindicado> findImoveisPorUsuario(Long idUsuario, ImovelindicadoForm form);

	List<Imovelindicado> findImoveisIndicacoesPorUsuario(Long idUsuario, ImovelindicadoForm form);

	Imovelindicado findImovelIndicadoByIdImovel(Long idImovel);

	Imovelindicado findImovelIndicacaoByIdImovelIdUsuario(Long idImovel, Long idUsuario);

	Imovelindicado findImovelIndicadoByIdImovelIdUsuario(Long idImovel, Long idUsuario);

	List<Imovelindicado> findImoveisIndicadosNovos(Long idUsuario);

	List checarImoveisComMaisIndicacoesPeriodo(Date dataInicio, Date dataFim, int quant);

	List checarImoveisComMaisIndicacoesPeriodo(AdministracaoForm form);

	List<Imovelindicado> filterImoveisIndicacoes(Long idUsuario, ImovelindicadoForm form);

	List<Imovelindicado> filterImoveisIndicados(Long idUsuario, ImovelindicadoForm form);

	List findInfoAgruparUsuariosImoveisIndicacoes(Long idUsuarioIndicacao);

	List findImoveisPorUsuarioDistinct(Long idUsuario, ImovelindicadoForm form);

	List findImoveisIndicacoesPorUsuarioDistinct(Long idUsuario, ImovelindicadoForm form);

	List findImoveisIndicacoesByIdUsuarioDistinct(Long idUsuario, ImovelindicadoForm form);

	long findQuantidadeNovosImoveisIndicacoes(Long idImovel);

	List<Imovelindicado> findImoveisIndicadosByIdImovel(Long idImovel);

	List<Imovelindicado> findImoveisIndicadosParaMimByIdUsuarioSessaoByIdUsuario(Long idUsuarioSessao, Long idUsuario);

	List filtrarAgruparImoveis(Long idUsuario, ImovelindicadoForm form);

	List<Imovelindicado> findImoveisIndicadosByIdImovelPorIdUsuarioIndicador(Long idImovel, Long idUsuarioIndicador);

	List<Imovelindicado> findImoveisNovosPorUsuario(Long idUsuario);

	void updateStatusLeituraByIdUsuarioIndicado(Long idUsuario);

	long findQuantImoveisIndicadosByIdUsuarioByStatusLeitura(Long idUsuario, String statusLeitura);

	long findQuantImoveisIndicacoesByIdUsuarioByStatusLeitura(Long idUsuario, String statusLeitura);

}


text:
module Hammer
  module Widget

    # Abstract class of widgets used to render components
    class Component < Base

      needs :component
      attr_reader :component
      alias_method(:c, :component)

      wrap_in :div

      # automatically passes :component assign to child widgets
      def widget(target, assigns = {}, options = {}, &block)
        assigns.merge!(:component => @component) {|_,old,_| old } if target.is_a? Class
        super target, assigns, options, &block
      end

      def a(*args, &block)
        super *args.push(args.extract_options!.merge(:href => '#')), &block
      end

      # calls missing methods on component
      def method_missing(method, *args, &block)
        if component.respond_to?(method)
          component.__send__ method, *args, &block
        else
          super
        end
      end

      def respond_to?(symbol, include_private = false)
        component.respond_to?(symbol) || super
      end

      # enters scope for callback definition
      # @example onclick on element span executes action block
      #   cb.span('new room').event(:click).action! { a_action }
      def callback
        @callback ||= Callback.new(self)
      end

      alias_method :cb, :callback

      # scope for callback definition
      class Callback
        def initialize(widget)
          @widget, @events = widget, []
        end

        # sores by method element which will be rendered later with callbacks
        # @param args for element
        def method_missing(method, *args, &block)
          raise "invalid state, flush first #{self.inspect}" if @tag
          @tag, @block  = method, block
          @options = args.extract_options!
          @args = args
          self
        end

        # on which event will be callback triggered
        # @param [Symbol] event
        def event(event) # TODO args for events like keypress
          @events << event
          self
        end

        # @yield block action to be executed
        def action(&block)
          raise "invalid state, flush first #{self.inspect}" if @action
          @action = block
          self
        end

        # form callback
        # @param [Object, Fixnum] id a Fixnum or a Object where its #object_id is called to get form's id
        def form(id = @widget.component)
          raise "invalid state, flush first #{self.inspect}" if @form
          id = id.object_id unless id.is_a? Fixnum
          @form = id
          self
        end

        # calls {#action} and {#flush!}
        def action!(&block)
          action(&block)
          flush!
        end

        # calls {#form} and {#flush!}
        def form!(id)
          form(id)
          flush!
        end

        # renders element defined in {#method_missing}, adds callback on {#event}
        def flush!
          hash = {}
          hash[:action] = @widget.__send__ :register_action, &@action if @action
          hash[:form] = @form if @form
          # json = JSON[ hash ]
          json = simple_json(hash)

          @options.merge!( @events.inject({}) {|hash, e| hash[:"data-callback-#{e}"] = json; hash } )
          @widget.__send__ @tag, *@args.push(@options), &@block
          @tag = @action = @form = @block = @options = @args = nil
          @events = []
          nil
        end

        private

        # transforms Hash to JSON
        # @param [Hash] hash one-level hash with primitive types
        def simple_json(hash)
          str = hash.inject('{') {|str, pair| str << pair[0].to_s.inspect << ':' << pair[1].inspect << "," }
          str[-1] = '}'
          str
        end

      end

      private

      # registers action to {#component} for later evaluation
      # @yield action block to register
      # @return [String] uuid of the action
      def register_action(&block)
        component.context.register_action(component, &block)
      end

    end
  end
end


text:
"""
paasta_oom_logger is supposed to be used as a syslog-ng destination.
It looks for OOM events in the log, adds PaaSTA service and instance names
and send JSON-encoded messages the stream 'tmp_paasta_oom_events'.

syslog-ng.conf:

destination paasta_oom_logger {
  program("exec /usr/bin/paasta_oom_logger" template("${UNIXTIME} ${HOST} ${MESSAGE}\n") );
};

filter f_cgroup_oom {
  match(" killed as a result of limit of ") or match(" invoked oom-killer: ");
};

log {
  source(s_all);
  filter(f_cgroup_oom);
  destination(paasta_oom_logger);
};
"""
import re
import sys
from collections import namedtuple

from docker.errors import APIError

from paasta_tools.cli.utils import get_instance_config
from paasta_tools.utils import _log
from paasta_tools.utils import DEFAULT_LOGLEVEL
from paasta_tools.utils import get_docker_client
from paasta_tools.utils import load_system_paasta_config

# Sorry to any non-yelpers but this won't
# do much as our metrics and logging libs
# are not open source
try:
    import yelp_meteorite
except ImportError:
    yelp_meteorite = None

try:
    import clog
except ImportError:
    clog = None

LogLine = namedtuple(
    "LogLine",
    [
        "timestamp",
        "hostname",
        "container_id",
        "cluster",
        "service",
        "instance",
        "process_name",
        "mesos_container_id",
        "mem_limit",
    ],
)

def capture_oom_events_from_stdin():
    process_name_regex = re.compile(
        r"^\d+\s[a-zA-Z0-9\-]+\s.*\]\s(.+)\sinvoked\soom-killer:"
    )
    oom_regex_docker = re.compile(
        r"^(\d+)\s([a-zA-Z0-9\-]+)\s.*Task in /docker/(\w{12})\w+ killed as a"
    )
    oom_regex_kubernetes = re.compile(
        r"""
        ^(\d+)\s # timestamp
        ([a-zA-Z0-9\-]+) # hostname
        \s.*Task\sin\s/kubepods/(?:[a-zA-Z]+/)? # start of message; non capturing, optional group for the qos cgroup
        pod[-\w]+/(\w{12})\w+\s # containerid
        killed\sas\sa*  # eom
        """,
        re.VERBOSE,
    )
    oom_regex_kubernetes_structured = re.compile(
        r"""
        ^(\d+)\s # timestamp
        ([a-zA-Z0-9\-]+) # hostname
        \s.*oom-kill:.*task_memcg=/kubepods/(?:[a-zA-Z]+/)? # start of message; non-capturing, optional group for the qos cgroup
        pod[-\w]+/(\w{12})\w+,.*$ # containerid
        """,
        re.VERBOSE,
    )
    process_name = ""

    while True:
        try:
            syslog = sys.stdin.readline()
        except StopIteration:
            break
        if not syslog:
            break
        r = process_name_regex.search(syslog)
        if r:
            process_name = r.group(1)
        r = oom_regex_docker.search(syslog)
        if r:
            yield (int(r.group(1)), r.group(2), r.group(3), process_name)
            process_name = ""
        r = oom_regex_kubernetes.search(syslog)
        if r:
            yield (int(r.group(1)), r.group(2), r.group(3), process_name)
            process_name = ""
        r = oom_regex_kubernetes_structured.search(syslog)
        if r:
            yield (int(r.group(1)), r.group(2), r.group(3), process_name)
            process_name = ""

def get_container_env_as_dict(docker_inspect):
    env_vars = {}
    config = docker_inspect.get("Config")
    if config is not None:
        env = config.get("Env", [])
        for i in env:
            name, _, value = i.partition("=")
            env_vars[name] = value
    return env_vars

def log_to_clog(log_line):
    """Send the event to 'tmp_paasta_oom_events'."""
    line = (
        '{"timestamp": %d, "hostname": "%s", "container_id": "%s", "cluster": "%s", '
        '"service": "%s", "instance": "%s", "process_name": "%s", '
        '"mesos_container_id": "%s", "mem_limit": "%s"}'
        % (
            log_line.timestamp,
            log_line.hostname,
            log_line.container_id,
            log_line.cluster,
            log_line.service,
            log_line.instance,
            log_line.process_name,
            log_line.mesos_container_id,
            log_line.mem_limit,
        )
    )
    clog.log_line("tmp_paasta_oom_events", line)

def log_to_paasta(log_line):
    """Add the event to the standard PaaSTA logging backend."""
    line = "oom-killer killed {} on {} (container_id: {}).".format(
        "a %s process" % log_line.process_name
        if log_line.process_name
        else "a process",
        log_line.hostname,
        log_line.container_id,
    )
    _log(
        service=log_line.service,
        instance=log_line.instance,
        component="oom",
        cluster=log_line.cluster,
        level=DEFAULT_LOGLEVEL,
        line=line,
    )

def send_sfx_event(service, instance, cluster):
    if yelp_meteorite:
        service_instance_config = get_instance_config(
            service=service, instance=instance, cluster=cluster
        )
        dimensions = {
            "paasta_cluster": cluster,
            "paasta_instance": instance,
            "paasta_service": service,
            "paasta_pool": service_instance_config.get_pool(),
        }
        yelp_meteorite.events.emit_event(
            "paasta.service.oom_events",
            dimensions=dimensions,
        )
        counter = yelp_meteorite.create_counter(
            "paasta.service.oom_count",
            default_dimensions=dimensions,
        )
        counter.count()

def main():
    if clog is None:
        print("CLog logger unavailable, exiting.", file=sys.stderr)
        sys.exit(1)

    clog.config.configure(
        scribe_host="169.254.255.254",
        scribe_port=1463,
        monk_disable=False,
        scribe_disable=False,
    )

    cluster = load_system_paasta_config().get_cluster()
    client = get_docker_client()
    for (
        timestamp,
        hostname,
        container_id,
        process_name,
    ) in capture_oom_events_from_stdin():
        try:
            docker_inspect = client.inspect_container(resource_id=container_id)
        except (APIError):
            continue
        env_vars = get_container_env_as_dict(docker_inspect)
        service = env_vars.get("PAASTA_SERVICE", "unknown")
        instance = env_vars.get("PAASTA_INSTANCE", "unknown")
        mesos_container_id = env_vars.get("MESOS_CONTAINER_NAME", "mesos-null")
        mem_limit = env_vars.get("PAASTA_RESOURCE_MEM", "unknown")
        log_line = LogLine(
            timestamp=timestamp,
            hostname=hostname,
            container_id=container_id,
            cluster=cluster,
            service=service,
            instance=instance,
            process_name=process_name,
            mesos_container_id=mesos_container_id,
            mem_limit=mem_limit,
        )
        log_to_clog(log_line)
        log_to_paasta(log_line)
        send_sfx_event(service, instance, cluster)

if __name__ == "__main__":
    main()


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Job = mongoose.model('Job'),
	_ = require('lodash');

/**
 * Create a Job
 */
exports.create = function(req, res) {
	var job = new Job(req.body);
	job.user = req.user;

	job.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(job);
		}
	});
};

/**
 * Show the current Job
 */
exports.read = function(req, res) {
	var jobArr = [];
	var getParent = function(err, job) {
		jobArr[job.tier] = job;

		if (err || !job.tier) {
			res.jsonp(jobArr);
		} else {
			Job.findById(job.parent._id || job.parent).exec(getParent);
		}
	};

	if (req.query.full) {
		getParent(null, req.job);
	} else {
		res.jsonp([req.job]);
	}
};

/**
 * Update a Job
 */
exports.update = function(req, res) {
	var job = req.job ;

	job = _.extend(job , req.body);

	job.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(job);
		}
	});
};

/**
 * Delete an Job
 */
exports.delete = function(req, res) {
	var job = req.job ;

	job.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(job);
		}
	});
};

/**
 * List of Jobs
 */
exports.list = function(req, res) {
	Job.find()
		.sort('name')
		.populate('parent', 'name tier')
		.exec(function(err, jobs) {
			if (err) {
				return res.status(400).send({
					message: errorHandler.getErrorMessage(err)
				});
			} else {
				res.jsonp(jobs);
			}
		});
};

/**
 * Job middleware
 */
exports.jobByID = function(req, res, next, id) {
	Job.findById(id)
		.populate('parent', 'name tier')
		.exec(function(err, job) {
			if (err) return next(err);
			if (! job) return next(new Error('Failed to load Job ' + id));
			req.job = job ;
			next();
		});
};

/**
 * Job authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (_.indexOf(req.user.roles, 'admin') === -1) {
		return res.status(403).send('User is not authorized');
	}
	next();
};


text:
from io import StringIO

from django.test import TestCase
from django.db import models
from django.core.management import CommandError, call_command

class DescribeFormExceptionsTests(TestCase):
    """Tests for describe_form command exceptions."""

    def test_should_raise_CommandError_if_invalid_arg(self):
        with self.assertRaisesRegex(CommandError, "Need application and model name in the form: appname.model"):
            call_command('describe_form', 'testapp')

class DescribeFormTests(TestCase):
    """Tests for describe_form command."""

    def setUp(self):
        self.out = StringIO()

        class BaseModel(models.Model):
            title = models.CharField(max_length=50)
            body = models.TextField()

            class Meta:
                app_label = 'testapp'

        class NonEditableModel(models.Model):
            created_at = models.DateTimeField(auto_now_add=True)
            title = models.CharField(max_length=50)

            class Meta:
                app_label = 'testapp'

    def test_should_print_form_definition_for_TestModel(self):
        expected_result = '''from django import forms
from testapp.models import BaseModel

class BaseModelForm(forms.Form):
    title = forms.CharField(label='Title', max_length=50)
    body = forms.CharField(label='Body')'''

        call_command('describe_form', 'testapp.BaseModel', stdout=self.out)

        self.assertIn(expected_result, self.out.getvalue())

    def test_should_print_form_definition_for_TestModel_with_non_editable_field(self):
        expected_result = '''from django import forms
from testapp.models import NonEditableModel

class NonEditableModelForm(forms.Form):
    title = forms.CharField(label='Title', max_length=50)'''

        call_command('describe_form', 'testapp.NonEditableModel', stdout=self.out)

        self.assertIn(expected_result, self.out.getvalue())

    def test_should_print_form_with_fields_for_TestModel(self):
        not_expected = '''body = forms.CharField(label='Body')'''

        call_command('describe_form', 'testapp.BaseModel', '--fields=title', stdout=self.out)

        self.assertNotIn(not_expected, self.out.getvalue())


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
    <entity repository-class="FDevs\CRUDBundle\Entity\BookRepository" name="FDevs\CRUDBundle\Entity\Book">
        <id name="id" type="integer" column="id">
            <generator strategy="AUTO"/>
        </id>
        <field name="title" type="string" column="title" length="255"/>
        <field name="description" type="text" column="description"/>
        <field name="publicationDate" type="date" column="publicationDate"/>
        <many-to-one field="publisher" target-entity="FDevs\CRUDBundle\Entity\Publisher"/>
        <many-to-many target-entity="FDevs\CRUDBundle\Entity\Author" field="authors"/>
    </entity>
</doctrine-mapping>


text:
//=========================================================
// Generic Monster - purely for scripted sequence work.
//=========================================================
#include	"extdll.h"
#include	"util.h"
#include	"cbase.h"
#include	"monsters.h"
#include	"schedule.h"

// For holograms, make them not solid so the player can walk through them
#define	SF_GENERICMONSTER_NOTSOLID					4

//=========================================================
// Monster's Anim Events Go Here
//=========================================================

class CGenericMonster : public CBaseMonster
{
public:
	void Spawn( void );
	void Precache( void );
	void SetYawSpeed( void );
	int  Classify ( void );
	void HandleAnimEvent( MonsterEvent_t *pEvent );
	int ISoundMask ( void );
};
LINK_ENTITY_TO_CLASS( monster_generic, CGenericMonster );

//=========================================================
// Classify - indicates this monster's place in the
// relationship table.
//=========================================================
int	CGenericMonster :: Classify ( void )
{
	return	CLASS_PLAYER_ALLY;
}

//=========================================================
// SetYawSpeed - allows each sequence to have a different
// turn rate associated with it.
//=========================================================
void CGenericMonster :: SetYawSpeed ( void )
{
	int ys;

	switch ( m_Activity )
	{
	case ACT_IDLE:
	default:
		ys = 90;
	}

	pev->yaw_speed = ys;
}

//=========================================================
// HandleAnimEvent - catches the monster-specific messages
// that occur when tagged animation frames are played.
//=========================================================
void CGenericMonster :: HandleAnimEvent( MonsterEvent_t *pEvent )
{
	switch( pEvent->event )
	{
	case 0:
	default:
		CBaseMonster::HandleAnimEvent( pEvent );
		break;
	}
}

//=========================================================
// ISoundMask - generic monster can't hear.
//=========================================================
int CGenericMonster :: ISoundMask ( void )
{
	return	NULL;
}

//=========================================================
// Spawn
//=========================================================
void CGenericMonster :: Spawn()
{
	Precache();

	SET_MODEL( ENT(pev), STRING(pev->model) );

/*
	if ( FStrEq( STRING(pev->model), "models/player.mdl" ) )
		UTIL_SetSize(pev, VEC_HUMAN_HULL_MIN, VEC_HUMAN_HULL_MAX);
	else
		UTIL_SetSize(pev, VEC_HULL_MIN, VEC_HULL_MAX);
*/

	if ( FStrEq( STRING(pev->model), "models/player.mdl" ) || FStrEq( STRING(pev->model), "models/holo.mdl" ) )
		UTIL_SetSize(pev, VEC_HULL_MIN, VEC_HULL_MAX);
	else
		UTIL_SetSize(pev, VEC_HUMAN_HULL_MIN, VEC_HUMAN_HULL_MAX);

	pev->solid			= SOLID_SLIDEBOX;
	pev->movetype		= MOVETYPE_STEP;
	m_bloodColor		= BLOOD_COLOR_RED;
	pev->health			= 8;
	m_flFieldOfView		= 0.5;// indicates the width of this monster's forward view cone ( as a dotproduct result )
	m_MonsterState		= MONSTERSTATE_NONE;

	MonsterInit();

	if ( pev->spawnflags & SF_GENERICMONSTER_NOTSOLID )
	{
		pev->solid = SOLID_NOT;
		pev->takedamage = DAMAGE_NO;
	}
}

//=========================================================
// Precache - precaches all resources this monster needs
//=========================================================
void CGenericMonster :: Precache()
{
	PRECACHE_MODEL( (char *)STRING(pev->model) );
}

//=========================================================
// AI Schedules Specific to this monster
//=========================================================


text:
package org.knowm.xchange.kuna;

import org.junit.BeforeClass;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;

/** @author Dat Bui */
public class BaseKunaTest {

  private static Exchange exchange;

  @BeforeClass
  public static void beforeClass() {
    exchange = ExchangeFactory.INSTANCE.createExchange(KunaExchange.class.getName());
  }

  protected static Exchange getExchange() {
    return exchange;
  }
}


text:
module Operationcode
  module Slack
    class User
      attr_reader :id, :name

      def initialize(data)
        # If we get a string should we go look the users info up?
        if data.is_a? String
          @id = data
          populate_name!
        else
          @id = data['id']
          @name = data['name']
        end
      end

      def populate_name!
        res = Operationcode::Slack::Api::UsersInfo.post(with_data: { user: @id })
        @name = res['user']['real_name'] if res['user']
      end
    end
  end
end


text:
typedef struct {
  int err;
  size_t ret;
  long offs;
  int eof;
  int ferr;
} freadShmData_t;

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) {
  // Get libc syscall function pointer & offset in image
  libc_func(fread, size_t, void *, size_t, size_t, FILE *);

  if (plr_checkInsidePLR()) {
    // If already inside PLR code, just call original syscall & return
    return _fread(ptr, size, nmemb, stream);
  } else {
    plr_setInsidePLR();
    int fn = fileno(stream);
    plrlog(LOG_SYSCALL, "[%d:fread] Read %ld %ld-byte elems from fileno %d\n", getpid(), nmemb, size, fn);

    syscallArgs_t args = {
      .addr = _off_fread,
      .arg[0] = fn,
      .arg[1] = size,
      .arg[2] = nmemb,
    };
    plr_checkSyscallArgs(&args);

    // Nested function actually performed by master process only
    size_t ret;
    freadShmData_t shmDat;
    int masterAct() {
      // Call original libc function
      ret = _fread(ptr, size, nmemb, stream);

      // Use ftell to get new file offset
      shmDat.err = errno;
      shmDat.ret = ret;
      shmDat.offs = ftell(stream);
      shmDat.eof = feof(stream);
      shmDat.ferr = ferror(stream);

      // Store return value & returned data in shared memory for slave processes
      plr_copyToShm(&shmDat, sizeof(shmDat), 0);
      plr_copyToShm(ptr, ret, sizeof(shmDat));

      if (shmDat.ferr) {
        // Not sure how to handle passing ferror's to slaves yet, no way
        // to manually set error state
        plrlog(LOG_ERROR, "[%d:fread] ferror (%d) occurred (%d)\n", getpid(), shmDat.ferr, fn);
        exit(1);
      }

      return 0;
    }
    // All processes call plr_masterAction() to synchronize at this point
    plr_masterAction(masterAct);

    if (!plr_isMasterProcess()) {
      // Slaves copy return values from shared memory
      plr_copyFromShm(&shmDat, sizeof(shmDat), 0);
      if (shmDat.ret > 0) {
        plr_copyFromShm(ptr, shmDat.ret, sizeof(shmDat));
      }

      // Slaves seek to new fd offset
      // Can't use SEEK_CUR and advance by ret because the slave processes
      // may have been forked from each other after the fd was opened, in which
      // case the fd & its offset are shared, and that would advance more than needed
      fseek(stream, shmDat.offs, SEEK_SET);

      // Necessary to manually reset EOF flag because fseek clears it
      if (shmDat.eof) {
        // fgetc at EOF to set feof indicator
        int c;
        if ((c = fgetc(stream)) != EOF) {
          const char *fmt = "[%d:fread] ERROR: fgetc to cause EOF actually got data (%c %d), ftell = %d, feof = %d\n";
          plrlog(LOG_ERROR, fmt, getpid(), c, c, ftell(stream), feof(stream));
          exit(1);
        }
      }
      if (shmDat.ferr) {
        plrlog(LOG_ERROR, "[%d:fread] ERROR: ferror (%d) from master (%d)\n", getpid(), shmDat.ferr, fn);
        exit(1);
      }
    }

    // TEMPORARY
    // Slave processes sometimes end up with the wrong file offset, even after SEEK_SET
    // Compare file state at exit to make sure everything is consistent
    // Piggybacking off checkSyscallArgs mechanism to do this
    syscallArgs_t exitState = {
      .arg[0] = ftell(stream),
      .arg[1] = feof(stream),
      .arg[2] = ferror(stream),
    };
    plr_checkSyscallArgs(&exitState);

    // All procs return same value & errno
    ret = shmDat.ret;
    errno = shmDat.err;

    plr_clearInsidePLR();
    return ret;
  }
}


text:
* HTML documents
  * HTML was created to share research documents
  * doctype declares which version of HTML standard you are using
  * leave out doctype and the browser has to guess
  * html
    * head
      * title
    * body
* The head element
  * metadata, not usually shown to the user
  * except for the title
  * meta includes metadata such as keywords, description, author
  * meta can also emulate http headers with 'http-equiv'
  * script
  * style inline styles
  * link directive indicating related documents, often linking in stylesheets
  * base base address for all relative links, not specified the browser will make assumptions
* The body element
  * bulk of the content
  * headings
  * text
  * lists
  * links
  * tables
  * images/objects
* Using id and class attributes
  * id is unique, class can be applied to a lot of elements

#### HTML Text
 * Headings
   * H1 -> primary heading of document, H2-H6 sub- headings
 * Block vs. Inline Elements
  * block elements
    * container elements for grouping
    * may contain other block elements and line elements
  * inline elements
    * container for text and other inline elements
    * a span can't contain a div
 * Whitespace
   * whitespace generally ignored in block and inline
   * pre - whitespace is respected
   * br explicit line break
   * hr horizontal rule
   * character entities, nbsp indicates a space which cannot be used for line breaks. lt, gt for angle brackets
 * Additional Text Elements
  * sup and sub, superscript and subscript
  * cite, cite work by another
  * abbr and acronym, abbreviation or acronym
  * em, strong, typically you use styles for this
  * code, samp -> code block or program output
  * kbd, var -> keyboard input and code variables
  * blockquote, q --> block level or inline quotes

#### HTML Lists

* List Types
  * li = list item
  * unordered, ul + li -> bullets
  * ordered, ol + li -> numeric or alpha labels
  * definition list. dl, dt: definition term, dd: definition definition -> term + definition
  * sublists by nesting a ul or ol inside an li

#### HTML Links
* Link Concepts
  * anchors (a tags) act as either source or target for linking
  * named anchors are targets
  * anchors with href attributes are sources
  * absolute provides the entire URI
  * relative is relative to the current document -> base element to change what it is relative to
* Understanding Targets
  * links can target anchors, within the same document or in a separate document
  * we use the # symbol to specify an anchor or the id of an element to link to
* Additional link attributes
  * language, relationship, content type, access key
  * not often used because they are dependent on the thing you are linking to which can change

#### HTML Tables
* Table Elements
  * table, can have a summary attribute
    * caption
    * thead -> headers for columns, single row tr, th, th, tr
    * tfoot -> summary etc., footer comes before tbody so they can render before reading all the data
    * tbody -> multiple rows presenting data
* Table Data
  * tr represents a row
    * used in header, body and footer
    * th table header data insied tr inside thead
    * td tabe data
* Spanning Columns and Rows
  * colspan/ rowspan
  * attributes used on td (cell) to flow across rows or columns
* Formatting Tables
  * not tables for formatting, use divs or block elements + stylesheets for that
  * control width, border, cell padding (space around content inside cell), cell spacing (space between cells)

#### HTML Images and Objects
* Image and Object Concepts
 * img tag and reference an image file
  * be aware of file size, leave an alt-text
 * objects for plug-ins, flash, applets, videos, silverlight etc
 * optimise images for the web, don't post size
 * the object tag, data attribute and type attribute tell the browser what this is
  * the param element name and value attributes give the path to the source of the application


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link href="estilo.css" rel="stylesheet" type="text/css">
<title>Henrique Cursos</title>

        <? include_once "inc_topo.php"; ?>

        <? include_once "example.php"; ?>

                 VENTOSATERAPIA

    PROGRAMA DO CURSO

PROGRAMA

        Curso: Ventosaterapia

        Carga  Horária: 14h

        Ementa: Os estudos dos princípios da medicina chinesa aliada a terapia de  Sucção facilitando a eliminação de energia estagnada do canal ou meridiano, com  ação direta sobre as vísceras e suas funções.

        Objetivo:

- Fornecer ao profissional atuante na área da saúde conhecimentos  práticos, seja no campo patológico, funcional ou estético do seu paciente  aliado ao manuseio das ventosas.

Conteúdo Programático:

Unidade  I - História da Ventosaterapia

Unidade  II - Noções básicas das Teorias da Medicina Tradicional Chinesa, TAO, Yin/Yang,  5 Elementos e Meridianos

Unidade  III - Benefícios da Ventosaterapia

Unidade  IV -Terapias que beneficiam a técnica da ventosa

Unidade  V - Indicações

Unidade  VI - Contra-indicações

Unidade  VII - Procedimentos para aplicação das ventosas

Unidade  VIII -Tipos de métodos de aplicação das ventosas

Unidade  IX - Tratamento de doenças mais comuns

Unidade  X - Ventosas aplicadas à Estética

Unidade  XI - Prática.

Referências Bibliográficas:

Acupuntura Médica : Um enfoque científico do ponto de vista       ocidental / Editado por Jacqueline Filshie, Adrian White; São Paulo :       Roca. 2002

Beau, Georges. A Medicina Chinesa. RJ, Ed. Interciencia 1982

Carneiro, Norton Moritz - Fundamentos da Acupuntura Médica.       Florianópolis : Editora Sistema, 2001.

Eliade Mircea História das crenças e idéias religiosas Tomo II Vol       I RJ, Ed Zahar

Liu Gong Wang: Tratado Contemporâneo de Acupuntura e moxibustão;       Ceimec

Gernet, J. O Mundo chinês, Pt, Lisboa – Br, RJ, Ed. Cosmo, 1975

	  				  <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="562" height="63">
                          <param name="movie" value="banners_horizontal_botao_baixo.swf" />
                          <param name="quality" value="high" />
                      	  <param name="wmode" value="transparent" />
                          <embed src="banners_horizontal_botao_baixo.swf" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="562" height="63"></embed>
  				      </object>


text:
robotgame
=========

Learning git and a bit of python at the same time


text:
import random
import math
import sys

def count(T, fname, label):
    with open(fname) as F:
        for line in F:
            for feat in line.strip().split():
                if feat not in T:
                    T[feat] = {0:0, 1:0}
                T[feat][label] += 1
    pass

def get_vects(fname, label):
    L = []
    with open(fname) as test_file:
        for line in test_file:
            L.append((label, line.strip().split()))
    return L

def predict(T, x, pos_total, neg_total):
    pos_likelihood = neg_likelihood = 0
    for feat in x:
        print feat
        pos_likelihood += math.log(T[feat][1])
        neg_likelihood += math.log(T[feat][0])
    return 1 if pos_likelihood > neg_likelihood else 0

def naive_bayes():
    T = {}
    count(T, "train.positive", 1)
    count(T, "train.negative", 0)
    pos_total = neg_total = 0
    for feat in T:
        pos_total += T[feat][1]
        neg_total += T[feat][0]
    vocab_size = len(T)
    corrects = 0
    test_data = get_vects("test.positive", 1)
    test_data.extend(get_vects("test.negative", 0))
    random.shuffle(test_data)
    for (t, x) in test_data:
        if t == predict(x, T, pos_total, neg_total):
            corrects += 1
    print "Accuracy =", float(corrects) / float(len(test_data))
    pass

if __name__ == "__main__":
    naive_bayes()


text:
"""
Implements the anti-entropy and eventual consistency policies on a replica.
[Eventual consistency][ec] requires two things:

1. method of exchanging data (anti-entropy)
2. method of reconcilliation

Anti Entropy
============

Writes are gossiped to and from causal/eventual devices for [anti-entropy][gossip]
    - pushed via [rumor-mongering][gp]
    - pulled via periodic gossip
    - random targets in both cases

Writes are always pushed in in-order.
    - first find out what target has (remote read)
    - then push everything the source has at the target (remote write).
    - only new versions are pushed (some devices might not get old versions).

Reconcilliation
===============

Last writer wins. Reconcillation is scheduled via asynchronous repair, e.g.
not part of a read/write operation, and is therefore part of the anti-entropy
mechanism rather than any remote reads/writes.

[ec]: https://en.wikipedia.org/wiki/Eventual_consistency
[gossip]: https://en.wikipedia.org/wiki/Gossip_protocol
[gp]: http://www.inf.u-szeged.hu/~jelasity/ddm/gossip.pdf
"""

##########################################################################
## Imports
##########################################################################

import random

from .base import Replica
from .store import namespace
from .store import MultiObjectWriteLog

from cloudscope.config import settings
from cloudscope.simulation.timer import Timer
from cloudscope.exceptions import AccessError

from collections import defaultdict
from collections import namedtuple

##########################################################################
## Module Constants
##########################################################################

## Fetch simulation settings from defaults
AE_DELAY    = settings.simulation.anti_entropy_delay
NEIGHBORS   = settings.simulation.num_neighbors

# Deprecated
DO_GOSSIP   = settings.simulation.do_gossip
DO_RUMORING = settings.simulation.do_rumoring

## RPC Message Definition
Gossip   = namedtuple('Gossip', 'entries, length')
GossipResponse = namedtuple('GossipResponse', 'entries, length, success')
Rumor    = namedtuple('Rumor', 'access')
RumorResponse  = namedtuple('RumorResponse', 'access, success')

##########################################################################
## Eventual Replica
##########################################################################

class EventualReplica(Replica):

    def __init__(self, simulation, **kwargs):
        super(EventualReplica, self).__init__(simulation, **kwargs)

        # Eventually consistent settings
        self.ae_delay    = kwargs.get('anti_entropy_delay', AE_DELAY)
        self.n_neighbors = kwargs.get('num_neighbors', NEIGHBORS)

        # Deprecated
        self.do_gossip   = kwargs.get('do_gossip', DO_GOSSIP)
        self.do_rumoring = kwargs.get('do_rumoring', DO_RUMORING)

        self.log         = MultiObjectWriteLog() # the write log of the replica
        self.timeout     = None                  # anti entropy timer

    ######################################################################
    ## Properties
    ######################################################################

    ######################################################################
    ## Core Methods (Replica API)
    ######################################################################

    def read(self, name, **kwargs):
        """
        Eventually consistent replicas simply return the latest version for
        the name that they have in their store. This easily could be stale or
        forked depending on writes elsewhere in the cluster.
        """
        # Create the read event using super.
        access  = super(EventualReplica, self).read(name, **kwargs)

        # Record the number of attempts for the access
        if access.is_local_to(self): access.attempts += 1

        # Fetch the latest version from the log
        version = self.log.get_latest_version(access.name)

        # If version is None then we haven't read anything; bail!
        if version is None: return access.drop(empty=True)

        # Eventual nodes read locally and immediately, so complete the read.
        access.update(version, completed=True)

        # Log the access from this particular replica.
        access.log(self)

        return access

    def write(self, name, **kwargs):
        """
        Performs a write to the object with the given name by first creating
        the access event using super. Note that other access events can be
        passed into the write method in the case of remote writes.

        The access will define if the write is local or not.
        If local: write to the latest local version and complete.
        If remote: append write to log if latest version of object else error.

        After local vs. remote do the following:

        1. append the write to the log as (version, id)
        2. cache the latest access for gossip or rumoring
        3. update the version for visibility latency
        4. call the rumor handler

        Note this method can raise an error if not writing the latest version.
        """
        # Create the write event using super.
        access  = super(EventualReplica, self).write(name, **kwargs)

        # Determine if the write is local or remote
        if access.is_local_to(self):
            # Record the number of attempts for the access
            access.attempts += 1

            # Fetch the latest version from the log
            latest  = self.log.get_latest_version(access.name)

            # Perform the write
            if latest is None:
                version = namespace(access.name)(self)
            else:
                version = latest.nextv(self)

            # Update the access with the latest version and complete
            access.update(version, completed=True)

        else:

            # If there is no version, raise an exception
            if access.version is None:
                raise AccessError(
                    "Attempting a remote write on {} without a version!".format(self)
                )

            # Save the version variable for use below
            version = access.version
            current = self.log.get_latest_version(access.name)

            # Ensure that the version is the latest.
            if current is not None and version <= current:
                raise AccessError(
                    "Attempting unordered write of {} after write of {}".format(version, current)
                )

        # At this point we've dealt with local vs. remote
        # Append the latest version to the local data store
        self.log.append(version, 0)

        # Handle the access according to eventual rules
        version.update(self) # Update the version to track visibility latency
        access.log(self)     # Log the access from this particular replica.
        self.rumor(access)   # Rumor the access on demand

        # Return the access for subclass access.
        return access

    def run(self):
        """
        The run method basically implements an anti-entropy timer.
        """
        while True:
            yield self.get_anti_entropy_timeout()

    ######################################################################
    ## Helper Methods
    ######################################################################

    def gossip(self):
        """
        Pairwise gossip protocol by randomly selecting a neighbor and
        exchanging information about the state of the latest objects in the
        cache since the last anti-entropy delay.

        TODO: how to gossip to strong consistency nodes?
        """
        # If gossiping is not allowed, forget about it.
        if not self.do_gossip:
            return

        # Perform pairwise anti-entropy sessions with n_neighbors
        for target in self.get_anti_entropy_neighbors():
            # Send the latest version of ALL objects.
            entries = [
                self.log.get_latest_version(name).access
                for name in self.log.namespace
            ]
            gossip  = Gossip(tuple(entries), len(entries))
            self.send(target, gossip)

    def rumor(self, access):
        """
        Performs on access rumor mongering
        """
        # if rumoring is not allowed, forget about it.
        if not self.do_rumoring:
            return

        # Send the access to n other neighbors (excluding the origin)
        for target in self.get_anti_entropy_neighbors():
            rumor = Rumor(access)
            self.send(target, rumor)

    def get_anti_entropy_timeout(self):
        """
        Creates the anti-entropy timeout.
        In the future this could be random timeout not fixed.
        """
        self.timeout = Timer(self.env, self.ae_delay, self.gossip)
        return self.timeout.start()

    def select_anti_entropy_neighbor(self):
        """
        Implements the anti-entropy neighbor selection policy. By default this
        is simply uniform random selection of all the eventual neighbors.
        """
        return random.choice(self.neighbors(self.consistency))

    def get_anti_entropy_neighbors(self):
        """
        Selects the neighbors to perform anti-entropy with.
        """
        for _ in xrange(self.n_neighbors):
            yield self.select_anti_entropy_neighbor()

    def update_forte_children(self, current, remote):
        """
        This unfortunately named method is a recursive function that updates
        all the children of the remote version with the new forte number and
        returns the newly correct current version.

        The idea here is that if the current version has a lower forte number
        then we should update the children of the remote (higher forte) in
        order to make sure that the latest branch is current.

        This method provides backpressure from Raft to Eventual.
        """

        def update_forte(forte, version, current):
            """
            Recursive update the forte number for a particular version.
            """
            # Update all the version's children with its forte number.
            for child in version.children:
                # Only update children that are in the current log.
                if child in self.log:
                    # Update child forte to parent and detect current
                    child.forte = forte
                    if child > current: current = child

                # Recurse on grandchildren
                current = update_forte(forte, child, current)

            # Return the maximal version (using forte numbers) discovered.
            return current

        # This function only needs be called if we're in federated versioning.
        if settings.simulation.versioning != "federated":
            return current

        # If the current is greater than the remote, return it.
        if current is None or current >= remote: return current

        # Check the forte number on the remote and update the children.
        if remote.forte > current.forte:
            strong = update_forte(remote.forte, remote, current)
            if strong > current:
                # Put the strong version at the end of the log and return it
                # as the new current version (or latest for this object)
                if strong in self.log:
                    self.log.remove(strong)
                    self.log.append(strong, strong.forte)
                    return strong
                else:
                    # This really shouldn't happen?!
                    self.sim.logger.warning(
                        "Attempting to move {} to end when not in log!"
                    )

        # Last resort, return the current version.
        return current

    ######################################################################
    ## Event Handlers
    ######################################################################

    def on_gossip_rpc(self, message):
        """
        Handles the receipt of a gossip from another node. Expects multiple
        accesses (Write events) as entries. Goes through all and compares the
        versions, replying False only if there is an error or a conflict.
        """
        entries = message.value.entries
        updates = []

        # Go through the entries from the RPC and update log
        for access in entries:
            # Get the latest version from the log then update with forte
            current = self.log.get_latest_version(access.name)
            current = self.update_forte_children(current, access.version)

            # If the access is greater than our current version, write it!
            if current is None or access.version > current:
                self.write(access)

            # Is the the remote behind us? If so, send the latest version!
            elif access.version < current:
                updates.append(current.access)

            else:
                # Presumably the version are equal, so do nothing.
                continue

        # Success here just means whether or not we're responding with updates
        success = True if updates else False

        # Respond to the sender with the latest versions from our log
        self.send(message.source, GossipResponse(updates, len(updates), success))

    def on_gossip_response_rpc(self, message):
        """
        Handles the response to pairwise gossiping, updating entries from the
        responder's cache to the local log and latest version cache.
        """
        entries = message.value.entries

        for access in entries:
            current = self.log.get_latest_version(access.name)
            current = self.update_forte_children(current, access.version)

            # This is a new version or a later version than our current.
            if current is None or access.version > current:
                self.write(access)

    def on_rumor_rpc(self, message):
        """
        Handles the rumor message from the originator of the rumor.
        """
        access  = message.value.access
        current = self.log.get_latest_version(access.name)
        current = self.update_forte_children(current, access.version)

        # Is the rumored version later than our current?
        if current is None or access.version > current:
            # Write the access which will rumor it out again
            self.write(access)

            # Respond True to the origin of the rumor
            response = RumorResponse(None, True)

        elif access.version < current:
            # Respond False to the origin with the later version
            response = RumorResponse(current.access, False)

        else:
            # Simply acknowledge receipt
            response = RumorResponse(None, True)

        # Send the response back to the source
        self.send(message.source, response)

    def on_rumor_response_rpc(self, message):
        """
        Handles the rumor acknowledgment
        """
        response = message.value
        if not response.success:
            # This means that a later value has come in!
            current = self.log.get_latest_version(response.access.name)
            current = self.update_forte_children(current, access.version)

            # If their response is later than our version, write it.
            if current is None or response.access.version > current:
                self.write(response.access)


text:
<?php
//$mysqli = mysqli_connect("localhost", "aldeiacr_dev", "voanubo2016", "aldeiacr_dev");
$mysqli = mysqli_connect("localhost", "root", "root", "aldeia_crystal");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
?>


text:
Namespace IBM

	''' Enum Representing IBM Blower State
	''' <autogenerated>Generated from a T4 template. Modifications will be lost, if applicable use a partial class instead.</autogenerated>
	''' <generator-date>08/02/2014 18:20:28</generator-date>
	''' <generator-functions>1</generator-functions>
	''' <generator-source>Caerus\_IBM\Enums\BlowerState.tt</generator-source>
	''' <generator-version>1</generator-version>
	<System.CodeDom.Compiler.GeneratedCode("Caerus\_IBM\Enums\BlowerState.tt", "1")> _
	Public Enum BlowerState As System.Int32

		''' Status is Unknown
		Unknown = 0

		''' Status is Good
		Good = 1

		''' Status is Warning
		Warning = 2

		''' Status is Bad
		Bad = 3

	End Enum

End Namespace


text:
<?php

namespace Components\Categories\Admin;

use Request;

// Access check.
if (!\User::authorise('core.manage', Request::getCmd('extension')))
{
	return \App::abort(404, \Lang::txt('JERROR_ALERTNOAUTHOR'));
}

// Load needed files
require_once dirname(__DIR__) . '/models/category.php';
require_once __DIR__ . '/helpers/categories.php';

// Determine task
$task = Request::getCmd('task');
if (strpos($task, '.') !== false)
{
	$splitTask = explode('.', $task);
	Request::setVar('task', $splitTask[1]);
}

// Get the controller
$defaultController = 'categories';
$controllerName = Request::getCmd('controller', $defaultController);
if (!file_exists(__DIR__ . '/controllers/' . $controllerName . '.php'))
{
	$controllerName = $defaultController;
}
require_once __DIR__ . '/controllers/' . $controllerName . '.php';
$controllerName = __NAMESPACE__ . '\\Controllers\\' . ucfirst(strtolower($controllerName));

// Execute
$controller = new $controllerName();
$controller->execute();


text:
"""
Django settings for allauthdemo project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '!h8#n5wopc#7zq!_)i=l#t=q)7g0g-+&0!=kxv+*&2b7*xb8bm'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'bootstrap3', # optional module for making bootstrap forms easier

    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'location',

    'allauth.socialaccount.providers.google',  # enabled by configure

    #'allauth.socialaccount.providers.dropbox',
    #'allauth.socialaccount.providers.github',
    #'allauth.socialaccount.providers.linkedin',
    # etc

    'allauthdemo.auth',
    'allauthdemo.demo',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'allauthdemo.urls'

WSGI_APPLICATION = 'allauthdemo.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': '',
    'USER': '',
    'PASSWORD': '',
    'HOST': '',
    'PORT': '',
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

# Authentication

AUTHENTICATION_BACKENDS = (
  'django.contrib.auth.backends.ModelBackend',
    "allauth.account.auth_backends.AuthenticationBackend",
)

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.request",
    "django.contrib.messages.context_processors.messages",
    "allauth.account.context_processors.account",
    "allauth.socialaccount.context_processors.socialaccount",
)

TEMPLATE_DIRS = (
    # allauth templates: you could copy this directory into your
    # project and tweak it according to your needs
    # os.path.join(PROJECT_ROOT, 'templates', 'uniform', 'allauth'),
    # example project specific templates
    os.path.join(BASE_DIR, 'allauthdemo', 'templates', 'plain', 'example'),
    #os.path.join(BASE_DIR, 'allauthdemo', 'templates', 'bootstrap', 'allauth'),
    os.path.join(BASE_DIR, 'allauthdemo', 'templates', 'allauth'),
    os.path.join(BASE_DIR, 'allauthdemo', 'templates'),
)

MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

SITE_ID = 1
AUTH_USER_MODEL = 'auth.DemoUser'
LOGIN_REDIRECT_URL = '/member/'
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_MIN_LENGTH = 3
# ACCOUNT_EMAIL_VERIFICATION = 'none'  # testing...
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
SOCIALACCOUNT_AUTO_SIGNUP = False  # require social accounts to use the signup form ... I think
# For custom sign-up form:
# http://stackoverflow.com/questions/12303478/how-to-customize-user-profile-when-using-django-allauth


text:
<?php
// Copyright 2013 OCLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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.
namespace OCLC\Tests\Auth;

use OCLC\Auth\WSKey;
use OCLC\Auth\AccessToken;
use OCLC\User;
use OCLC\Auth\RefreshToken;
use Guzzle\Http\Client;

class AccessTokenViaRefreshTokenTest extends \PHPUnit_Framework_TestCase
{

    private $accessToken;

    private $options;

    private $wskey;

    private static $services = array(
        'WMS_NCIP',
        'WMS_ACQ'
    );

    private static $redirect_uri = 'http://library.worldshare.edu/test';

    function setUp()
    {
        $wskeyOptions = array(
            'redirectUri' => static::$redirect_uri,
            'services' => static::$services
        );
        $wskeyArgs = array(
            'test',
            'secret',
            $wskeyOptions
        );
        $this->wskey = $this->getMockBuilder(WSkey::class)
        	->setConstructorArgs($wskeyArgs)
        	->getMock();;

        $this->refreshToken = new refreshToken('rt_239308230', '15000', '2018-08-23 18:45:29Z');
        $this->options = array(
            'refreshToken' => $this->refreshToken
        );
        $this->accessToken = new AccessToken('refresh_token', $this->options);
    }

    /**
     * can construct Access Token
     */
    function testGrantTypeSet()
    {
        $this->assertAttributeInternalType('string', 'grantType', $this->accessToken);
        $this->assertAttributeEquals('refresh_token', 'grantType', $this->accessToken);
    }

    function testRefreshTokenSet()
    {
        $this->assertAttributeInstanceOf('OCLC\Auth\RefreshToken', 'refreshToken', $this->accessToken);
        $this->assertAttributeEquals('rt_239308230', 'refreshToken', $this->accessToken->getRefreshToken());
    }

    function testAccess_token_urlSetRefreshToken()
    {
        $desiredURL = 'https://authn.sd00.worldcat.org/oauth2/accessToken?grant_type=refresh_token&refresh_token=rt_239308230';
        $this->assertAttributeInternalType('string', 'accessTokenUrl', $this->accessToken);
        $this->assertAttributeEquals($desiredURL, 'accessTokenUrl', $this->accessToken);
    }

    /**
     * can create Access Token
     */
    function testCreateWithRefreshToken()
    {
        $accessTokenArgs = array(
            'refresh_token',
            $this->options
        );

        $accessTokenMock = $this->getMockBuilder(AccessToken::class)
        	->setMethods(['create'])
        	->setConstructorArgs($accessTokenArgs)
        	->getMock();

        $accessTokenMock->expects($this->once())
            ->method('create')
            ->with($this->isInstanceOf('OCLC\Auth\WSKey'))
            ->will($this->returnSelf());
        $this->assertSame($accessTokenMock, $accessTokenMock->create($this->wskey));
    }

    /**
     * @vcr accessTokenWithRefreshTokenSuccess
     * testProcessGoodAuthServerResponse
     */

    function testRetrieveRefreshToken()
    {
        $options = array(
            'authenticatingInstitutionId' => 128807,
            'contextInstitutionId' => 128807,
            'scope' => static::$services
        );
        $this->accessToken = new AccessToken('client_credentials', $options);

        $this->accessToken->create($this->wskey);

        // Test all the properties are set from the JSON response

        $this->assertInstanceOf('OCLC\Auth\RefreshToken', $this->accessToken->getRefreshToken());

        $this->assertEquals('rt_ZrigZXPJQnB1l2DxF1dCratGNxUHpGLjMw8z', $this->accessToken->getRefreshToken()->getValue());
        $this->assertEquals('604799', $this->accessToken->getRefreshToken()->getExpiresIn());
        $this->assertEquals('2018-08-30 18:25:29Z', $this->accessToken->getRefreshToken()->getExpiresAt());
        $this->assertFalse($this->accessToken->getRefreshToken()->isExpired());
    }

    /**
     * @vcr accessTokenWithRefreshTokenExpired
     * testProcessGoodAuthServerResponse
     */

    function testRetrieveRefreshTokenExpired()
    {
        $options = array(
            'authenticatingInstitutionId' => 128807,
            'contextInstitutionId' => 128807,
            'scope' => static::$services
        );
        $this->accessToken = new AccessToken('client_credentials', $options);

        $this->accessToken->create($this->wskey);

        // Test all the properties are set from the JSON response

        $this->assertInstanceOf('OCLC\Auth\RefreshToken', $this->accessToken->getRefreshToken());

        $this->assertEquals('rt_ZrigZXPJQnB1l2DxF1dCratGNxUHpGLjMw8z', $this->accessToken->getRefreshToken()->getValue());
        $this->assertEquals('604799', $this->accessToken->getRefreshToken()->getExpiresIn());
        $this->assertEquals('2013-08-30 18:25:29Z', $this->accessToken->getRefreshToken()->getExpiresAt());
        $this->assertTrue($this->accessToken->getRefreshToken()->isExpired());
    }

    /* Negative Test Cases */

    /**
     * @expectedException LogicException
     * @expectedExceptionMessage You must pass the option refreshToken to construct an Access Token using the refresh_token grant type
     */
    function testInvalidOptionsRefreshTokenGrantType()
    {
        $options = array(
            'code' => 'auth_239308230'
        );
        $this->accessToken = new AccessToken('refresh_token', $options);
    }

    /**
     * @expectedException LogicException
     * @expectedExceptionMessage You must pass the option refreshToken to construct an Access Token using the refresh_token grant type
     */
    function testInvalidRefreshToken()
    {
        $options = array(
            'refreshToken' => 'rt_123456'
        );
        $this->accessToken = new AccessToken('refresh_token', $options);
    }
}