text:
/*
 *	author: muggle wei <mugglewei@gmail.com>
 *
 *	Use of this source code is governed by the MIT license that can be
 *	found in the LICENSE file.
 */

#include "muggle_benchmark/muggle_benchmark.h"

uint64_t *consumer_read_num = NULL;

struct consumer_thread_args
{
	muggle_ring_buffer_t *ring;
	muggle_atomic_int *consumer_ready;
	muggle_benchmark_block_t *blocks;
};

struct producer_thread_args
{
	muggle_ring_buffer_t *ring;
	muggle_benchmark_config_t *config;
	muggle_benchmark_block_t *blocks;
	muggle_atomic_int *consumer_ready;
	int cnt_consumer;
	uint64_t start_idx;
	uint64_t end_idx;
};

muggle_thread_ret_t consumer_thread(void *void_arg)
{
	struct consumer_thread_args *arg = (struct consumer_thread_args*)void_arg;

	muggle_atomic_int consumer_idx = muggle_atomic_fetch_add(arg->consumer_ready, 1, muggle_memory_order_relaxed);
	muggle_atomic_int pos = 0;
	uint64_t cnt = 0;
	while (1)
	{
		muggle_benchmark_block_t *block = (muggle_benchmark_block_t*)muggle_ring_buffer_read(arg->ring, pos++);
		if (!block)
		{
			break;
		}

		uint64_t block_idx = block->idx;
		timespec_get(&arg->blocks[block_idx].ts[2], TIME_UTC);
		muggle_sowr_memory_pool_free(block);
		timespec_get(&arg->blocks[block_idx].ts[3], TIME_UTC);

		++cnt;
	}
	consumer_read_num[consumer_idx] = cnt;

	return 0;
}

muggle_thread_ret_t producer_thread(void *void_arg)
{
	struct producer_thread_args *arg = (struct producer_thread_args*)void_arg;

	while (muggle_atomic_load(arg->consumer_ready, muggle_memory_order_relaxed) != arg->cnt_consumer);

	muggle_sowr_memory_pool_t pool;
	muggle_sowr_memory_pool_init(&pool, (muggle_atomic_int)(arg->config->loop * (arg->end_idx - arg->start_idx) / 10), sizeof(muggle_benchmark_block_t));

	for (uint64_t i = 0; i < arg->config->loop; ++i)
	{
		for (uint64_t j = arg->start_idx; j < arg->end_idx; ++j)
		{
			uint64_t idx = i * arg->config->cnt_per_loop + j;
			memset(&arg->blocks[idx], 0, sizeof(muggle_benchmark_block_t));
			arg->blocks[idx].idx = idx;

			timespec_get(&arg->blocks[idx].ts[0], TIME_UTC);
			muggle_benchmark_block_t *block = (muggle_benchmark_block_t*)muggle_sowr_memory_pool_alloc(&pool);
			timespec_get(&arg->blocks[idx].ts[1], TIME_UTC);
			if (block == NULL)
			{
				printf("failed allocate memory for idx: %llu\n", (unsigned long long)idx);
				continue;
			}

			block->idx = idx;
			muggle_ring_buffer_write(arg->ring, block);
		}
		if (arg->config->loop_interval_ms > 0)
		{
			muggle_msleep((unsigned int)arg->config->loop_interval_ms);
		}
	}

	while (!muggle_sowr_memory_pool_is_all_free(&pool))
	{
		muggle_msleep((unsigned int)1);
	}
	muggle_sowr_memory_pool_destroy(&pool);

	free(arg);
	return 0;
}

void Benchmark_wr(FILE *fp, muggle_benchmark_config_t *config, int cnt_producer, int cnt_consumer, int flag)
{
	uint64_t cnt = config->loop * config->cnt_per_loop;
	muggle_benchmark_block_t *blocks = (muggle_benchmark_block_t*)malloc(cnt * sizeof(muggle_benchmark_block_t));
	muggle_atomic_int consumer_ready = 0;

	consumer_read_num = (uint64_t*)malloc(sizeof(uint64_t) * cnt_consumer);

	muggle_ring_buffer_t ring;
	muggle_ring_buffer_init(&ring, 1024 * 16, flag);

	// consumer
	muggle_thread_t *consumers = (muggle_thread_t*)malloc(cnt_consumer * sizeof(muggle_thread_t));
	struct consumer_thread_args consumer_args;
	consumer_args.ring = ˚
	consumer_args.consumer_ready = &consumer_ready;
	consumer_args.blocks = blocks;
	for (int i = 0; i < cnt_consumer; ++i)
	{
		muggle_thread_create(&consumers[i], consumer_thread, &consumer_args);
	}

	// producer
	muggle_thread_t *producers = (muggle_thread_t*)malloc(cnt_producer * sizeof(muggle_thread_t));
	for (int i = 0; i < cnt_producer; ++i)
	{
		struct producer_thread_args *producer_args = (struct producer_thread_args*)malloc(sizeof(struct producer_thread_args));
		producer_args->ring = ˚
		producer_args->config = config;
		producer_args->blocks = blocks;
		producer_args->consumer_ready = &consumer_ready;
		producer_args->cnt_consumer = cnt_consumer;
		producer_args->start_idx = i * (config->cnt_per_loop / cnt_producer);
		producer_args->end_idx = (i + 1) * (config->cnt_per_loop / cnt_producer);
		if (i == cnt_producer - 1)
		{
			producer_args->end_idx = config->cnt_per_loop;
		}
		muggle_thread_create(&producers[i], producer_thread, producer_args);
	}

	for (int i = 0; i < cnt_producer; ++i)
	{
		muggle_thread_join(&producers[i]);
	}

	muggle_ring_buffer_write(&ring, NULL);

	for (int i = 0; i < cnt_consumer; ++i)
	{
		muggle_thread_join(&consumers[i]);
	}

	free(producers);
	free(consumers);
	muggle_ring_buffer_destroy(&ring);

	char buf[128];

	for (int i = 0; i < cnt_consumer; ++i)
	{
		printf("%dw%dr consumer[%d] read %llu %s\n",
			cnt_producer, cnt_consumer, i, (unsigned long long)consumer_read_num[i],
			consumer_read_num[i] == config->cnt_per_loop * config->loop ? "" : "(message loss)");
	}
	free(consumer_read_num);

	snprintf(buf, sizeof(buf) - 1, "%dw%dr-sowr-alloc", cnt_producer, cnt_consumer);
	muggle_benchmark_gen_reports_body(fp, config, blocks, buf, cnt, 0, 1, 0);

	snprintf(buf, sizeof(buf) - 1, "%dw%dr-sowr-alloc-sorted", cnt_producer, cnt_consumer);
	muggle_benchmark_gen_reports_body(fp, config, blocks, buf, cnt, 0, 1, 1);

	snprintf(buf, sizeof(buf) - 1, "%dw%dr-sowr-free", cnt_producer, cnt_consumer);
	muggle_benchmark_gen_reports_body(fp, config, blocks, buf, cnt, 2, 3, 0);

	snprintf(buf, sizeof(buf) - 1, "%dw%dr-sowr-free-sorted", cnt_producer, cnt_consumer);
	muggle_benchmark_gen_reports_body(fp, config, blocks, buf, cnt, 2, 3, 1);

	free(blocks);
}

int main()
{
	muggle_benchmark_config_t config;
	strncpy(config.name, "sowr_memory_pool", sizeof(config.name)-1);
	config.loop = 50;
	config.cnt_per_loop = 20000;
	config.loop_interval_ms = 10;
	config.report_step = 10;

	char file_name[128];
	snprintf(file_name, sizeof(file_name)-1, "benchmark_%s.csv", config.name);
	FILE *fp = fopen(file_name, "wb");
	if (fp == NULL)
	{
		printf("failed open file: %s\n", file_name);
		exit(1);
	}

	muggle_benchmark_gen_reports_head(fp, &config);

	int hc = (int)muggle_thread_hardware_concurrency();
	printf("hardware_concurrency: %d\n", hc);

	int flag = 0;

	// 1 writer, 1 reader
	Benchmark_wr(fp, &config, 1, 1, flag);

	// hc write, 1 reader
	Benchmark_wr(fp, &config, hc, 1, flag);

	// 2 * hc write, 1 reader
	Benchmark_wr(fp, &config, 2 * hc, 1, flag);

	fclose(fp);
}


text:
package com.qmetry.qaf.automation.stepfinder.common;

import com.qmetry.qaf.automation.step.QAFTestStep;

public class BaseClass {

	@QAFTestStep(description = "common base step")
	public String commonBaseStep() {
		System.out.println("Commonnn base steps");
		return "BaseStep";
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Elixir\Validator;

/**
 * @author Cédric Tanghe <ced.tanghe@gmail.com>
 */
interface ValidatableInterface
{
    /**
     * @param string $value
     */
    public function setGlobalErrorMessage($value);

    /**
     * @return string
     */
    public function getGlobalErrorMessage();

    /**
     * @param bool $value
     */
    public function setBreakChainValidationOnFailure($value);

    /**
     * @return bool
     */
    public function isBreakChainValidationOnFailure();

    /**
     * @param ValidatorInterface $validator
     * @param array              $options
     */
    public function addValidator(ValidatorInterface $validator, array $options = []);

    /**
     * @param array $validators
     */
    public function setValidators(array $validators);

    /**
     * @return array
     */
    public function getValidators();

    /**
     * @return bool
     */
    public function hasError();

    /**
     * @param array $messages
     */
    public function setErrorMessages(array $messages);

    /**
     * @return array
     */
    public function getErrorMessages();

    /**
     * @param mixed $data
     * @param array $options
     *
     * @return bool
     */
    public function validate($data = null, array $options = []);

    public function resetValidation();
}


text:
var gulp = require('gulp');
var gutil = require('gulp-util');
var path = require("path");
var sass = require('gulp-sass');
var autoprefixer = require("gulp-autoprefixer");
var minifyCss = require('gulp-minify-css');
var sourcemaps = require('gulp-sourcemaps');
var webpack = require("webpack");
var eslint = require('gulp-eslint');
var browserSync = require('browser-sync').create();

var getWebpackConfig = function() {
  return {
    context: __dirname + "/src/scripts",
    entry: {
      Core: "./Core",
      Editor: "./Editor",
    },
    devtool: "eval-source-map",
    externals: [
      'd3',
      {
        'file-saver': {
          root: 'saveAs',
          commonjs: 'file-saver',
          commonjs2: 'file-saver',
          amd: 'file-saver'
        },
        'spectrum': {
          root: 'spectrum',
          commonjs: 'spectrum-colorpicker',
          commonjs2: 'spectrum-colorpicker',
          amd: 'spectrum',
        },
        'js-signals': {
          root: 'signals',
          commonjs: 'signals',
          commonjs2: 'signals',
          amd: 'signals'
        },
        'draggable-number.js': {
          root: 'DraggableNumber',
          commonjs: 'draggable-number.js',
          commonjs2: 'draggable-number.js',
          amd: 'DraggableNumber'
        },
        'TweenMax': {
          root: 'TweenMax',
          commonjs: ['gsap', 'TweenMax'],
          commonjs2: ['gsap', 'TweenMax'],
          amd: 'TweenMax'
        },
        'TimelineMax': {
          root: 'TimelineMax',
          commonjs: ['gsap', 'TimelineMax'],
          commonjs2: ['gsap', 'TimelineMax'],
          amd: 'TimelineMax'
        },
        'Quad': {
          root: 'Quad',
          commonjs: ['gsap', 'Quad'],
          commonjs2: ['gsap', 'Quad'],
          amd: 'Quad'
        },
        'jquery': {
          root: '$',
          commonjs: 'jquery',
          commonjs2: 'jquery',
          amd: 'jquery'
        },
        'lodash': {
          root: '_',
          commonjs: "lodash",
          commonjs2: "lodash",
          amd: "lodash"
        }
      }
    ],
    output: {
        path: path.join(__dirname, "dist/scripts"),
        filename: "TweenTime.[name].js",
        libraryTarget: "umd",
        library: ["TweenTime", "[name]"]
    },
    module: {
      loaders: [
        {
          test: /\.js$/,
          exclude: [/bower_components/, /node_modules/, /dist/],
          loader: 'babel',
          query: {
            presets: ['es2015']
          }
        },
        {
          test: /\.tpl.html$/,
          loader: 'mustache'
        }
      ],
    },
    plugins: [
      new webpack.ResolverPlugin(
          new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
      )
    ],
  };
};

gulp.task('lint-scripts', function() {
  gulp.src([
    'src/scripts/**/*.js',
    '!src/scripts/bower_components/**'
    ])
    .pipe(eslint())
    .pipe(eslint.formatEach('stylish', process.stderr));
});

gulp.task('scripts', function(cb) {
  var conf = getWebpackConfig();
  webpack(conf, function(err, stats) {
    if(err) throw new gutil.PluginError("webpack", err);
    gutil.log("[webpack]", stats.toString({
        chunks: false
    }));
    cb();
  });
});

gulp.task('scripts:dist', ['lint-scripts'], function(cb) {
  var conf = getWebpackConfig();
  // Add .min.js to output filename.
  conf.output.filename = "TweenTime.[name].min.js";
  // Add minification with UglifyJs.
  conf.plugins.push(new webpack.optimize.UglifyJsPlugin({
    mangle: true,
    output: {
      comments: false
    },
    compress: {
      drop_debugger: false,
      sequences: true,
      //dead_code: true,
      conditionals: true,
      booleans: true,
      unused: true,
      if_return: true,
      join_vars: true,
      drop_console: false
    }
  }));
  webpack(conf, function(err, stats) {
    if(err) throw new gutil.PluginError("webpack", err);
    gutil.log("[webpack]", stats.toString({
        chunks: false
    }));
    cb();
  });
});

gulp.task('styles', function() {
  gulp.src('src/styles/editor.sass')
    .pipe(sourcemaps.init())
    .pipe(sass({
      sourceComments: false,
      omitSourceMapUrl: true,
      errLogToConsole: true
    }))
    .pipe(sourcemaps.write({includeContent: false}))
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(autoprefixer({
      browsers: ['> 5%', 'last 2 versions'],
      cascade: false
    }))
    .pipe(minifyCss())
    .pipe(sourcemaps.write('./maps'))
    .pipe(gulp.dest('./dist/styles/'))
    .pipe(browserSync.stream({match: '**/*.css'}));
});

gulp.task('browser-sync', function() {
  browserSync.init({
    server: {
      baseDir: './',
      directory: true
    }
  });
});

gulp.task('watch', function() {
  gulp.watch(['examples/*.html'], browserSync.reload);
  gulp.watch(['dist/scripts/*.js'], browserSync.reload);
  gulp.watch('src/styles/**', ['styles']);
  gulp.watch(['src/scripts/**', '!src/scripts/bower_components/**'], ['scripts:dist']);
});

gulp.task('default', ['watch', 'styles', 'scripts:dist', 'browser-sync']);
gulp.task('build', ['styles', 'scripts', 'scripts:dist']);


text:
use validator::{Validate, ValidationError};

fn hello_world(_: &str, _arg: &mut String) -> Result<(), ValidationError> {
    Ok(())
}

#[derive(Validate)]
struct Test {
    #[validate(custom(function = "hello_world", arg = "&'a mut String"))]
    s: String,
}

fn main() {}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.07.02 at 03:35:23 PM MSK
//

package ru.gov.zakupki.oos.signincoming.soap.messages;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import ru.gov.zakupki.oos.signincoming._1.Contract;
import ru.gov.zakupki.oos.signincoming._1.ContractProcedure;
import ru.gov.zakupki.oos.signincoming._1.ContractProcedureCancel;
import ru.gov.zakupki.oos.signincoming._1.ContractWithControl99NoticeCompliance;

/**
 *
Java class for receiveRkRequestType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="receiveRkRequestType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <choice>
 *         <element name="contractProcedure" type="{http://zakupki.gov.ru/oos/signIncoming/1}contractProcedure"/>
 *         <element name="contractProcedureCancel" type="{http://zakupki.gov.ru/oos/signIncoming/1}contractProcedureCancel"/>
 *         <element name="contract" type="{http://zakupki.gov.ru/oos/signIncoming/1}contract"/>
 *         <element name="contractWithControl99NoticeCompliance" type="{http://zakupki.gov.ru/oos/signIncoming/1}contractWithControl99NoticeCompliance"/>
 *       </choice>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "receiveRkRequestType", propOrder = {
    "contractProcedure",
    "contractProcedureCancel",
    "contract",
    "contractWithControl99NoticeCompliance"
})
public class ReceiveRkRequestType {

    protected ContractProcedure contractProcedure;
    protected ContractProcedureCancel contractProcedureCancel;
    protected Contract contract;
    protected ContractWithControl99NoticeCompliance contractWithControl99NoticeCompliance;

    /**
     * Gets the value of the contractProcedure property.
     *
     * @return
     *     possible object is
     *     {@link ContractProcedure }
     *
     */
    public ContractProcedure getContractProcedure() {
        return contractProcedure;
    }

    /**
     * Sets the value of the contractProcedure property.
     *
     * @param value
     *     allowed object is
     *     {@link ContractProcedure }
     *
     */
    public void setContractProcedure(ContractProcedure value) {
        this.contractProcedure = value;
    }

    /**
     * Gets the value of the contractProcedureCancel property.
     *
     * @return
     *     possible object is
     *     {@link ContractProcedureCancel }
     *
     */
    public ContractProcedureCancel getContractProcedureCancel() {
        return contractProcedureCancel;
    }

    /**
     * Sets the value of the contractProcedureCancel property.
     *
     * @param value
     *     allowed object is
     *     {@link ContractProcedureCancel }
     *
     */
    public void setContractProcedureCancel(ContractProcedureCancel value) {
        this.contractProcedureCancel = value;
    }

    /**
     * Gets the value of the contract property.
     *
     * @return
     *     possible object is
     *     {@link Contract }
     *
     */
    public Contract getContract() {
        return contract;
    }

    /**
     * Sets the value of the contract property.
     *
     * @param value
     *     allowed object is
     *     {@link Contract }
     *
     */
    public void setContract(Contract value) {
        this.contract = value;
    }

    /**
     * Gets the value of the contractWithControl99NoticeCompliance property.
     *
     * @return
     *     possible object is
     *     {@link ContractWithControl99NoticeCompliance }
     *
     */
    public ContractWithControl99NoticeCompliance getContractWithControl99NoticeCompliance() {
        return contractWithControl99NoticeCompliance;
    }

    /**
     * Sets the value of the contractWithControl99NoticeCompliance property.
     *
     * @param value
     *     allowed object is
     *     {@link ContractWithControl99NoticeCompliance }
     *
     */
    public void setContractWithControl99NoticeCompliance(ContractWithControl99NoticeCompliance value) {
        this.contractWithControl99NoticeCompliance = value;
    }

}


text:
<?php

namespace SmartyView\Smarty\Plugins;

use Illuminate\Support\Facades\URL as URLFacade;

class URL implements SmartyPlugin {
	const URL_TYPE_ROUTE = 'route';
	const URL_TYPE_ACTION = 'action';
	const URL_TYPE_ASSET = 'asset';
	const URL_TYPE_SECURE_URL = 'secure_url';
	const URL_TYPE_URL = 'url';

	public function getType() {
		return self::PLUGIN_TYPE_MODIFIER;
	}

	public function pluginCallback() {
		$params = func_get_args();

		$value = array_shift($params);
		$type = array_shift($params);
		$params = json_decode(array_shift($params), true);

		$acceptableTypes = array(
			self::URL_TYPE_ROUTE,
			self::URL_TYPE_ACTION,
			self::URL_TYPE_ASSET,
			self::URL_TYPE_SECURE_URL,
			self::URL_TYPE_URL
		);

		if (in_array($type, $acceptableTypes)) {
			return URLFacade::$type($value, is_array($params) ? $params : null);
		}

		return '';
	}
}


text:
#ifndef __included_tcp_timer_h__
#define __included_tcp_timer_h__

#include <vnet/tcp/tcp_types.h>

always_inline void
tcp_timer_set (tcp_timer_wheel_t * tw, tcp_connection_t * tc, u8 timer_id,
	       u32 interval)
{
  ASSERT (tc->c_thread_index == vlib_get_thread_index ());
  ASSERT (tc->timers[timer_id] == TCP_TIMER_HANDLE_INVALID);
  tc->timers[timer_id] = tw_timer_start_tcp_twsl (tw, tc->c_c_index,
						  timer_id, interval);
}

always_inline void
tcp_timer_reset (tcp_timer_wheel_t * tw, tcp_connection_t * tc, u8 timer_id)
{
  ASSERT (tc->c_thread_index == vlib_get_thread_index ());
  tc->pending_timers &= ~(1 << timer_id);
  if (tc->timers[timer_id] == TCP_TIMER_HANDLE_INVALID)
    return;

  tw_timer_stop_tcp_twsl (tw, tc->timers[timer_id]);
  tc->timers[timer_id] = TCP_TIMER_HANDLE_INVALID;
}

always_inline void
tcp_timer_update (tcp_timer_wheel_t * tw, tcp_connection_t * tc, u8 timer_id,
		  u32 interval)
{
  ASSERT (tc->c_thread_index == vlib_get_thread_index ());
  if (tc->timers[timer_id] != TCP_TIMER_HANDLE_INVALID)
    tw_timer_update_tcp_twsl (tw, tc->timers[timer_id], interval);
  else
    tc->timers[timer_id] = tw_timer_start_tcp_twsl (tw, tc->c_c_index,
						    timer_id, interval);
}

always_inline u8
tcp_timer_is_active (tcp_connection_t *tc, tcp_timers_e timer)
{
  return tc->timers[timer] != TCP_TIMER_HANDLE_INVALID ||
	 (tc->pending_timers & (1 << timer));
}

always_inline void
tcp_retransmit_timer_set (tcp_timer_wheel_t * tw, tcp_connection_t * tc)
{
  ASSERT (tc->snd_una != tc->snd_nxt);
  tcp_timer_set (tw, tc, TCP_TIMER_RETRANSMIT,
		 clib_max ((u32) tc->rto * TCP_TO_TIMER_TICK, 1));
}

always_inline void
tcp_retransmit_timer_reset (tcp_timer_wheel_t * tw, tcp_connection_t * tc)
{
  tcp_timer_reset (tw, tc, TCP_TIMER_RETRANSMIT);
}

always_inline void
tcp_persist_timer_set (tcp_timer_wheel_t * tw, tcp_connection_t * tc)
{
  /* Reuse RTO. It's backed off in handler */
  tcp_timer_set (tw, tc, TCP_TIMER_PERSIST,
		 clib_max ((u32) tc->rto * TCP_TO_TIMER_TICK, 1));
}

always_inline void
tcp_persist_timer_reset (tcp_timer_wheel_t * tw, tcp_connection_t * tc)
{
  tcp_timer_reset (tw, tc, TCP_TIMER_PERSIST);
}

always_inline void
tcp_retransmit_timer_update (tcp_timer_wheel_t * tw, tcp_connection_t * tc)
{
  if (tc->snd_una == tc->snd_nxt)
    {
      tcp_retransmit_timer_reset (tw, tc);
      if (tc->snd_wnd < tc->snd_mss &&
	  !tcp_timer_is_active (tc, TCP_TIMER_PERSIST))
	tcp_persist_timer_set (tw, tc);
    }
  else
    tcp_timer_update (tw, tc, TCP_TIMER_RETRANSMIT,
		      clib_max ((u32) tc->rto * TCP_TO_TIMER_TICK, 1));
}

always_inline void
tcp_timer_expire_timers (tcp_timer_wheel_t * tw, f64 now)
{
  tw_timer_expire_timers_tcp_twsl (tw, now);
}

void tcp_timer_initialize_wheel (tcp_timer_wheel_t * tw,
				 void (*expired_timer_cb) (u32 *), f64 now);

#endif /* __included_tcp_timer_h__ */

/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "gnu")
 * End:
 */


text:
$(document).ready(function() {
	$('#fullpage').fullpage({
		sectionsColor: ['#ffffff'],
		anchors: ['firstPage'],
		menu: '#menu',
		scrollingSpeed: 1000
	});

});


text:
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).

#ifndef ROCKSDB_LITE

#include "db/transaction_log_impl.h"
#include <cinttypes>
#include "db/write_batch_internal.h"
#include "file/sequence_file_reader.h"

namespace ROCKSDB_NAMESPACE {

TransactionLogIteratorImpl::TransactionLogIteratorImpl(
    const std::string& dir, const ImmutableDBOptions* options,
    const TransactionLogIterator::ReadOptions& read_options,
    const EnvOptions& soptions, const SequenceNumber seq,
    std::unique_ptr<VectorLogPtr> files, VersionSet const* const versions,
    const bool seq_per_batch)
    : dir_(dir),
      options_(options),
      read_options_(read_options),
      soptions_(soptions),
      starting_sequence_number_(seq),
      files_(std::move(files)),
      started_(false),
      is_valid_(false),
      current_file_index_(0),
      current_batch_seq_(0),
      current_last_seq_(0),
      versions_(versions),
      seq_per_batch_(seq_per_batch) {
  assert(files_ != nullptr);
  assert(versions_ != nullptr);

  reporter_.env = options_->env;
  reporter_.info_log = options_->info_log.get();
  SeekToStartSequence(); // Seek till starting sequence
}

Status TransactionLogIteratorImpl::OpenLogFile(
    const LogFile* log_file,
    std::unique_ptr<SequentialFileReader>* file_reader) {
  FileSystem* fs = options_->fs.get();
  std::unique_ptr<FSSequentialFile> file;
  std::string fname;
  Status s;
  EnvOptions optimized_env_options = fs->OptimizeForLogRead(soptions_);
  if (log_file->Type() == kArchivedLogFile) {
    fname = ArchivedLogFileName(dir_, log_file->LogNumber());
    s = fs->NewSequentialFile(fname, optimized_env_options, &file, nullptr);
  } else {
    fname = LogFileName(dir_, log_file->LogNumber());
    s = fs->NewSequentialFile(fname, optimized_env_options, &file, nullptr);
    if (!s.ok()) {
      //  If cannot open file in DB directory.
      //  Try the archive dir, as it could have moved in the meanwhile.
      fname = ArchivedLogFileName(dir_, log_file->LogNumber());
      s = fs->NewSequentialFile(fname, optimized_env_options,
                                &file, nullptr);
    }
  }
  if (s.ok()) {
    file_reader->reset(new SequentialFileReader(std::move(file), fname));
  }
  return s;
}

BatchResult TransactionLogIteratorImpl::GetBatch()  {
  assert(is_valid_);  //  cannot call in a non valid state.
  BatchResult result;
  result.sequence = current_batch_seq_;
  result.writeBatchPtr = std::move(current_batch_);
  return result;
}

Status TransactionLogIteratorImpl::status() { return current_status_; }

bool TransactionLogIteratorImpl::Valid() { return started_ && is_valid_; }

bool TransactionLogIteratorImpl::RestrictedRead(Slice* record) {
  // Don't read if no more complete entries to read from logs
  if (current_last_seq_ >= versions_->LastSequence()) {
    return false;
  }
  return current_log_reader_->ReadRecord(record, &scratch_);
}

void TransactionLogIteratorImpl::SeekToStartSequence(uint64_t start_file_index,
                                                     bool strict) {
  Slice record;
  started_ = false;
  is_valid_ = false;
  if (files_->size() <= start_file_index) {
    return;
  }
  Status s =
      OpenLogReader(files_->at(static_cast<size_t>(start_file_index)).get());
  if (!s.ok()) {
    current_status_ = s;
    reporter_.Info(current_status_.ToString().c_str());
    return;
  }
  while (RestrictedRead(&record)) {
    if (record.size() < WriteBatchInternal::kHeader) {
      reporter_.Corruption(
        record.size(), Status::Corruption("very small log record"));
      continue;
    }
    UpdateCurrentWriteBatch(record);
    if (current_last_seq_ >= starting_sequence_number_) {
      if (strict && current_batch_seq_ != starting_sequence_number_) {
        current_status_ = Status::Corruption(
            "Gap in sequence number. Could not "
            "seek to required sequence number");
        reporter_.Info(current_status_.ToString().c_str());
        return;
      } else if (strict) {
        reporter_.Info("Could seek required sequence number. Iterator will "
                       "continue.");
      }
      is_valid_ = true;
      started_ = true; // set started_ as we could seek till starting sequence
      return;
    } else {
      is_valid_ = false;
    }
  }

  // Could not find start sequence in first file. Normally this must be the
  // only file. Otherwise log the error and let the iterator return next entry
  // If strict is set, we want to seek exactly till the start sequence and it
  // should have been present in the file we scanned above
  if (strict) {
    current_status_ = Status::Corruption(
        "Gap in sequence number. Could not "
        "seek to required sequence number");
    reporter_.Info(current_status_.ToString().c_str());
  } else if (files_->size() != 1) {
    current_status_ = Status::Corruption(
        "Start sequence was not found, "
        "skipping to the next available");
    reporter_.Info(current_status_.ToString().c_str());
    // Let NextImpl find the next available entry. started_ remains false
    // because we don't want to check for gaps while moving to start sequence
    NextImpl(true);
  }
}

void TransactionLogIteratorImpl::Next() {
  return NextImpl(false);
}

void TransactionLogIteratorImpl::NextImpl(bool internal) {
  Slice record;
  is_valid_ = false;
  if (!internal && !started_) {
    // Runs every time until we can seek to the start sequence
    return SeekToStartSequence();
  }
  while(true) {
    assert(current_log_reader_);
    if (current_log_reader_->IsEOF()) {
      current_log_reader_->UnmarkEOF();
    }
    while (RestrictedRead(&record)) {
      if (record.size() < WriteBatchInternal::kHeader) {
        reporter_.Corruption(
          record.size(), Status::Corruption("very small log record"));
        continue;
      } else {
        // started_ should be true if called by application
        assert(internal || started_);
        // started_ should be false if called internally
        assert(!internal || !started_);
        UpdateCurrentWriteBatch(record);
        if (internal && !started_) {
          started_ = true;
        }
        return;
      }
    }

    // Open the next file
    if (current_file_index_ < files_->size() - 1) {
      ++current_file_index_;
      Status s = OpenLogReader(files_->at(current_file_index_).get());
      if (!s.ok()) {
        is_valid_ = false;
        current_status_ = s;
        return;
      }
    } else {
      is_valid_ = false;
      if (current_last_seq_ == versions_->LastSequence()) {
        current_status_ = Status::OK();
      } else {
        const char* msg = "Create a new iterator to fetch the new tail.";
        current_status_ = Status::TryAgain(msg);
      }
      return;
    }
  }
}

bool TransactionLogIteratorImpl::IsBatchExpected(
    const WriteBatch* batch, const SequenceNumber expected_seq) {
  assert(batch);
  SequenceNumber batchSeq = WriteBatchInternal::Sequence(batch);
  if (batchSeq != expected_seq) {
    char buf[200];
    snprintf(buf, sizeof(buf),
             "Discontinuity in log records. Got seq=%" PRIu64
             ", Expected seq=%" PRIu64 ", Last flushed seq=%" PRIu64
             ".Log iterator will reseek the correct batch.",
             batchSeq, expected_seq, versions_->LastSequence());
    reporter_.Info(buf);
    return false;
  }
  return true;
}

void TransactionLogIteratorImpl::UpdateCurrentWriteBatch(const Slice& record) {
  std::unique_ptr<WriteBatch> batch(new WriteBatch());
  WriteBatchInternal::SetContents(batch.get(), record);

  SequenceNumber expected_seq = current_last_seq_ + 1;
  // If the iterator has started, then confirm that we get continuous batches
  if (started_ && !IsBatchExpected(batch.get(), expected_seq)) {
    // Seek to the batch having expected sequence number
    if (expected_seq < files_->at(current_file_index_)->StartSequence()) {
      // Expected batch must lie in the previous log file
      // Avoid underflow.
      if (current_file_index_ != 0) {
        current_file_index_--;
      }
    }
    starting_sequence_number_ = expected_seq;
    // currentStatus_ will be set to Ok if reseek succeeds
    // Note: this is still ok in seq_pre_batch_ && two_write_queuesp_ mode
    // that allows gaps in the WAL since it will still skip over the gap.
    current_status_ = Status::NotFound("Gap in sequence numbers");
    // In seq_per_batch_ mode, gaps in the seq are possible so the strict mode
    // should be disabled
    return SeekToStartSequence(current_file_index_, !seq_per_batch_);
  }

  struct BatchCounter : public WriteBatch::Handler {
    SequenceNumber sequence_;
    BatchCounter(SequenceNumber sequence) : sequence_(sequence) {}
    Status MarkNoop(bool empty_batch) override {
      if (!empty_batch) {
        sequence_++;
      }
      return Status::OK();
    }
    Status MarkEndPrepare(const Slice&) override {
      sequence_++;
      return Status::OK();
    }
    Status MarkCommit(const Slice&) override {
      sequence_++;
      return Status::OK();
    }

    Status PutCF(uint32_t /*cf*/, const Slice& /*key*/,
                 const Slice& /*val*/) override {
      return Status::OK();
    }
    Status DeleteCF(uint32_t /*cf*/, const Slice& /*key*/) override {
      return Status::OK();
    }
    Status SingleDeleteCF(uint32_t /*cf*/, const Slice& /*key*/) override {
      return Status::OK();
    }
    Status MergeCF(uint32_t /*cf*/, const Slice& /*key*/,
                   const Slice& /*val*/) override {
      return Status::OK();
    }
    Status MarkBeginPrepare(bool) override { return Status::OK(); }
    Status MarkRollback(const Slice&) override { return Status::OK(); }
  };

  current_batch_seq_ = WriteBatchInternal::Sequence(batch.get());
  if (seq_per_batch_) {
    BatchCounter counter(current_batch_seq_);
    batch->Iterate(&counter);
    current_last_seq_ = counter.sequence_;
  } else {
    current_last_seq_ =
        current_batch_seq_ + WriteBatchInternal::Count(batch.get()) - 1;
  }
  // currentBatchSeq_ can only change here
  assert(current_last_seq_ <= versions_->LastSequence());

  current_batch_ = std::move(batch);
  is_valid_ = true;
  current_status_ = Status::OK();
}

Status TransactionLogIteratorImpl::OpenLogReader(const LogFile* log_file) {
  std::unique_ptr<SequentialFileReader> file;
  Status s = OpenLogFile(log_file, &file);
  if (!s.ok()) {
    return s;
  }
  assert(file);
  current_log_reader_.reset(
      new log::Reader(options_->info_log, std::move(file), &reporter_,
                      read_options_.verify_checksums_, log_file->LogNumber()));
  return Status::OK();
}
}  // namespace ROCKSDB_NAMESPACE
#endif  // ROCKSDB_LITE


text:
<?php

namespace PROCERGS\VPR\CoreBundle\Controller\Admin;

use PROCERGS\VPR\CoreBundle\Entity\User;
use PROCERGS\VPR\CoreBundle\Form\Type\Admin\UserForm;
use Rhumsaa\Uuid\Uuid;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

/**
 * User controller.
 *
 * @Route("/user")
 */
class UserController extends Controller
{

    /**
     * @Route("/", name="admin_user_list")
     * @Route("/search", name="admin_user_search")
     * @Method({"GET","POST"})
     * @Template("PROCERGSVPRCoreBundle:Admin/User:index.html.twig")
     */
    public function searchAction(Request $request)
    {
        $this->denyAccessUnlessGranted('ROLE_USER_READ');
        $repo = $this->getDoctrine()->getRepository('PROCERGSVPRCoreBundle:User');
        $query = $request->get('query', null);
        if ($request->isMethod(Request::METHOD_POST) || $query !== null) {
            $users = $repo->findBy(['email' => $request->get('query')]);
        } else {
            $users = $repo->findAll();
        }

        return compact('users');
    }

    /**
     * Finds and displays an User entity.
     *
     * @Route("/{id}/edit", name="admin_user_edit")
     * @Method({"GET","POST"})
     * @Template("PROCERGSVPRCoreBundle:Admin/User:form.html.twig")
     */
    public function editAction(Request $request, $id)
    {
        $this->denyAccessUnlessGranted('ROLE_USER_UPDATE');
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('PROCERGSVPRCoreBundle:User')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find User.');
        }

        $form = $this->createForm(new UserForm(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        $form->handleRequest($request);
        if ($form->isValid()) {
            $em->persist($entity);
            $em->flush($entity);

            return $this->redirectToRoute('admin_user_edit', compact('id'));
        }

        return array(
            'entity' => $entity,
            'form' => $form->createView(),
            'deleteForm' => $deleteForm->createView(),
        );
    }

    /**
     * Finds and displays an User entity.
     *
     * @Route("/new", name="admin_user_new")
     * @Method({"GET","POST"})
     * @Template("PROCERGSVPRCoreBundle:Admin/User:form.html.twig")
     */
    public function newAction(Request $request)
    {
        $this->denyAccessUnlessGranted('ROLE_USER_CREATE');
        $entity = new User();

        $form = $this->createForm(new UserForm(), $entity);

        $form->handleRequest($request);
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();

            $entity->setConfirmationCode(Uuid::uuid4());
            $em->persist($entity);
            $em->flush($entity);

            $email = \Swift_Message::newInstance()
                ->setSubject('Novo cadastro na Consulta Popular')
                ->setFrom($this->getParameter('mailer_sender_mail'))
                ->setTo($entity->getEmail())
                ->setBody(
                    $this->renderView(
                        'PROCERGSVPRCoreBundle:Emails:registration.txt.twig',
                        array(
                            'name' => $entity->getName(),
                            'code' => $entity->getConfirmationCode(),
                        )
                    ),
                    'text/plain'
                );
            $this->get('mailer')->send($email);

            return $this->redirectToRoute('admin_user_edit', ['id' => $entity->getId()]);
        }

        return array(
            'entity' => $entity,
            'form' => $form->createView(),
        );
    }

    /**
     * Deletes an User entity.
     *
     * @Route("/{id}", name="admin_user_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $this->denyAccessUnlessGranted('ROLE_USER_DELETE');
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('PROCERGSVPRCoreBundle:User')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Category entity.');
            }

            $em->remove($entity);
            $em->flush();

            $translator = $this->get('translator');
            $this->get('session')->getFlashBag()->add(
                'success',
                $translator->trans('admin.successfully_removed_record')
            );
        }

        return $this->redirect($this->generateUrl('admin_user_list'));
    }

    /**
     * Creates a form to delete a User entity by id.
     *
     * @param mixed $id the entity id
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('admin_user_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm();
    }
}


text:
/**
 * Created by 31211 on 2016/5/12 0012.
 */

/**
 * @description 配置模块基础信息
 * */
require.config({
    baseUrl: "./scripts",
    paths: {
        'jquery': ['/js/jquery.min'],
        // 滚动条插件
        'perfect-scrollbar': ['/js/jquery/plugins/perfect-scrollbar/perfect-scrollbar-0.4.1.min'],
        'perfect-scrollbar-mousewheel': ['/js/jquery/plugins/perfect-scrollbar-0.4.1.with-mousewheel.min'],
        // 通用库
        'common': ['../js/util'],
        'underscore': ['/js/underscore-min'],
        // mvvm框架库
        'knockout': ['/js/knockout-3.4.0.debug'],

        //Goldwind 框架
        'GD_base1.1': ['../js/base1.1'],
        'GD_baseUI': ['/js/baseUI'],
        'GD_runlog': ['/js/runlog'],
        'GD_canvasNew': ['/js/layout/canvasNew'],

        // controller
        'homePageController': ['Controllers/homePageController'],
        // model
        'dataModel': ['Model/DataModel'],
        // viewModel
        'homePageViewModel': ['ViewModel/homePageViewModel'],
        // services
        'standingBookService': ['Services/standingBookService'],
        'monitorServices': ['Services/monitorServices']
    },
    shim: {
        'perfect-scrollbar-mousewheel': ['jquery'],
        'perfect-scrollbar': ['jquery', 'perfect-scrollbar-mousewheel'],
        'underscore': {
            exports: '_'
        },
        'GD_canvasNew': {
            deps: ['GD_base1.1', 'GD_baseUI']
        },
        'GD_baseUI': {
            exports: 'UI'
        }
    }
})
;

/**
 * @description 初始化
 *, 'domReady'domReady
 * */
require(['jquery', 'homePageController'], function ($, homePage) {
    "use strict"

    $(document).ready(function () {
        homePage.init();
    })

});


text:
import time

class Effect:

    """
    Representation of an effect. Effects can alter the behavior
    or stats of a unit and can have a duration or be permanent
    """

    def __init__(self, **kwargs):
        effect = kwargs["effect"]
        self.id = effect["id"]
        self.name = effect["name"]
        self.description = effect["description"]
        self.operator = effect["operator"]
        self.hp_adjustment = effect["hp_adjustment"]
        self.incoming_damage_adjustment = effect["incoming_damage_adjustment"]
        self.outgoing_damage_adjustment = effect["outgoing_damage_adjustment"]
        self.interval_seconds = effect["interval_seconds"]
        self.stacks = int(effect["stacks"])
        self.effect_on_possession = False
        self.created_at = time.time()

        if "effect_on_possession" in effect:
            self.effect_on_possession = effect["effect_on_possession"]

    def get_hp_adjustment(self):
        return self.hp_adjustment * self.stacks

    def get_incoming_damage_adjustment(self):
        return self.incoming_damage_adjustment * self.stacks

    def get_outgoing_damage_adjustment(self):
        return self.outgoing_damage_adjustment * self.stacks


text:
package com.chrisharrill.metaheuristics.searches.cuckoo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

import com.chrisharrill.metaheuristics.accept.Acceptor;
import com.chrisharrill.metaheuristics.fitness.Fitness;
import com.chrisharrill.metaheuristics.searches.Search;

public class CuckooSearch extends Search {
	private int numNests;
	private double prob;
	private double[] low;
	private double[] up;
	private Nest[] nests;
	private double best;
	private double[] bestLoc;
	private double currentBest;
	private double[] currentBestLoc;
	private int locSize;
	private Random r = new Random();

	public CuckooSearch(Fitness fitness, Acceptor acceptor, int numberOfNests, double probabilityOfDiscovery) {
		super(fitness, acceptor);
		numNests = numberOfNests;
		prob = probabilityOfDiscovery;
		low = fitness.getBounds()[0];
		up = fitness.getBounds()[1];
		nests = new Nest[numNests];
		locSize = fitness.getSolutionSize();
		best = fitness.getWorstFitness();
		bestLoc = new double[locSize];
		currentBest = fitness.getWorstFitness();
		currentBestLoc = new double[locSize];
		for (int i = 0; i < numNests; i++) {
			double[] location = new double[locSize];
			for (int j = 0; j < low.length; j++) {
				// double rand = Math.random();
				// location[j] = low[j] + up[j] * rand - low[j] * rand;
				// Strange syntax guarantess it won't overflow
				location[j] = low[j] + (up[j] - low[j]) * Math.random();
			}
			nests[i] = new Nest(location);
			nests[i].setFitness(fitness.evaluateSolution(nests[i].getLocation()));
		}
	}

	public void setInitialSoln(double[] loc, int i) {
		nests[i].setLocation(loc.clone());
		nests[i].setFitness(fitness.evaluateSolution(loc));
	}

	private void getBestNest() {
		double best = fitness.getWorstFitness();
		double[] location = new double[locSize];
		for (int i = 0; i < numNests; i++) {
			double f = fitness.evaluateSolution(nests[i].getLocation());
			if (fitness.fitnessCompare(f, nests[i].getFitness()) > 0)
				nests[i].setFitness(f);
			if (fitness.fitnessCompare(nests[i].getFitness(), best) > 0) {
				best = nests[i].getFitness();
				location = nests[i].getLocation();
			}
		}
		currentBest = best;
		currentBestLoc = location.clone();
	}

	private double[] LevyFlight(double[] loc) {
		double beta = 3.0 / 2.0;
		double gamma1 = 1.32934038818; // = gamma(1 + beta)
		double gamma2 = 0.919062526849; // = gamma(1 + beta/2)
		double sigma = Math.pow((gamma1 * Math.sin(Math.PI / 2.0) / (gamma2
				* beta * Math.pow(2.0, (beta - 1.0) / 2.0))), 1.0 / beta);
		for (int i = 0; i < locSize; i++) {
			double u = r.nextGaussian() * sigma;
			double v = r.nextGaussian();
			double step = u / Math.pow(Math.abs(v), 1.0 / beta);
			double stepsize = 0.01 * step * (loc[i] - currentBestLoc[i]);
			loc[i] += stepsize * r.nextGaussian();
		}
		double[] loc_temp = loc.clone();
		for (int i = 0; i < loc.length; i++) {
			if (loc[i] < low[i])
				loc_temp[i] = low[i];
			if (loc[i] > up[i])
				loc_temp[i] = up[i];
		}
		return loc_temp;
	}

	private void getCuckoos() {
		for (int i = 0; i < numNests; i++) {
			double[] newLoc = LevyFlight(nests[i].getLocation());
			double newFit = fitness.evaluateSolution(newLoc);
			if (fitness.fitnessCompare(newFit, nests[i].getFitness()) > 0) {
				nests[i] = new Nest(newLoc);
				nests[i].setFitness(newFit);
			}
		}
	}

	private void emptyNests() {
		int[] discoveredBooleans = new int[numNests];
		for (int i = 0; i < numNests; i++)
			discoveredBooleans[i] = (r.nextDouble() < prob) ? 1 : 0;
		ArrayList<Integer> range1 = new ArrayList<Integer>();
		ArrayList<Integer> range2 = new ArrayList<Integer>();
		for (int i = 0; i < numNests; i++) {
			range1.add(Integer.valueOf(i));
			range2.add(Integer.valueOf(i));
		}
		double[][] stepsize = new double[numNests][];
		for (int i = 0; i < numNests; i++) {
			double[] temp = new double[locSize];
			Collections.shuffle(range1);
			Collections.shuffle(range2);
			for (int j = 0; j < locSize; j++)
				temp[j] = r.nextDouble()
						* (nests[range1.get(i)].getLocation()[j] - nests[range2.get(i)].getLocation()[j]);
			stepsize[i] = temp;
		}
		for (int i = 0; i < numNests; i++) {
			double[] nestLocation = nests[i].getLocation();
			for (int j = 0; j < locSize; j++)
				nestLocation[j] = nestLocation[j] + stepsize[i][j]
						* discoveredBooleans[i];
			for (int j = 0; j < locSize; j++) {
				if (nestLocation[j] < low[j])
					nestLocation[j] = low[j];
				if (nestLocation[j] > up[j])
					nestLocation[j] = up[j];
			}
		}
	}

	@Override
	protected double[] doStep(int currentIteration, double previousFitness) {
		getCuckoos();
		getBestNest();
		emptyNests();
		getBestNest();
		if (fitness.fitnessCompare(currentBest, best) > 0) {
			best = currentBest;
			bestLoc = currentBestLoc.clone();
		}
		return bestLoc.clone();
	}

}


text:
package org.apache.giraph.examples;

import org.apache.hadoop.io.LongWritable;

import org.apache.giraph.graph.Aggregator;

/**
 * Aggregator for summing up values.
 */
public class LongSumAggregator implements Aggregator<LongWritable> {
    /** Internal sum */
    private long sum = 0;

    public void aggregate(long value) {
        sum += value;
    }

    @Override
    public void aggregate(LongWritable value) {
        sum += value.get();
    }

    @Override
    public void setAggregatedValue(LongWritable value) {
        sum = value.get();
    }

    @Override
    public LongWritable getAggregatedValue() {
        return new LongWritable(sum);
    }

    @Override
    public LongWritable createAggregatedValue() {
        return new LongWritable();
    }
}


text:
require 'right_scraper/resources'

require 'digest/sha1'
require 'uri'

module RightScraper

  module Resources

    # Localized representation of a resource.  Contains the resource
    # contents, and the metadata as a hash. A resource at its core is any
    # abstraction that is statically represented by a set of files and
    # directories and metadata.
    #
    # The JSON metadata for the resource is in #metadata, and the
    # manifest is in #manifest.
    class Base

      # (Repositories::Base) Repository the resource was fetched from.
      attr_reader :repository

      # (Hash) Metadata from the resource.
      attr_accessor :metadata

      # (Hash) Manifest for resource.  A hash of path => SHA-1 digests.
      attr_accessor :manifest

      # (String) Position in the repository.
      attr_accessor :pos

      # Create a new resource from the given parameters.
      #
      # === Parameters
      # repo(Repositories::Base):: Repository containing this resource
      def initialize(repo, pos)
        @repository = repo
        @pos = pos
      end

      # Resource hash
      #
      # === Return
      # hash(String):: Hexadecimal value that uniquely identifies this resource
      def resource_hash
        Digest::SHA1.hexdigest("#{PROTOCOL_VERSION}\000#{@repository.checkout_hash}\000#{@pos}")
      end

    end
  end
end


text:
import { postalCodeTestSet01 } from './mock-response';
import { PostalCode } from './postal-code';

describe('PostalCode', () => {

    it('should create an empty PostalCode', () => {
        const pc = new PostalCode()
        expect(pc).toBeTruthy();
        expect(pc.code).toBeUndefined();
        expect(pc.city).toBeUndefined();
    });

    it('should create a PostalCode from another one', () => {
        const pc = new PostalCode(postalCodeTestSet01[0]);
        expect(pc).toEqual(postalCodeTestSet01[0]);
        expect(pc).not.toBe(postalCodeTestSet01[0]);
    });

    it('should return a string', () => {
        const pc = postalCodeTestSet01[0];
        expect(pc.toString()).toBe(JSON.stringify(pc));
    });

    it('should copy (deep copy) a PostalCode', () => {
        const pc: PostalCode = postalCodeTestSet01[0].copy();
        expect(pc).toEqual(postalCodeTestSet01[0]);
        expect(pc).not.toBe(postalCodeTestSet01[0]);
    });

    it('should transform an output string {Code} / {City} into a valid PostalCode', () => {
        const value = `${postalCodeTestSet01[0].code} / ${postalCodeTestSet01[0].city}`;
        expect(PostalCode.fromValue(value)).toEqual(postalCodeTestSet01[0],
            'PostalCode.fromValue(value) and postalCodeTestSet01[0] should be equal');
    });

    it('should transform an output string {City} / {Code} into a valid PostalCode', () => {
        const value = `${postalCodeTestSet01[0].city} / ${postalCodeTestSet01[0].code}`;
        expect(PostalCode.fromValue(value, 'city', 'code')).toEqual(postalCodeTestSet01[0],
            'PostalCode.fromValue(value) and postalCodeTestSet01[0] should be equal');
    });

    it('it should fail to call the method PostalCode.fromValue() with invalid parameters', () => {
        const value = `${postalCodeTestSet01[0].city} / ${postalCodeTestSet01[0].code}`;

        expect(() => PostalCode.fromValue(value, 'city', 'city')).toThrowError('The parameter first and second must not be equal');
        expect(() => PostalCode.fromValue(value, 'code', 'code')).toThrowError('The parameter first and second must not be equal');
        expect(() => PostalCode.fromValue(value, '', 'code')).toThrowError('The parameter first and second must not be equal');
        expect(() => PostalCode.fromValue(value, 'city', '')).toThrowError('The parameter first and second must not be equal');
        expect(() => PostalCode.fromValue(value, 'spongebob', ''))
            .toThrowError('The parameter first of fromValue() is not \'code\' or \'city\'');
        expect(() => PostalCode.fromValue(value, '', 'spongebob'))
            .toThrowError('The second argument of fromValue() is not \'code\' or \'city\'');

        expect(() => PostalCode.fromValue(value, 'code', 'city'))
            .toThrowError(SyntaxError);
    });
});


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
 * The contents of this file are subject to the Mozilla Public
 * License Version 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 *
 * The Original Code is the Netscape Portable Runtime (NSPR).
 *
 * The Initial Developer of the Original Code is Netscape
 * Communications Corporation.  Portions created by Netscape are
 * Copyright (C) 1998-2000 Netscape Communications Corporation.  All
 * Rights Reserved.
 *
 * Contributor(s):
 *   Roland Mainz <roland mainz@informatik.med.uni-giessen.de>
 *
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL"), in which case the provisions of the GPL are applicable
 * instead of those above.  If you wish to allow use of your
 * version of this file only under the terms of the GPL and not to
 * allow others to use your version of this file under the MPL,
 * indicate your decision by deleting the provisions above and
 * replace them with the notice and other provisions required by
 * the GPL.  If you do not delete the provisions above, a recipient
 * may use your version of this file under either the MPL or the
 * GPL.
 */

#ifndef _plstr_h
#define _plstr_h

/*
 * plstr.h
 *
 * This header file exports the API to the NSPR portable library or string-
 * handling functions.
 *
 * This API was not designed as an "optimal" or "ideal" string library; it
 * was based on the good ol' unix string.3 functions, and was written to
 *
 *  1) replace the libc functions, for cross-platform consistancy,
 *  2) complete the API on platforms lacking common functions (e.g.,
 *     strcase*), and
 *  3) to implement some obvious "closure" functions that I've seen
 *     people hacking around in our code.
 *
 * Point number three largely means that most functions have an "strn"
 * limited-length version, and all comparison routines have a non-case-
 * sensitive version available.
 */

#include "prtypes.h"

PR_BEGIN_EXTERN_C
/*
 * PL_strlen
 *
 * Returns the length of the provided string, not including the trailing '\0'.
 */

PR_EXTERN(PRUint32)
PL_strlen(const char *str);

/*
 * PL_strnlen
 *
 * Returns the length of the provided string, not including the trailing '\0',
 * up to the indicated maximum.  The string will not be examined beyond the
 * maximum; if no terminating '\0' is found, the maximum will be returned.
 */

PR_EXTERN(PRUint32)
PL_strnlen(const char *str, PRUint32 max);

/*
 * PL_strcpy
 *
 * Copies the source string, up to and including the trailing '\0', into the
 * destination buffer.  It does not (can not) verify that the destination
 * buffer is large enough.  It returns the "dest" argument.
 */

PR_EXTERN(char *)
PL_strcpy(char *dest, const char *src);

/*
 * PL_strncpy
 *
 * Copies the source string into the destination buffer, up to and including
 * the trailing '\0' or up to and including the max'th character, whichever
 * comes first.  It does not (can not) verify that the destination buffer is
 * large enough.  If the source string is longer than the maximum length,
 * the result will *not* be null-terminated (JLRU).
 */

PR_EXTERN(char *)
PL_strncpy(char *dest, const char *src, PRUint32 max);

/*
 * PL_strncpyz
 *
 * Copies the source string into the destination buffer, up to and including
 * the trailing '\0' or up but not including the max'th character, whichever
 * comes first.  It does not (can not) verify that the destination buffer is
 * large enough.  The destination string is always terminated with a '\0',
 * unlike the traditional libc implementation.  It returns the "dest" argument.
 *
 * NOTE: If you call this with a source "abcdefg" and a max of 5, the
 * destination will end up with "abcd\0" (i.e., it's strlen length will be 4)!
 *
 * This means you can do this:
 *
 *     char buffer[ SOME_SIZE ];
 *     PL_strncpyz(buffer, src, sizeof(buffer));
 *
 * and the result will be properly terminated.
 */

PR_EXTERN(char *)
PL_strncpyz(char *dest, const char *src, PRUint32 max);

/*
 * PL_strdup
 *
 * Returns a pointer to a malloc'd extent of memory containing a duplicate
 * of the argument string.  The size of the allocated extent is one greater
 * than the length of the argument string, because of the terminator.  A
 * null argument, like a zero-length argument, will result in a pointer to
 * a one-byte extent containing the null value.  This routine returns null
 * upon malloc failure.
 */

PR_EXTERN(char *)
PL_strdup(const char *s);

/*
 * PL_strfree
 *
 * Free memory allocated by PL_strdup
 */

PR_EXTERN(void)
PL_strfree(char *s);

/*
 * PL_strndup
 *
 * Returns a pointer to a malloc'd extent of memory containing a duplicate
 * of the argument string, up to the maximum specified.  If the argument
 * string has a length greater than the value of the specified maximum, the
 * return value will be a pointer to an extent of memory of length one
 * greater than the maximum specified.  A null string, a zero-length string,
 * or a zero maximum will all result in a pointer to a one-byte extent
 * containing the null value.  This routine returns null upon malloc failure.
 */

PR_EXTERN(char *)
PL_strndup(const char *s, PRUint32 max);

/*
 * PL_strcat
 *
 * Appends a copy of the string pointed to by the second argument to the
 * end of the string pointed to by the first.  The destination buffer is
 * not (can not be) checked for sufficient size.  A null destination
 * argument returns null; otherwise, the first argument is returned.
 */

PR_EXTERN(char *)
PL_strcat(char *dst, const char *src);

/*
 * PL_strncat
 *
 * Appends a copy of the string pointed to by the second argument, up to
 * the maximum size specified, to the end of the string pointed to by the
 * first.  The destination buffer is not (can not be) checked for sufficient
 * size.  A null destination argument returns null; otherwise, the first
 * argument is returned.  If the maximum size limits the copy, then the
 * result will *not* be null-terminated (JLRU).  A null destination
 * returns null; otherwise, the destination argument is returned.
 */

PR_EXTERN(char *)
PL_strncat(char *dst, const char *src, PRUint32 max);

/*
 * PL_strcatn
 *
 * Appends a copy of the string pointed to by the third argument, to the
 * end of the string pointed to by the first.  The second argument specifies
 * the maximum size of the destination buffer, including the null termination.
 * If the existing string in dst is longer than the max, no action is taken.
 * The resulting string will be null-terminated.  A null destination returns
 * null; otherwise, the destination argument is returned.
 */

PR_EXTERN(char *)
PL_strcatn(char *dst, PRUint32 max, const char *src);

/*
 * PL_strcmp
 *
 * Returns an integer, the sign of which -- positive, zero, or negative --
 * reflects the lexical sorting order of the two strings indicated.  The
 * result is positive if the first string comes after the second.  The
 * NSPR implementation is not i18n.
 */

PR_EXTERN(PRIntn)
PL_strcmp(const char *a, const char *b);

/*
 * PL_strncmp
 *
 * Returns an integer, the sign of which -- positive, zero, or negative --
 * reflects the lexical sorting order of the two strings indicated, up to
 * the maximum specified.  The result is positive if the first string comes
 * after the second.  The NSPR implementation is not i18n.  If the maximum
 * is zero, only the existance or non-existance (pointer is null) of the
 * strings is compared.
 */

PR_EXTERN(PRIntn)
PL_strncmp(const char *a, const char *b, PRUint32 max);

/*
 * PL_strcasecmp
 *
 * Returns an integer, the sign of which -- positive, zero or negative --
 * reflects the case-insensitive lexical sorting order of the two strings
 * indicated.  The result is positive if the first string comes after the
 * second.  The NSPR implementation is not i18n.
 */

PR_EXTERN(PRIntn)
PL_strcasecmp(const char *a, const char *b);

/*
 * PL_strncasecmp
 *
 * Returns an integer, the sign of which -- positive, zero or negative --
 * reflects the case-insensitive lexical sorting order of the first n characters
 * of the two strings indicated.  The result is positive if the first string comes
 * after the second.  The NSPR implementation is not i18n.
 */

PR_EXTERN(PRIntn)
PL_strncasecmp(const char *a, const char *b, PRUint32 max);

/*
 * PL_strchr
 *
 * Returns a pointer to the first instance of the specified character in the
 * provided string.  It returns null if the character is not found, or if the
 * provided string is null.  The character may be the null character.
 */

PR_EXTERN(char *)
PL_strchr(const char *s, char c);

/*
 * PL_strrchr
 *
 * Returns a pointer to the last instance of the specified character in the
 * provided string.  It returns null if the character is not found, or if the
 * provided string is null.  The character may be the null character.
 */

PR_EXTERN(char *)
PL_strrchr(const char *s, char c);

/*
 * PL_strnchr
 *
 * Returns a pointer to the first instance of the specified character within the
 * first n characters of the provided string.  It returns null if the character
 * is not found, or if the provided string is null.  The character may be the
 * null character.
 */

PR_EXTERN(char *)
PL_strnchr(const char *s, char c, PRUint32 n);

/*
 * PL_strnrchr
 *
 * Returns a pointer to the last instance of the specified character within the
 * first n characters of the provided string.  It returns null if the character is
 * not found, or if the provided string is null.  The character may be the null
 * character.
 */

PR_EXTERN(char *)
PL_strnrchr(const char *s, char c, PRUint32 n);

/*
 * NOTE: Looking for strcasechr, strcaserchr, strncasechr, or strncaserchr?
 * Use strpbrk, strprbrk, strnpbrk or strnprbrk.
 */

/*
 * PL_strpbrk
 *
 * Returns a pointer to the first instance in the first string of any character
 * (not including the terminating null character) of the second string.  It returns
 * null if either string is null.
 */

PR_EXTERN(char *)
PL_strpbrk(const char *s, const char *list);

/*
 * PL_strprbrk
 *
 * Returns a pointer to the last instance in the first string of any character
 * (not including the terminating null character) of the second string.  It returns
 * null if either string is null.
 */

PR_EXTERN(char *)
PL_strprbrk(const char *s, const char *list);

/*
 * PL_strnpbrk
 *
 * Returns a pointer to the first instance (within the first n characters) of any
 * character (not including the terminating null character) of the second string.
 * It returns null if either string is null.
 */

PR_EXTERN(char *)
PL_strnpbrk(const char *s, const char *list, PRUint32 n);

/*
 * PL_strnprbrk
 *
 * Returns a pointer to the last instance (within the first n characters) of any
 * character (not including the terminating null character) of the second string.
 * It returns null if either string is null.
 */

PR_EXTERN(char *)
PL_strnprbrk(const char *s, const char *list, PRUint32 n);

/*
 * PL_strstr
 *
 * Returns a pointer to the first instance of the little string within the
 * big one.  It returns null if either string is null.
 */

PR_EXTERN(char *)
PL_strstr(const char *big, const char *little);

/*
 * PL_strrstr
 *
 * Returns a pointer to the last instance of the little string within the big one.
 * It returns null if either string is null.
 */

PR_EXTERN(char *)
PL_strrstr(const char *big, const char *little);

/*
 * PL_strnstr
 *
 * Returns a pointer to the first instance of the little string within the first
 * n characters of the big one.  It returns null if either string is null.  It
 * returns null if the length of the little string is greater than n.
 */

PR_EXTERN(char *)
PL_strnstr(const char *big, const char *little, PRUint32 n);

/*
 * PL_strnrstr
 *
 * Returns a pointer to the last instance of the little string within the first
 * n characters of the big one.  It returns null if either string is null.  It
 * returns null if the length of the little string is greater than n.
 */

PR_EXTERN(char *)
PL_strnrstr(const char *big, const char *little, PRUint32 max);

/*
 * PL_strcasestr
 *
 * Returns a pointer to the first instance of the little string within the big one,
 * ignoring case.  It returns null if either string is null.
 */

PR_EXTERN(char *)
PL_strcasestr(const char *big, const char *little);

/*
 * PL_strcaserstr
 *
 * Returns a pointer to the last instance of the little string within the big one,
 * ignoring case.  It returns null if either string is null.
 */

PR_EXTERN(char *)
PL_strcaserstr(const char *big, const char *little);

/*
 * PL_strncasestr
 *
 * Returns a pointer to the first instance of the listtle string within the first
 * n characters of the big one, ignoring case.  It returns null if either string is
 * null.  It returns null if the length of the little string is greater than n.
 */

PR_EXTERN(char *)
PL_strncasestr(const char *big, const char *little, PRUint32 max);

/*
 * PL_strncaserstr
 *
 * Returns a pointer to the last instance of the little string within the first
 * n characters of the big one, ignoring case.  It returns null if either string is
 * null.  It returns null if the length of the little string is greater than n.
 */

PR_EXTERN(char *)
PL_strncaserstr(const char *big, const char *little, PRUint32 max);

/*
 * PL_strtok_r
 *
 * Splits the string s1 into tokens, separated by one or more characters
 * from the separator string s2.  The argument lasts points to a
 * user-supplied char * pointer in which PL_strtok_r stores information
 * for it to continue scanning the same string.
 *
 * In the first call to PL_strtok_r, s1 points to a string and the value
 * of *lasts is ignored.  PL_strtok_r returns a pointer to the first
 * token, writes '\0' into the character following the first token, and
 * updates *lasts.
 *
 * In subsequent calls, s1 is null and lasts must stay unchanged from the
 * previous call.  The separator string s2 may be different from call to
 * call.  PL_strtok_r returns a pointer to the next token in s1.  When no
 * token remains in s1, PL_strtok_r returns null.
 */

PR_EXTERN(char *)
PL_strtok_r(char *s1, const char *s2, char **lasts);

/*
 * Things not (yet?) included: strspn/strcspn, strsep.
 * memchr, memcmp, memcpy, memccpy, index, rindex, bcmp, bcopy, bzero.
 * Any and all i18n/l10n stuff.
 */

PR_END_EXTERN_C

#endif /* _plstr_h */


text:
<?php

use Illuminate\Database\Seeder;
use App\User;

class UsersTableSeeder extends Seeder {

  public function run()
  {
      DB::table('users')->delete();

      User::create(array(
          'username' => 'julien',
          'password' => Hash::make('capucin'),
		  'email' => 'mialon.julien@gmail.com'
      ));

      User::create(array(
          'username' => 'indiarose',
          'password' => Hash::make('imaginecup'),
		  'email' => 'equipe.indiarose@gmail.com'
      ));
  }

}


text:
namespace Morgados.StateMachineExploration.Tests.Runtime
{
    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using FakeItEasy;
    using Morgados.StateMachines.Runtime;
    using Xunit;

    public class RuntimeStateBaseTests
    {
        [Fact]
        public async Task ExecuteAsync_WithoutCancellation_RunsEnterAndExitActions()
        {
            var tracker = new TestTracker();

            var state = A.Fake<RuntimeStateBase>(builder =>
                builder.WithArgumentsForConstructor(new object[]
                    {
                                "test",
                                tracker.StateEnterAction,
                                tracker.StateExitAction,
                                tracker.StateCanceledAction,
                    })
                .CallsBaseMethods());

            await state.ExecuteAsync(CancellationToken.None);

            Assert.Equal(">test;<test;", tracker.ToString());
        }

        [Fact]
        public async Task ExecuteAsync_WithoutCancellationAndNonTargettedTransitions_RunsEnterAndExecutesTransitionsUntilNullTransitionAndExitActionsAndReturnsNull()
        {
            var tracker = new TestTracker();

            var nonTargetedTransition = new RuntimeTransition("NonTargeted", null, tracker.TransitionAction, null);

            var state = A.Fake<RuntimeStateBase>(builder =>
                builder
                    .WithArgumentsForConstructor(new object[]
                        {
                            "test",
                            tracker.StateEnterAction,
                            tracker.StateExitAction,
                            tracker.StateCanceledAction,
                        })
                    .CallsBaseMethods());

            A.CallTo(state)
                .Where(call => call.Method.Name == "ExecuteStepAsync")
                .WithReturnType<Task<RuntimeTransition>>()
                .ReturnsNextFromSequence(nonTargetedTransition, nonTargetedTransition, null);

            var actual = await state.ExecuteAsync(CancellationToken.None);

            Assert.Equal(null, actual);
            Assert.Equal(">test;@test;@test;<test;", tracker.ToString());
        }

        [Fact]
        public async Task ExecuteAsync_WithoutCancellationAndNonTargettedTransitions_RunsEnterAndExecutesTransitionsUntilTargettedTransitionAndExitActionsAndReturnsTargettedTransitionWithoutExecuting()
        {
            var tracker = new TestTracker();

            var targetedTransition = new RuntimeTransition("Targeted", A.Fake<ITransitionTarget>(), tracker.TransitionAction, null);
            var nonTargetedTransition = new RuntimeTransition("NonTargeted", null, tracker.TransitionAction, null);

            var state = A.Fake<RuntimeStateBase>(builder =>
                builder
                    .WithArgumentsForConstructor(new object[]
                        {
                            "test",
                            tracker.StateEnterAction,
                            tracker.StateExitAction,
                            tracker.StateCanceledAction,
                        })
                    .CallsBaseMethods());

            A.CallTo(state)
                .Where(call => call.Method.Name == "ExecuteStepAsync")
                .WithReturnType<Task<RuntimeTransition>>()
                .ReturnsNextFromSequence(nonTargetedTransition, nonTargetedTransition, targetedTransition);

            var actual = await state.ExecuteAsync(CancellationToken.None);

            Assert.Equal(targetedTransition, actual);
            Assert.Equal(">test;@test;@test;<test;", tracker.ToString());
        }

        [Fact]
        public async Task ExecuteAsync_CanceledBeforeExecution_RunsNodActionAndThrowsOperationCanceledException()
        {
            var tracker = new TestTracker();

            using (var cts = new CancellationTokenSource())
            {
                cts.Cancel();

                var state = A.Fake<RuntimeStateBase>(builder =>
                    builder
                        .WithArgumentsForConstructor(new object[]
                            {
                                "test",
                                tracker.StateEnterAction,
                                tracker.StateExitAction,
                                tracker.StateCanceledAction,
                            })
                        .CallsBaseMethods());

                await Assert.ThrowsAsync<OperationCanceledException>(async () => await state.ExecuteAsync(cts.Token));
            }

            Assert.Equal(string.Empty, tracker.ToString());
        }

        [Fact]
        public async Task ExecuteAsync_CanceledDuringEnter_RunsEnterAndCanceledActionsAndThrowsOperationCanceledException()
        {
            var tracker = new TestTracker();

            using (var cts = new CancellationTokenSource())
            {
                var state = A.Fake<RuntimeStateBase>(builder =>
                    builder
                        .WithArgumentsForConstructor(new object[]
                            {
                                "test",
                                new Func<string, Task>(async s =>
                                {
                                    await tracker.StateEnterAction(s);
                                    cts.Cancel();
                                }),
                                tracker.StateExitAction,
                                tracker.StateCanceledAction,
                            })
                        .CallsBaseMethods());

                await Assert.ThrowsAsync<OperationCanceledException>(async () => await state.ExecuteAsync(cts.Token));
            }

            Assert.Equal(">test;!test;", tracker.ToString());
        }

        [Fact]
        public async Task ExecuteAsync_CanceledDuringExit_RunsEnterAndExitActionsAndThrowsOperationCanceledException()
        {
            var tracker = new TestTracker();

            using (var cts = new CancellationTokenSource())
            {
                var state = A.Fake<RuntimeStateBase>(builder =>
                    builder
                        .WithArgumentsForConstructor(new object[]
                            {
                                "test",
                                tracker.StateEnterAction,
                                new Func<string, Task>(async s =>
                                {
                                    await tracker.StateExitAction(s);
                                    cts.Cancel();
                                }),
                                tracker.StateCanceledAction,
                            })
                        .CallsBaseMethods());

                await Assert.ThrowsAsync<OperationCanceledException>(async () => await state.ExecuteAsync(cts.Token));
            }

            Assert.Equal(">test;<test;", tracker.ToString());
        }

        [Fact]
        public async Task ExecuteAsync_WithCancellationDuringExecute_RunsEnterAndExitActionsAndThrowsOperationCanceledException()
        {
            var tracker = new TestTracker();

            using (var cts = new CancellationTokenSource())
            {
                var state = A.Fake<RuntimeStateBase>(builder =>
                    builder
                        .WithArgumentsForConstructor(new object[]
                            {
                                "test",
                                tracker.StateEnterAction,
                                tracker.StateExitAction,
                                tracker.StateCanceledAction,
                            })
                        .CallsBaseMethods());

                A.CallTo(state)
                    .Where(call => call.Method.Name == "ExecuteStepAsync")
                    .WithReturnType<Task<RuntimeTransition>>()
                    .Invokes(() => cts.Cancel());

                await Assert.ThrowsAsync<OperationCanceledException>(async () => await state.ExecuteAsync(cts.Token));
            }

            Assert.Equal(">test;!test;", tracker.ToString());
        }

        [Fact]
        public async Task ExecuteAsync_ExecutingState_ThrowsInvalidOperationExceptionAsync()
        {
            var tracker = new TestTracker();

            var tcs = new TaskCompletionSource<RuntimeTransition>();

            var state = A.Fake<RuntimeStateBase>(builder =>
                builder
                    .WithArgumentsForConstructor(new object[]
                        {
                            "test",
                            tracker.StateEnterAction,
                            tracker.StateExitAction,
                            tracker.StateCanceledAction,
                        })
                    .CallsBaseMethods());

            A.CallTo(state)
                .Where(call => call.Method.Name == "ExecuteStepAsync")
                .WithReturnType<Task<RuntimeTransition>>()
                .Returns(tcs.Task);

            var task = state.ExecuteAsync(CancellationToken.None);

            await Assert.ThrowsAsync<InvalidOperationException>(() => state.ExecuteAsync(CancellationToken.None));

            tcs.SetResult(null);

            await task;
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace EdmondsCommerce\DoctrineStaticMeta\Tests\Large\C\Entity\Embeddable\Traits\Geo;

use EdmondsCommerce\DoctrineStaticMeta\Entity\DataTransferObjects\AbstractEntityUpdateDto;
use EdmondsCommerce\DoctrineStaticMeta\Entity\Embeddable\Interfaces\Geo\HasAddressEmbeddableInterface;
use EdmondsCommerce\DoctrineStaticMeta\Entity\Embeddable\Interfaces\Objects\Geo\AddressEmbeddableInterface;
use EdmondsCommerce\DoctrineStaticMeta\Entity\Embeddable\Objects\Geo\AddressEmbeddable;
use EdmondsCommerce\DoctrineStaticMeta\Entity\Embeddable\Traits\Geo\HasAddressEmbeddableTrait;
use EdmondsCommerce\DoctrineStaticMeta\Tests\Assets\AbstractLargeTest;

/**
 * @large
 * @covers \EdmondsCommerce\DoctrineStaticMeta\Entity\Embeddable\Traits\Geo\HasAddressEmbeddableTrait
 */
class HasAddressEmbeddableTraitLargeTest extends AbstractLargeTest
{
    public const  WORK_DIR    = self::VAR_PATH .
                                '/' .
                                self::TEST_TYPE_LARGE .
                                '/HasAddressEmbeddableTraitLargeTest';
    private const TEST_ENTITY = self::TEST_PROJECT_ROOT_NAMESPACE . '\\Entities\\Place';
    protected static $buildOnce = true;
    private $entityFqn;

    public function setup()
    {
        parent::setUp();
        if (false === self::$built) {
            $this->getEntityGenerator()->generateEntity(self::TEST_ENTITY);
            $this->getEntityEmbeddableSetter()
                 ->setEntityHasEmbeddable(self::TEST_ENTITY, HasAddressEmbeddableTrait::class);
        }
        $this->setupCopiedWorkDirAndCreateDatabase();
        $this->recreateDtos();
        $this->entityFqn = $this->getCopiedFqn(self::TEST_ENTITY);
    }

    /**
     * @test
     * @large
     * @SuppressWarnings(PHPMD.StaticAccess)
     */
    public function theEntityCanBeSavedAndLoadedWithCorrectValuesWithAnAssocArray(): void
    {
        /**
         * @var HasAddressEmbeddableInterface $entity
         */
        $entity = $this->createEntity($this->entityFqn);
        $entity->update(
            new class ($this->entityFqn, $entity->getId()) extends AbstractEntityUpdateDto
            {
                public function getAddressEmbeddable(): AddressEmbeddableInterface
                {
                    return AddressEmbeddable::create(
                        [
                            AddressEmbeddableInterface::EMBEDDED_PROP_HOUSE_NUMBER => '1',
                            AddressEmbeddableInterface::EMBEDDED_PROP_HOUSE_NAME   => '',
                            AddressEmbeddableInterface::EMBEDDED_PROP_STREET       => 'streetname',
                            AddressEmbeddableInterface::EMBEDDED_PROP_CITY         => 'cityname',
                            AddressEmbeddableInterface::EMBEDDED_PROP_POSTAL_CODE  => 'ABC 123',
                            AddressEmbeddableInterface::EMBEDDED_PROP_POSTAL_AREA  => 'county',
                            AddressEmbeddableInterface::EMBEDDED_PROP_COUNTRY_CODE => 'UK',
                        ]
                    );
                }
            }
        );

        $this->getEntitySaver()->save($entity);

        $loaded = $this->getRepositoryFactory()
                       ->getRepository($this->entityFqn)
                       ->findAll()[0];
        self::assertSame($entity, $loaded);
    }

    /**
     * @test
     * @large
     * @covers \EdmondsCommerce\DoctrineStaticMeta\Entity\Embeddable\Traits\Geo\HasAddressEmbeddableTrait
     * @SuppressWarnings(PHPMD.StaticAccess)
     */
    public function theEntityCanBeSavedAndLoadedWithCorrectValuesWithAnArray(): void
    {
        /**
         * @var HasAddressEmbeddableInterface $entity
         */
        $entity = $this->createEntity($this->entityFqn);
        $entity->update(
            new class ($this->entityFqn, $entity->getId()) extends AbstractEntityUpdateDto
            {
                public function getAddressEmbeddable(): AddressEmbeddableInterface
                {
                    return AddressEmbeddable::create(
                        [
                            '1',
                            '',
                            'streetname',
                            'cityname',
                            'ABC 123',
                            'county',
                            'UK',
                        ]
                    );
                }
            }
        );

        $this->getEntitySaver()->save($entity);

        $loaded = $this->getRepositoryFactory()
                       ->getRepository($this->entityFqn)
                       ->findAll()[0];
        self::assertSame($entity, $loaded);
    }
}


text:
package org.eclipse.jetty.nosql.memcached;

public class OrphanedSessionTest extends AbstractMemcachedOrphanedSessionTest
{
}


text:
@interface UIImageView (VT)
- (void)setPath:(NSString *)path;

- (void)setHighlightedPath:(NSString *)path;
@end


text:
'use strict';

module.exports = function exported(_, async, Rx) {
	return function viewRegistrar(views, done, prior) {
		var api = this;

		async.series([
			async.apply(prior, views),
			async.apply(addViews, api, _, Rx, getPattern.bind(null, _), views)
		], done);
	};
};

function addViews(api, _, Rx, handler, views, done) {
	Rx.Observable
		.from(views)
		.filter(hasPatternUri)
		.select(getPatternUri)
		.distinct()
		.subscribe(
			onNext.bind(null, api, _, handler),
			done,
			done
		);
}

function getPattern(_, uri, routeObj) {
	return _.assign({}, {uri: uri}, routeObj.params);
}

function hasPatternUri(view) {
	return view && view.pattern && view.pattern.uri;
}

function getPatternUri(view) {
	return view.pattern.uri;
}

function onNext(api, _, handler, uri) {
	api.router.add([{path: uri, handler: handler.bind(null, uri)}]);
}


text:
<?php

namespace VersionControl\GithubIssueBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use VersionControl\GitControlBundle\Entity\ProjectIssueIntegrator;

/**
 * Project Issue Integrator Entity.
 *
 *
 * @ORM\Table(name="project_issue_integrator_github")
 * @ORM\Entity
 */
class ProjectIssueIntegratorGithub extends ProjectIssueIntegrator
{
    /**
     * @var string
     *
     * @ORM\Column(name="repo_name", type="string", length=255, nullable=true)
     */
    private $repoName;

    /**
     * @var string
     *
     * @ORM\Column(name="owner_name", type="string", length=255, nullable=true)
     */
    private $ownerName;

    /**
     * @var string
     *
     * @ORM\Column(name="api_token", type="string", length=255, nullable=true)
     */
    private $apiToken;

    /**
     * Constructor.
     */
    public function __construct()
    {
    }

    /**
     * Git Respository Name.
     *
     * @return string
     */
    public function getRepoName()
    {
        return $this->repoName;
    }

    /**
     * Git Repository Owner Name.
     *
     * @return type
     */
    public function getOwnerName()
    {
        return $this->ownerName;
    }

    /**
     * API Token. Used to authenticate.
     *
     * @return type
     */
    public function getApiToken()
    {
        return $this->apiToken;
    }

    public function setRepoName($repoName)
    {
        $this->repoName = $repoName;

        return $this;
    }

    public function setOwnerName($ownerName)
    {
        $this->ownerName = $ownerName;

        return $this;
    }

    public function setApiToken($apiToken)
    {
        $this->apiToken = $apiToken;

        return $this;
    }
}


text:
namespace andrews_curtis
{
    // Utility function that added Relators to the passed presentation
    static void populate_child(Balanced_presentation *balanced_presentation);

    // Utility function that creates children resulting form Type I moves: [r => r^-1]
    static void create_type_one_children(const Balanced_presentation *bp,std::list<Balanced_presentation*> &children);

    // Utility function that creates children resulting form Type II moves: [r => g*r*g^-1]
    static void create_type_two_children(const Balanced_presentation *bp,std::list<Balanced_presentation*> &children);

    // Utility function that creates children resulting form Type III moves: [r => r*s]
    static void create_type_three_children(const Balanced_presentation *bp,std::list<Balanced_presentation*> &children);

    std::list<Balanced_presentation*> Balanced_presentation_nursery::get_children(const Balanced_presentation *bp)
    {
        // Create list to return
        std::list<Balanced_presentation*> children;

        // Create children resulting from Type I moves: [r => r^-1]
        create_type_one_children(bp,children);

        // Create children resulting from Type II moves: [r => g*r*g^-1]
        create_type_two_children(bp,children);

        // Create children resulting from Type III moves: [r => r*s]
        create_type_three_children(bp,children);

        // Return children
        return children;
    }

    void populate_child(Balanced_presentation *balanced_presentation)
    {
        // Loop over relators
        for(unsigned int r_index = 0; r_index < g_relators_count; ++r_index)
        {
            // Put a new Relator in the Balanced_presentation
            balanced_presentation->set_relator(new Relator(), r_index);
        }
    }

    void create_type_one_children(const Balanced_presentation *bp,std::list<Balanced_presentation*> &children)
    {
        // Loop over Relator's
        for(unsigned int index = 0; index < g_relators_count; ++index)
        {
            // New up a Balanced_presentation
            Balanced_presentation *balanced_presentation = new Balanced_presentation();

            // Populate balanced_presentation with Relators
            populate_child(balanced_presentation);

            // Copy bp to balanced_presentation
            *balanced_presentation = *bp;

            // Invert Relator at index
            balanced_presentation->get_relator(index)->invert();

            // Put balanced_presentation into children
            children.push_back(balanced_presentation);
        }
    }

    void create_type_two_children(const Balanced_presentation *bp,std::list<Balanced_presentation*> &children)
    {
        // Loop over relators
        for(unsigned int r_index = 0; r_index < g_relators_count; ++r_index)
        {
            // Loop over all generators (Note: They're 1 based, n and -n are inverses)
            for(int g_index = -g_generators_count; g_index <= g_generators_count; ++g_index)
            {
                // There is no generator 0; so, skip it
                if(0 == g_index)
                    continue;

                // New up a Balanced_presentation
                Balanced_presentation *balanced_presentation = new Balanced_presentation();

                // Populate balanced_presentation with Relators
                populate_child(balanced_presentation);

                // Copy bp to balanced_presentation
                *balanced_presentation = *bp;

                // Conjugate Relator at r_index with generator g_index
                balanced_presentation->get_relator(r_index)->conjugate(g_index);

                // Put balanced_presentation into children
                children.push_back(balanced_presentation);
            }
        }
    }

    void create_type_three_children(const Balanced_presentation *bp,std::list<Balanced_presentation*> &children)
    {
        // Loop over relators acted on
        for(unsigned int index1 = 0; index1 < g_relators_count; ++index1)
        {
            // Loop over relators acting on
            for(unsigned int index2 = 0; index2 < g_relators_count; ++index2)
            {
                // The move r_index1 => r_index1*r_index2 only occurs for index1 != index2
                if(index1 == index2)
                    continue;

                // New up a Balanced_presentation
                Balanced_presentation *balanced_presentation = new Balanced_presentation();

                // Populate balanced_presentation with Relators
                populate_child(balanced_presentation);

                // Copy bp to balanced_presentation
                *balanced_presentation = *bp;

                // Multiply Relator at index1 on the right by Relator at index2
                balanced_presentation->get_relator(index1)->multiply(balanced_presentation->get_relator(index2));

                // Put balanced_presentation into children
                children.push_back(balanced_presentation);
            }
        }
    }
}


text:
package org.stevewinfield.suja.idk.game.plugins;

import org.stevewinfield.suja.idk.Bootloader;
import org.stevewinfield.suja.idk.game.rooms.RoomInstance;
import org.stevewinfield.suja.idk.game.rooms.RoomItem;
import org.stevewinfield.suja.idk.game.rooms.RoomPlayer;
import org.stevewinfield.suja.idk.network.sessions.Session;

public class PluginHelper {
    public static Session[] getActiveSessions() {
        return Bootloader.getSessionManager().getSessions().toArray(new Session[Bootloader.getSessionManager().getSessions().size()]);
    }

    public static RoomPlayer[] getRoomPlayers(final RoomInstance room) {
        return room.getRoomPlayers().values().toArray(new RoomPlayer[room.getRoomPlayers().values().size()]);
    }

    public static RoomItem[] getRoomItems(final RoomInstance room) {
        return room.getRoomItems().values().toArray(new RoomItem[room.getRoomItems().values().size()]);
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__sizeof_double_81_bad.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__sizeof.label.xml
Template File: sources-sink-81_bad.tmpl.cpp
*/
/*
 * @description
 * CWE: 122 Heap Based Buffer Overflow
 * BadSource:  Initialize the source buffer using the size of a pointer
 * GoodSource: Initialize the source buffer using the size of the DataElementType
 * Sinks:
 *    BadSink : Print then free data
 * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
 *
 * */
#ifndef OMITBAD

#include "std_testcase.h"
#include "CWE122_Heap_Based_Buffer_Overflow__sizeof_double_81.h"

namespace CWE122_Heap_Based_Buffer_Overflow__sizeof_double_81
{

void CWE122_Heap_Based_Buffer_Overflow__sizeof_double_81_bad::action(double * data) const
{
    /* POTENTIAL FLAW: Attempt to use data, which may not have enough memory allocated */
    printDoubleLine(*data);
    free(data);
}

}
#endif /* OMITBAD */


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <parent>
        <groupId>org.apache.axis2.3rd.bundles</groupId>
        <artifactId>3rd.bundles</artifactId>
        <version>1.0.0</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>wstx-asl</artifactId>
    <packaging>bundle</packaging>
    <name>wstx-asl</name>
    <version>3.2.4</version>
    <description>
        This bundle will export packages from wstx-asl.jar
    </description>

    <dependencies>
        <dependency>
            <groupId>org.codehaus.woodstox</groupId>
            <artifactId>wstx-asl</artifactId>
            <version>${pom.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>stax</groupId>
                    <artifactId>stax-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>1.4.0</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-Version>${pom.version}</Bundle-Version>
                        <Bundle-Name>${pom.artifactId}</Bundle-Name>
                        <Bundle-Vendor>Apache Org</Bundle-Vendor>
                        <Bundle-SymbolicName>${pom.artifactId}</Bundle-SymbolicName>
                        <Fragment-Host>org.apache.geronimo.specs.geronimo-stax-api_1.0_spec</Fragment-Host>
                        <Import-Package>*;resolution:=optional</Import-Package>
                        <Embed-Dependency>wstx-asl;scope=compile|runtime;inline=true;</Embed-Dependency>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
// This file is automatically generated.

package adila.db;

/*
 * Huawei MediaPad X1 7.0
 *
 * DEVICE: hw7d501l
 * MODEL: MediaPad X1
 */
final class hw7d501l_mediapad20x1 {
    public static final String DATA = "Huawei|MediaPad X1 7.0|";
}


text:
package com.javarush.test.level14.lesson08.home02;

/* Дегустация вин
1. Создать абстрактный класс Drink с реализованным методом public void taste(), который выводит в консоль "Вкусно"
2. Создать класс Wine, который наследуется от Drink, с реализованным методом public String getHolidayName(), который возвращает строку "День рождения"
3. Создать класс BubblyWine, который наследуется от Wine, с реализованным методом public String getHolidayName(), который возвращает строку "Новый год"
4. Написать реализацию методов getDeliciousDrink, getWine, getBubblyWine
5. Каждый класс и интерфейс должны быть в отдельных файлах
6. Метод main менять нельзя!
*/

class Solution {

  public static void main(String[] args) {
    getDeliciousDrink().taste();
    System.out.println(getWine().getHolidayName());
    System.out.println(getBubblyWine().getHolidayName());
    System.out.println(getWine().getHolidayName());
  }

  private static Drink getDeliciousDrink() {
    return new Wine();
  }

  private static Wine getWine() {
    return new Wine();
  }

  private static Wine getBubblyWine() {
    return new BubblyWine();
  }
}