text:
from __future__ import print_function

import os
import sys
import time
from collections import defaultdict

import pytest
from process_tests import dump_on_error
from process_tests import TestProcess
from process_tests import wait_for_strings
from redis import StrictRedis

from redis_lock import Lock, AlreadyAcquired, NotAcquired
from redis_lock import reset_all

from conf import TIMEOUT
from conf import UDS_PATH
from conf import HELPER

@pytest.yield_fixture
def redis_server(scope='module'):
    try:
        os.unlink(UDS_PATH)
    except OSError:
        pass
    with TestProcess('redis-server', '--port', '0', '--unixsocket', UDS_PATH) as process:
        wait_for_strings(process.read, TIMEOUT, "Running")
        yield process

@pytest.fixture(scope='function')
def conn(redis_server):
    return StrictRedis(unix_socket_path=UDS_PATH)

def test_simple(redis_server):
    with TestProcess(sys.executable, HELPER, 'test_simple') as proc:
        with dump_on_error(proc.read):
            name = 'lock:foobar'
            wait_for_strings(
                proc.read, TIMEOUT,
                'Getting %r ...' % name,
                'Got lock for %r.' % name,
                'Releasing %r.' % name,
                'UNLOCK_SCRIPT not cached.',
                'DIED.',
            )

def test_no_block(conn):
    with Lock(conn, "foobar"):
        with TestProcess(sys.executable, HELPER, 'test_no_block') as proc:
            with dump_on_error(proc.read):
                name = 'lock:foobar'
                wait_for_strings(
                    proc.read, TIMEOUT,
                    'Getting %r ...' % name,
                    'Failed to get %r.' % name,
                    'acquire=>False',
                    'DIED.',
                )

def test_expire(conn):
    with Lock(conn, "foobar", expire=TIMEOUT/4):
        with TestProcess(sys.executable, HELPER, 'test_expire') as proc:
            with dump_on_error(proc.read):
                name = 'lock:foobar'
                wait_for_strings(
                    proc.read, TIMEOUT,
                    'Getting %r ...' % name,
                    'Got lock for %r.' % name,
                    'Releasing %r.' % name,
                    'UNLOCK_SCRIPT not cached.',
                    'DIED.',
                )
    lock = Lock(conn, "foobar")
    try:
        assert lock.acquire(blocking=False) == True
    finally:
        lock.release()

def test_double_acquire(conn):
    lock = Lock(conn, "foobar")
    with lock:
        pytest.raises(RuntimeError, lock.acquire)
        pytest.raises(AlreadyAcquired, lock.acquire)

def test_plain(conn):
    with Lock(conn, "foobar"):
        time.sleep(0.01)

def test_no_overlap(redis_server):
    with TestProcess(sys.executable, HELPER, 'test_no_overlap') as proc:
        with dump_on_error(proc.read):
            name = 'lock:foobar'
            wait_for_strings(proc.read, TIMEOUT, 'Getting %r ...' % name)
            wait_for_strings(proc.read, TIMEOUT, 'Got lock for %r.' % name)
            wait_for_strings(proc.read, TIMEOUT, 'Releasing %r.' % name)
            wait_for_strings(proc.read, TIMEOUT, 'UNLOCK_SCRIPT not cached.')
            wait_for_strings(proc.read, 10*TIMEOUT, 'DIED.')

            class Event(object):
                pid = start = end = '?'

                def __str__(self):
                    return "Event(%s; %r => %r)" % (self.pid, self.start, self.end)

            events = defaultdict(Event)
            for line in proc.read().splitlines():
                try:
                    pid, time, junk = line.split(' ', 2)
                    pid = int(pid)
                except ValueError:
                    continue
                if 'Got lock for' in junk:
                    events[pid].pid = pid
                    events[pid].start = time
                if 'Releasing' in junk:
                    events[pid].pid = pid
                    events[pid].end = time
            assert len(events) == 125

            for event in events.values():
                for other in events.values():
                    if other is not event:
                        try:
                            if other.start < event.start < other.end or \
                               other.start < event.end < other.end:
                                pytest.fail('%s overlaps %s' % (event, other))
                        except:
                            print("[%s/%s]" % (event, other))
                            raise

def test_reset(conn):
    with Lock(conn, "foobar") as lock:
        lock.reset()
        new_lock = Lock(conn, "foobar")
        new_lock.acquire(blocking=False)
        new_lock.release()

def test_reset_all(conn):
    lock1 = Lock(conn, "foobar1")
    lock2 = Lock(conn, "foobar2")
    lock1.acquire(blocking=False)
    lock2.acquire(blocking=False)
    reset_all(conn)
    lock1 = Lock(conn, "foobar1")
    lock2 = Lock(conn, "foobar2")
    lock1.acquire(blocking=False)
    lock2.acquire(blocking=False)
    lock1.release()
    lock2.release()

def test_owner_id(conn):
    unique_identifier = b"foobar-identifier"
    lock = Lock(conn, "foobar-tok", expire=TIMEOUT/4, id=unique_identifier)
    lock_id = lock.id
    assert lock_id == unique_identifier
    lock.acquire(blocking=False)
    assert lock.get_owner_id() == unique_identifier
    lock.release()

def test_token(conn):
    lock = Lock(conn, "foobar-tok")
    tok = lock.id
    assert conn.get(lock._name) is None
    lock.acquire(blocking=False)
    assert conn.get(lock._name) == tok

def test_bogus_release(conn):
    lock = Lock(conn, "foobar-tok")
    pytest.raises(NotAcquired, lock.release)
    lock.release(force=True)

def test_release_from_nonblocking_leaving_garbage(conn):
    for _ in range(10):
        lock = Lock(conn, 'release_from_nonblocking')
        lock.acquire(blocking=False)
        lock.release()
        assert conn.llen('lock-signal:release_from_nonblocking') == 1


text:
<form name="injectStreamForm" class="form"
      ng-submit="doInject($event)"
      novalidate>

 {{streamId}}

       Close

    <textarea class="flow-injector-input form-control" placeholder="Events injected here will be consumed by all attached programs." ng-model="userInput" ng-keyup="$event.keyCode == 13  && !$event.shiftKey? doInject($event) : null"></textarea>

      <my-file-select button-disabled="{{loading}}"
                      data-button-label="Upload"
                      on-file-select="uploadFile($files)">

      <button type="submit"
        ng-disabled="injectStreamForm.$invalid || loading"
        class="btn"
        ng-class="{'btn-primary': !injectStreamForm.$invalid && !loading }"
      >Inject</button>

</form>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

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

-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
    ">

  <!-- the test case route -->
  <camelContext id="tester" xmlns="http://camel.apache.org/schema/spring" depends-on="accounts">
    <route>
      <from uri="direct:start"/>
      <to uri="accounts:purchaseOrder"/>
    </route>
    <route>
      <from uri="accounts:invoice"/>
      <to uri="mock:results"/>
    </route>
  </camelContext>

  <!-- lets define a context component -->
  <camelContext id="accounts" xmlns="http://camel.apache.org/schema/spring">
    <route>
      <!--
        receive purchase orders, lets process it in some way then
        send an invoice to our invoice endpoint
      -->
      <from uri="direct:purchaseOrder"/>
      <setHeader headerName="received">
        <constant>true</constant>
      </setHeader>
      <to uri="direct:invoice"/>
    </route>
  </camelContext>

</beans>


text:
                <button type="button" class="share-close" data-dismiss="modal" aria-hidden="true">× Close</button>

Share this story

                    {{ COPY.share.story_summary }} {{ COPY.share.share_url }}  Copy

 Email to a friend

On Tumblr

                         Share story on Tumblr

On Facebook

                        {% for post in featured.facebook_posts %}
                        {% include '_featured_facebook_post.html' %}
                        {% endfor %}

 Share story on Facebook

On Twitter

                        {% for tweet in featured.tweets %}
                        {% include '_featured_tweet.html' %}
                        {% endfor %}

                         Share story on Twitter


text:
<?php

namespace Timsa\ControlFletesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Timsa\ControlFletesBundle\Entity\Economico;

class EconomicoController extends Controller{

	public function indexAction(){

		$socios = 		$this->getDoctrine()
							 ->getRepository('TimsaControlFletesBundle:Socio')
							 ->findAllActive();

		$economicos = $this->getDoctrine()
							->getRepository('TimsaControlFletesBundle:Economico')
							->findAll();

	   $paginator = $this->container->get('knp_paginator');

       $economicos_paginados = $paginator->paginate(
								           $economicos,
								           $this->get('request')->query->get('pagina', 1)/*page number*/,
								           16,/*limit per page*/
								           array('pageParameterName' => 'pagina',)
								       );

		return $this->render("TimsaControlFletesBundle:Economico:economicos.html.twig",
								 array(
								 		'socios' 	=> $socios,
								 		'economicos'=> $economicos_paginados
								 	 )
							);
	}

	public function ajaxSocioAction($idSocio){

		$economicos = $this->getDoctrine()
						   ->getRepository('TimsaControlFletesBundle:Economico')
						   ->getEconomicosPorSocio($idSocio);

		$socio      = $this->getDoctrine()
						   ->getRepository('TimsaControlFletesBundle:Socio')
						   ->find($idSocio);

		return $this->render("TimsaControlFletesBundle:Socio:socios.html.twig",
							array(	"economicos" => $economicos,
									"socio" => $socio,
								)
							);
	}
}


text:
'use strict';

const Sharp = require('./constructor');
[
  'input',
  'resize',
  'composite',
  'operation',
  'colour',
  'channel',
  'output',
  'utility'
].forEach(function (decorator) {
  require('./' + decorator)(Sharp);
});

module.exports = Sharp;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>My Robot</title>
    <link rel="stylesheet" href="stylesheets/normalize.css" charset="utf-8">
    <link rel="stylesheet" href="stylesheets/game.css" charset="utf-8">
    <link rel="stylesheet" href="stylesheets/custom.css" charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

Let's play tic-tac-toe!

    <button onclick= "window.location.href='index.html'">Back to home page</button>

    <button onclick= "window.location.href='game.html'">Play again!</button>


text:
<?php

class InvertedIndex extends Eloquent
{
	protected $table = 'inverted_index';

	use SoftDeletingTrait;

	protected $fillable = array
	(
		'word_id', 'picture_id'
	);
}


text:
using System.Windows;

namespace Anne.Foundation.Controls
{
    /// <summary>
    /// FileStatusMark.xaml の相互作用ロジック
    /// </summary>
    public partial class FileStatusMark
    {
#region Status
        public LibGit2Sharp.ChangeKind Status
        {
            get { return (LibGit2Sharp.ChangeKind)GetValue(StatusProperty); }
            set { SetValue(StatusProperty, value); }
        }

        public static readonly DependencyProperty StatusProperty =
            DependencyProperty.Register(
                "Status",
                typeof(LibGit2Sharp.ChangeKind),
                typeof(FileStatusMark),
                new FrameworkPropertyMetadata
                {
                    BindsTwoWayByDefault = false
                }
            );
#endregion

        public FileStatusMark()
        {
            InitializeComponent();
        }
    }
}


text:
<?php
/* @var $this UsersController */
/* @var $model Users */
/* @var $form CActiveForm */
?>

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'users-form',
	'enableAjaxValidation'=>true,
	'clientOptions'=>array('validateOnSubmit'=>true),
)); ?>

Fields with * are required.

	<?php echo $form->errorSummary($model,null,null,array('class'=>'alert alert-error')); ?>

		    <legend>Basic</legend>

				<?php echo $form->labelEx($model,'name'); ?>
				<?php echo $form->textField($model,'name',array('size'=>60,'maxlength'=>255)); ?>
				<?php echo $form->error($model,'name'); ?>

				<?php echo $form->labelEx($model,'username'); ?>
				<?php echo $form->textField($model,'username',array('size'=>60,'maxlength'=>128)); ?>
				<?php echo $form->error($model,'username'); ?>

				<?php echo $form->labelEx($model,'email'); ?>
				<?php echo $form->textField($model,'email',array('size'=>60,'maxlength'=>128)); ?>
				<?php echo $form->error($model,'email'); ?>

			<legend>Add</legend>

				<?php echo $form->labelEx($model,'birthday'); ?>
				<?php
				$this->widget("zii.widgets.jui.CJuiDatePicker",array(
						"attribute"=>"birthday",
						"model"=>$model,
						"language"=>"es",
						"options"=>array(
							"dateFormat"=>"yy-mm-dd",
							'showButtonPanel' => true,
							'changeYear' => true,
							'changeYear' => true,
							'yearRange' => '-80:-10',
							'minDate' => '-80Y',
							'maxDate' => '-10Y',
						)
					));
				?>
				<?php echo $form->error($model,'birthday'); ?>

				<?php
					$htmlOptions=array(
						"ajax"=>array(
							"url"=>$this->createUrl("citiesByCountry"),
							"type"=>"POST",
							"update"=>"#Users_cities_id",
						),
					);
				?>
				<?php echo $form->labelEx($model,'countries_id'); ?>
				<?php echo $form->dropDownList($model,'countries_id',$model->getMenuCountries(),$htmlOptions); ?>
				<?php echo $form->error($model,'countries_id'); ?>

				<?php echo $form->labelEx($model,'cities_id'); ?>
				<?php echo $form->dropDownList($model,'cities_id',$model->getMenuCities()); ?>
				<?php echo $form->error($model,'cities_id'); ?>

				<?php echo $form->checkBox($model,'status'); ?>
				<?php echo $form->labelEx($model,'status'); ?>
				<?php echo $form->error($model,'status'); ?>

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save',array('class'=>'btn btn-primary btn-large')); ?>

<?php $this->endWidget(); ?>


text:
#ifndef _WDD_MAIN_H_
#define _WDD_MAIN_H_

#include <pthread.h>
#include <syslog.h>

#include <protocol/TBinaryProtocol.h>
//#include <server/TSimpleServer.h>
#include <server/TThreadedServer.h>
#include <transport/TServerSocket.h>
#include <transport/TBufferTransports.h>
#include <thrift/concurrency/ThreadManager.h>
#include <thrift/concurrency/PosixThreadFactory.h>

#include <WDDaemon.h>
#include <WDDaemon_server.h>

using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;
using namespace ::apache::thrift::concurrency;

using boost::shared_ptr;
using namespace  ::watchdog;

void* start_watchdog_daemon(void *cls);
void  init_watchdog_daemon();

#endif //_WDD_MAIN_H_


text:
adracus.github.io
============

## Development

To start developing in the project run:

```bash
gulp serve
```

Then head to `http://localhost:3000` in your browser.

The `serve` tasks starts a static file server, which serves the AngularJS application, and a watch task which watches all files for changes and lints, builds and injects them into the index.html accordingly.

## Tests

To run tests run:

```bash
gulp test
```

**Or** first inject all test files into `karma.conf.js` with:

```bash
gulp karma-conf
```

Then you're able to run Karma directly. Example:

```bash
karma start --single-run
```

## Production ready build - a.k.a. dist

To make the app ready for deploy to production run:

```bash
gulp dist
```

Now there's a `./dist` folder with all scripts and stylesheets concatenated and minified, also third party libraries installed with bower will be concatenated and minified into `vendors.min.js` and `vendors.min.css` respectively.


text:
<?php

namespace John\SiteBundle\Controller;

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 John\AdminBundle\Entity\SubCategory;

/**
 * SubCategory controller.
 *
 * @Route("/subcategory")
 */
class SubCategoryController extends Controller {

    /**
     * Finds and displays a SubCategory entity.
     *
     * @Route("/{slug}", name="subcategory_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($slug)
    {
        $em = $this->getDoctrine()->getManager();

        $subCategory = $em->getRepository('JohnAdminBundle:SubCategory')->findOneBySlug($slug);

        $articlesBySubCategory = $this->getDoctrine()
                ->getRepository('JohnAdminBundle:Article')
                ->getArticlesBySubCategory($subCategory);

        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
                $articlesBySubCategory, $this->get('request')->query->get('page', 1)/* page number */, 6/* limit per page */
        );

        $totalPages = ceil($pagination->getTotalItemCount() / $pagination->getItemNumberPerPage());

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

        // pas d'articles, on affiche son titre et son body
        if (!$articlesBySubCategory) {
            return array(
                'subCategory' => $subCategory,
            );
        }

        // sinon, on retourne sa liste paginée d'articles
        return array(
            'subCategory' => $subCategory,
            'articles' => $pagination,
            'totalPages' => $totalPages
        );
    }

    public function subCategoriesByCategoryWithPositionAction($slug)
    {
        $em = $this->getDoctrine()->getManager();

        $category = $em->getRepository('JohnAdminBundle:Category')->findOneBySlug($slug);

        $subCategories = $this->getDoctrine()
                ->getRepository('JohnAdminBundle:SubCategory')
                ->getSubCategoriesByCategory($category);

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

        return $this->container->get('templating')
                        ->renderResponse('JohnAdminBundle:SubCategory:subCategoriesByCategoryWithPosition.html.twig', array(
                            'subCategories' => $subCategories,
                                )
        );
    }

}


text:
/*
Theme Name: AngularWordpress
Theme URI:
Author: Jhonn Rod (jhonn@outlook.com)
Author URI:
Description: AngularJS WP tema
Version: 1.1
*/

/* Sticky footer styles
-------------------------------------------------- */
html {
  position: relative;
  min-height: 100%;
}
body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
}
.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 60px;
  background-color: #f5f5f5;
}

/* Custom page CSS
-------------------------------------------------- */
/* Not required for template or sticky footer method. */

body > .container {
  padding: 60px 15px 0;
}
.container .text-muted {
  margin: 20px 0;
}

.footer > .container {
  padding-right: 15px;
  padding-left: 15px;
}


text:
/* ************************************ */
/* Define helper functions */
/* ************************************ */
function addID() {
  jsPsych.data.addDataToLastTrial({exp_id: 'flanker_with_shape_matching'})
}

function evalAttentionChecks() {
	var check_percent = 1
	if (run_attention_checks) {
		var attention_check_trials = jsPsych.data.getTrialsOfType('attention-check')
		var checks_passed = 0
		for (var i = 0; i < attention_check_trials.length; i++) {
			if (attention_check_trials[i].correct === true) {
				checks_passed += 1
			}
		}
		check_percent = checks_passed / attention_check_trials.length
	}
	return check_percent
}

function assessPerformance() {
	var experiment_data = jsPsych.data.getTrialsOfType('poldrack-single-stim')
	var missed_count = 0
	var trial_count = 0
	var rt_array = []
	var rt = 0
	var correct = 0

		//record choices participants made
	var choice_counts = {}
	choice_counts[-1] = 0
	choice_counts[77] = 0
	choice_counts[90] = 0
	for (var k = 0; k < possible_responses.length; k++) {
		choice_counts[possible_responses[k][1]] = 0
	}

	for (var i = 0; i < experiment_data.length; i++) {
		if (experiment_data[i].trial_id == 'test_trial'){
			trial_count += 1
			rt = experiment_data[i].rt
			key = experiment_data[i].key_press
			choice_counts[key] += 1
			if (rt == -1) {
				missed_count += 1
			} else {
				rt_array.push(rt)
			}

			if (key == experiment_data[i].correct_response){
				correct += 1
			}
		}
	}

	//calculate average rt
	var avg_rt = -1
	if (rt_array.length !== 0) {
		avg_rt = math.median(rt_array)
	}
	//calculate whether response distribution is okay
	var responses_ok = true
	Object.keys(choice_counts).forEach(function(key, index) {
		if (choice_counts[key] > trial_count * 0.85) {
			responses_ok = false
		}
	})
	var missed_percent = missed_count/trial_count
	var accuracy = correct / trial_count
	credit_var = (missed_percent < 0.25 && avg_rt > 200 && responses_ok && accuracy > 0.60)
	jsPsych.data.addDataToLastTrial({final_credit_var: credit_var,
									 final_missed_percent: missed_percent,
									 final_avg_rt: avg_rt,
									 final_responses_ok: responses_ok,
									 final_accuracy: accuracy})
}

var getInstructFeedback = function() {
	return '

' + feedback_instruct_text +
		'

'
}

var getFeedback = function() {
	return '

' + feedback_text + '

'
}

var randomDraw = function(lst) {
  var index = Math.floor(Math.random() * (lst.length))
  return lst[index]
}

var getPTD = function(shape_matching_condition, flanker_condition){
	var probe_i = randomDraw([1,2,3,4,5,6,7,8,9,10])
	var target_i = 0
	var distractor_i = 0
	if (shape_matching_condition[0] == 'S') {
		target_i = probe_i
		correct_response = possible_responses[0][1]
	} else {
		target_i = randomDraw([1,2,3,4,5,6,7,8,9,10].filter(function(y) {return y != probe_i}))
		correct_response = possible_responses[1][1]
	}
	//console.log('probe = ' + probe + ', target = ' + target)
	if (shape_matching_condition[1] == 'S') {
		distractor_i = target_i
	} else if (shape_matching_condition[2] == 'S') {
		distractor_i = probe_i
	} else if (shape_matching_condition[2] == 'D') {
		distractor_i = randomDraw([1,2,3,4,5,6,7,8,9,10].filter(function(y) {return $.inArray(y, [target_i, probe_i]) == -1}))
	} else if (shape_matching_condition[2] == 'N'){
		distractor_i = 'none'
	}

	if (flanker_condition == 'congruent'){
		flankers = probe_i
	} else if (flanker_condition == 'incongruent'){
		flankers = randomDraw([1,2,3,4,5,6,7,8,9,10].filter(function(y) {return y != probe_i}))

	}
	return [probe_i, target_i, distractor_i, correct_response, flankers]
}

var createTrialTypes = function(numTrialsPerBlock){
	flanker_trial_types = ['congruent','incongruent']
	shape_matching_trial_types = ['DDD','SDD','DSD','DDS','SSS','SNN','DNN']

	var stims = []
	for(var numIterations = 0; numIterations < numTrialsPerBlock/14; numIterations++){
		for (var numShapeConds = 0; numShapeConds < shape_matching_trial_types.length; numShapeConds++){
			for (var numFlankerConds = 0; numFlankerConds < flanker_trial_types.length; numFlankerConds++){

				shape_matching_condition = shape_matching_trial_types[numShapeConds]
				flanker_condition = flanker_trial_types[numFlankerConds]

				answer_arr = getPTD(shape_matching_condition, flanker_condition)

				probe = answer_arr[0]
				target = answer_arr[1]
				distractor = answer_arr[2]
				correct_response = answer_arr[3]
				flankers = answer_arr[4]

				stim = {
					flanker_condition: flanker_condition,
					shape_matching_condition: shape_matching_condition,
					probe: probe,
					target: target,
					distractor: distractor,
					flankers: flankers,
					correct_response: correct_response
					}

				stims.push(stim)
			}

		}
	}
	stims = jsPsych.randomization.repeat(stims,1)
	return stims
}

var getResponse = function() {
	return correct_response
}

var getStim = function(){
	if ((shape_matching_condition == "SNN") || (shape_matching_condition == "DNN")){

		return task_boards[0]+ preFileType + target + '_green' + fileTypePNG +
			   task_boards[1]+
			   task_boards[2]+ preFileType + flankers + '_white' + fileTypePNG +
			   task_boards[3]+ preFileType + flankers + '_white' + fileTypePNG +
			   task_boards[4]+ preFileType + probe + '_white' + fileTypePNG +
			   task_boards[5]+ preFileType + flankers + '_white' + fileTypePNG +
			   task_boards[6]+ preFileType + flankers + '_white' + fileTypePNG +
			   task_boards[7]

	} else {

		return task_boards[0]+ preFileType + target + '_green' + fileTypePNG +
			   task_boards[1]+ preFileType + distractor + '_red' + fileTypePNG +
			   task_boards[2]+ preFileType + flankers + '_white' + fileTypePNG +
			   task_boards[3]+ preFileType + flankers + '_white' + fileTypePNG +
			   task_boards[4]+ preFileType + probe + '_white' + fileTypePNG +
			   task_boards[5]+ preFileType + flankers + '_white' + fileTypePNG +
			   task_boards[6]+ preFileType + flankers + '_white' + fileTypePNG +
			   task_boards[7]
	}
}

var getMask = function(){

	stim = stims.shift()
	shape_matching_condition = stim.shape_matching_condition
	flanker_condition = stim.flanker_condition

	correct_response = stim.correct_response
	probe = stim.probe
	target = stim.target
	distractor = stim.distractor
	flankers = stim.flankers

	//console.log('shape condition = '+shape_matching_condition+', flanker_condition: '+ flanker_condition+', correct_response: '+correct_response+', probe: '+probe+', target: '+target+', distractor: '+distractor+', flankers: '+flankers)

	return task_boards[0]+ preFileType + 'mask' + fileTypePNG +
		   task_boards[1]+
		   task_boards[2]+ preFileType + 'mask' + fileTypePNG +
		   task_boards[3]+ preFileType + 'mask' + fileTypePNG +
		   task_boards[4]+ preFileType + 'mask' + fileTypePNG + '

+

' +
		   task_boards[5]+ preFileType + 'mask' + fileTypePNG +
		   task_boards[6]+ preFileType + 'mask' + fileTypePNG +
		   task_boards[7]

}

var appendData = function(){
	curr_trial = jsPsych.progress().current_trial_global
	trial_id = jsPsych.data.getDataByTrialIndex(curr_trial).trial_id

	current_trial+=1

	if (trial_id == 'practice_trial'){
		current_block = practiceCount
	} else if (trial_id == 'test_trial'){
		current_block = testCount
	}

	jsPsych.data.addDataToLastTrial({
		shape_matching_condition: shape_matching_condition,
		flanker_condition: flanker_condition,
		correct_response: correct_response,
		flankers: flankers,
		probe: probe,
		target: target,
		distractor: distractor,
		current_block: current_block,
		current_trial: current_trial
	})

	if (jsPsych.data.getDataByTrialIndex(curr_trial).key_press == correct_response){
		jsPsych.data.addDataToLastTrial({
			correct_trial: 1,
		})

	} else if (jsPsych.data.getDataByTrialIndex(curr_trial).key_press != correct_response){
		jsPsych.data.addDataToLastTrial({
			correct_trial: 0,
		})
	}

}

/* ************************************ */
/* Define experimental variables */
/* ************************************ */
// generic task variables
var sumInstructTime = 0 //ms
var instructTimeThresh = 0 ///in seconds
var credit_var = 0
var run_attention_checks = true

// task specific variables
// Set up variables for stimuli
var practice_len = 14 // must be divisible by 14
var exp_len = 280 // must be divisible by 14
var numTrialsPerBlock = 56; // divisible by 14
var numTestBlocks = exp_len / numTrialsPerBlock

var accuracy_thresh = 0.70
var missed_thresh = 0.10
var practice_thresh = 3 // 3 blocks of 14 trials

var possible_responses = [['M Key', 77],['Z Key', 90]]

var current_trial = 0
var current_block = 0

var fileTypePNG = '.png">'
var preFileType = '<img class = center src="/static/experiments/flanker_with_shape_matching/images/'

var task_boards = [['

'],['

'],['

'],['

'],['

'],['

'],['

'],['

']]

var stims = createTrialTypes(practice_len)

var prompt_text_list = '
'+
						'
Match: ' + possible_responses[0][0] + '
' +
						'
Mismatch: ' + possible_responses[1][0] + '
' +
					  '
'

var prompt_text = '
'+
					  '
Please judge if the green and the middle white shapes are the same.
' +
					  '
Same: ' + possible_responses[0][0] + '
' +
					  '
Different: ' + possible_responses[1][0] + '
' +
				  '
'

//PRE LOAD IMAGES HERE
var pathSource = "/static/experiments/flanker_with_shape_matching/images/"
var numbersPreload = ['1','2','3','4','5','6','7','8','9','10']
var colorsPreload = ['red','white','green']
var images = []

for(i = 0; i < numbersPreload.length; i++){
	for(x = 0; x < colorsPreload.length; x++){
		images.push(pathSource + numbersPreload[i] + '_' + colorsPreload[x] + '.png')
	}
}

images.push(pathSource + 'mask.png')
jsPsych.pluginAPI.preloadImages(images);
/* ************************************ */
/* Set up jsPsych blocks */
/* ************************************ */
// Set up attention check node
var attention_check_block = {
	type: 'attention-check',
	data: {
		trial_id: "attention_check"
	},
	timing_response: 180000,
	response_ends_trial: true,
	timing_post_trial: 200
}

var attention_node = {
	timeline: [attention_check_block],
	conditional_function: function() {
		return run_attention_checks
	}
}

//Set up post task questionnaire
var post_task_block = {
   type: 'survey-text',
   data: {
       exp_id: "flanker_with_shape_matching",
       trial_id: "post task questions"
   },
   questions: ['
Please summarize what you were asked to do in this task.
',
              '
Do you have any comments about this task?
'],
   rows: [15, 15],
   columns: [60,60],
   timing_response: 360000
};

var feedback_text =
	'Welcome to the experiment. This experiment will take around 15 minutes. Press enter to begin.'
var feedback_block = {
	type: 'poldrack-single-stim',
	data: {
		trial_id: "feedback_block"
	},
	choices: [13],
	stimulus: getFeedback,
	timing_post_trial: 0,
	is_html: true,
	timing_response: 180000,
	response_ends_trial: true,

};

var feedback_instruct_text =
	'Welcome to the experiment. This experiment will take around 15 minutes. Press enter to begin.'
var feedback_instruct_block = {
	type: 'poldrack-text',
	data: {
		trial_id: "instruction"
	},
	cont_key: [13],
	text: getInstructFeedback,
	timing_post_trial: 0,
	timing_response: 180000
};

/// This ensures that the subject does not read through the instructions too quickly.  If they do it too quickly, then we will go over the loop again.
var instructions_block = {
	type: 'poldrack-instructions',
	data: {
		trial_id: "instruction"
	},
	pages: [
		'
'+
			'
In this experiment you will see a row of shapes. You will always see 5 white shapes to the right, 1 green shape to the left, and sometimes, 1 red shape overlapping with the green shape.
 '+

			'
You will be asked to judge whether the green shape on the left matches the middle white shape on the right.
'+

		'
',

		'
'+

			'
If the shapes are the same, please press the '+possible_responses[0][0]+'.  If the shapes are different, press the '+possible_responses[1][0]+'.
'+

			'
You will always see multiple white shapes. Please match the green shape only to the middle white shape. Ignore the other white shapes.
'+

			'
Sometimes, you will also see a red shape near the green shape.  Ignore this red shape as well.
'+

			'
We will start practice when you finish instructions. Please make sure you understand the instructions before moving on. During practice, you will receive a reminder of the rules.  This reminder will be taken out for test.
'+
		'
'
	],
	allow_keys: false,
	show_clickable_nav: true,
	timing_post_trial: 1000
};

var instruction_node = {
	timeline: [feedback_instruct_block, instructions_block],
	/* This function defines stopping criteria */
	loop_function: function(data) {
		for (i = 0; i < data.length; i++) {
			if ((data[i].trial_type == 'poldrack-instructions') && (data[i].rt != -1)) {
				rt = data[i].rt
				sumInstructTime = sumInstructTime + rt
			}
		}
		if (sumInstructTime <= instructTimeThresh * 1000) {
			feedback_instruct_text =
				'Read through instructions too quickly.  Please take your time and make sure you understand the instructions.  Press enter to continue.'
			return true
		} else if (sumInstructTime > instructTimeThresh * 1000) {
			feedback_instruct_text = 'Done with instructions. Press enter to continue.'
			return false
		}
	}
}

var end_block = {
	type: 'poldrack-text',
	data: {
		trial_id: "end",
	},
	timing_response: 180000,
	text: '

Thanks for completing this task!

Press enter to continue.

',
	cont_key: [13],
	timing_post_trial: 0,
	on_finish: function(){
  	assessPerformance()
  	evalAttentionChecks()
  }
};

var start_test_block = {
	type: 'poldrack-text',
	data: {
		trial_id: "instruction"
	},
	timing_response: 180000,
	text: '
'+
			'
We will now start the test portion
'+

			'
You will be asked to judge whether the green shape on the left matches the middle white shape on the right..
'+

			'
If the shapes are the same, please press the '+possible_responses[0][0]+'.  If the shapes are different, press the '+possible_responses[1][0]+'.
'+

			'
You will always see multiple white shapes. Please match the green shape only to the middle white shape. Ignore the other white shapes.
'+

			'
Sometimes, you will also see a red shape near the green shape.  Ignore this red shape as well.
'+

			'
You will no longer receive the rule prompt, so remember the instructions before you continue. Press Enter to begin.
'+
		 '
',
	cont_key: [13],
	timing_post_trial: 1000,
	on_finish: function(){
		feedback_text = "We will now start the test portion. Press enter to begin."
	}
};

var rest_block = {
	type: 'poldrack-text',
	data: {
		trial_id: "instruction"
	},
	timing_response: 180000,
	text: '

Take a short break!

Press enter to continue the test.

',
	cont_key: [13],
	timing_post_trial: 1000
};

var fixation_block = {
	type: 'poldrack-single-stim',
	stimulus: '

+

',
	is_html: true,
	choices: 'none',
	data: {
		trial_id: "practice_fixation"
	},
	timing_response: 500, //500
	timing_post_trial: 0,
}

var practiceTrials = []
practiceTrials.push(feedback_block)
practiceTrials.push(instructions_block)
for (i = 0; i < practice_len; i++) {
	var mask_block = {
		type: 'poldrack-single-stim',
		stimulus: getMask,
		is_html: true,
		data: {
			"trial_id": "practice_mask",
		},
		choices: 'none',
		timing_response: 500, //500
		timing_post_trial: 0,
		response_ends_trial: false,
		prompt: prompt_text
	}

	var practice_block = {
		type: 'poldrack-categorize',
		stimulus: getStim,
		is_html: true,
		choices: [possible_responses[0][1],possible_responses[1][1]],
		key_answer: getResponse,
		data: {
			trial_id: "practice_trial"
			},
		correct_text: '

Correct!

' + prompt_text,
		incorrect_text: '

Incorrect

' + prompt_text,
		timeout_message: '

Respond Faster!

' + prompt_text,
		timing_stim: 1000, //1000
		timing_response: 2000, //2000
		timing_feedback_duration: 500, //500
		show_stim_with_feedback: false,
		timing_post_trial: 0,
		on_finish: appendData,
		prompt: prompt_text
	}
	practiceTrials.push(mask_block)
	practiceTrials.push(practice_block)
}

var practiceCount = 0
var practiceNode = {
	timeline: practiceTrials,
	loop_function: function(data){
		practiceCount += 1
		stims = createTrialTypes(practice_len)
		current_trial = 0

		var sum_rt = 0
		var sum_responses = 0
		var correct = 0
		var total_trials = 0

		for (var i = 0; i < data.length; i++){
			if (data[i].trial_id == "practice_trial"){
				total_trials+=1
				if (data[i].rt != -1){
					sum_rt += data[i].rt
					sum_responses += 1
					if (data[i].key_press == data[i].correct_response){
						correct += 1

					}
				}

			}

		}

		var accuracy = correct / total_trials
		var missed_responses = (total_trials - sum_responses) / total_trials
		var ave_rt = sum_rt / sum_responses

		feedback_text = "
Please take this time to read your feedback and to take a short break! Press enter to continue"
		feedback_text += "

Average reaction time:  " + Math.round(ave_rt) + " ms. 	Accuracy: " + Math.round(accuracy * 100)+ "%"

		if (accuracy > accuracy_thresh){
			feedback_text +=
					'

Done with this practice. Press Enter to continue.'
			stims = createTrialTypes(numTrialsPerBlock)
			return false

		} else if (accuracy < accuracy_thresh){
			feedback_text +=
					'

We are going to try practice again to see if you can achieve higher accuracy.  Remember: ' + prompt_text_list
			if (missed_responses > missed_thresh){
				feedback_text +=
						'

You have not been responding to some trials.  Please respond on every trial that requires a response.'
			}

			if (practiceCount == practice_thresh){
				feedback_text +=
					'

Done with this practice.'
					stims = createTrialTypes(numTrialsPerBlock)
					return false
			}

			feedback_text +=
				'

Redoing this practice. Press Enter to continue.'

			return true

		}

	}

}

var testTrials = []
testTrials.push(feedback_block)
testTrials.push(attention_node)
for (i = 0; i < numTrialsPerBlock; i++) {
	var mask_block = {
		type: 'poldrack-single-stim',
		stimulus: getMask,
		is_html: true,
		data: {
			"trial_id": "test_mask",
		},
		choices: 'none',
		timing_response: 500, //500
		timing_post_trial: 0,
		response_ends_trial: false
	}

	var test_block = {
		type: 'poldrack-single-stim',
		stimulus: getStim,
		is_html: true,
		data: {
			"trial_id": "test_trial",
		},
		choices: [possible_responses[0][1],possible_responses[1][1]],
		timing_stim: 1000, //1000
		timing_response: 2000, //2000
		timing_post_trial: 0,
		response_ends_trial: false,
		on_finish: appendData
	}
	testTrials.push(mask_block)
	testTrials.push(test_block)
}

var testCount = 0
var testNode = {
	timeline: testTrials,
	loop_function: function(data) {
	testCount += 1
	stims = createTrialTypes(numTrialsPerBlock)
	current_trial = 0

	var sum_rt = 0
		var sum_responses = 0
		var correct = 0
		var total_trials = 0

		for (var i = 0; i < data.length; i++){
			if (data[i].trial_id == "test_trial"){
				total_trials+=1
				if (data[i].rt != -1){
					sum_rt += data[i].rt
					sum_responses += 1
					if (data[i].key_press == data[i].correct_response){
						correct += 1

					}
				}

			}

		}

		var accuracy = correct / total_trials
		var missed_responses = (total_trials - sum_responses) / total_trials
		var ave_rt = sum_rt / sum_responses

		feedback_text = "
Please take this time to read your feedback and to take a short break! Press enter to continue"
		feedback_text += "

Average reaction time:  " + Math.round(ave_rt) + " ms. 	Accuracy: " + Math.round(accuracy * 100)+ "%"
		feedback_text += "

You have completed: "+testCount+" out of "+numTestBlocks+" blocks of trials."

		if (accuracy < accuracy_thresh){
			feedback_text +=
					'

Your accuracy is too low.  Remember: ' + prompt_text_list
		}

		if (missed_responses > missed_thresh){
			feedback_text +=
					'

You have not been responding to some trials.  Please respond on every trial that requires a response.'
		}

		if (testCount == numTestBlocks){
			feedback_text +=
					'

Done with this test. Press Enter to continue.'
			return false
		} else {

			return true
		}

	}
}

/* create experiment definition array */
flanker_with_shape_matching_experiment = []

flanker_with_shape_matching_experiment.push(practiceNode)
flanker_with_shape_matching_experiment.push(feedback_block)

flanker_with_shape_matching_experiment.push(start_test_block)
flanker_with_shape_matching_experiment.push(testNode)
flanker_with_shape_matching_experiment.push(feedback_block)

flanker_with_shape_matching_experiment.push(post_task_block)
flanker_with_shape_matching_experiment.push(end_block)


text:
/*
 * Do not modify this file. This file is generated from the swf-2012-01-25.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;

using Amazon.SimpleWorkflow.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;

namespace Amazon.SimpleWorkflow.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// RegisterDomain Request Marshaller
    /// </summary>
    public class RegisterDomainRequestMarshaller : IMarshaller<IRequest, RegisterDomainRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
    {
        /// <summary>
        /// Marshaller the request object to the HTTP request.
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public IRequest Marshall(AmazonWebServiceRequest input)
        {
            return this.Marshall((RegisterDomainRequest)input);
        }

        /// <summary>
        /// Marshaller the request object to the HTTP request.
        /// </summary>
        /// <param name="publicRequest"></param>
        /// <returns></returns>
        public IRequest Marshall(RegisterDomainRequest publicRequest)
        {
            IRequest request = new DefaultRequest(publicRequest, "Amazon.SimpleWorkflow");
            string target = "SimpleWorkflowService.RegisterDomain";
            request.Headers["X-Amz-Target"] = target;
            request.Headers["Content-Type"] = "application/x-amz-json-1.0";
            request.HttpMethod = "POST";

            string uriResourcePath = "/";
            request.ResourcePath = uriResourcePath;
            using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();
                var context = new JsonMarshallerContext(request, writer);
                if(publicRequest.IsSetDescription())
                {
                    context.Writer.WritePropertyName("description");
                    context.Writer.Write(publicRequest.Description);
                }

                if(publicRequest.IsSetName())
                {
                    context.Writer.WritePropertyName("name");
                    context.Writer.Write(publicRequest.Name);
                }

                if(publicRequest.IsSetWorkflowExecutionRetentionPeriodInDays())
                {
                    context.Writer.WritePropertyName("workflowExecutionRetentionPeriodInDays");
                    context.Writer.Write(publicRequest.WorkflowExecutionRetentionPeriodInDays);
                }

                writer.WriteObjectEnd();
                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }

            return request;
        }

    }
}


text:
from django import template

import import_string

from is_core.config import settings
from is_core.site import get_site_by_name

register = template.Library()

@register.inclusion_tag('is_core/menu/sub_menu.html', takes_context=True)
def submenu(context, menu_items):
    return {'menu_items': menu_items}

@register.inclusion_tag('is_core/menu/menu.html', takes_context=True)
def menu(context, site_name):
    site = get_site_by_name(site_name)
    request = context.get('request')

    active_menu_groups = context.get('active_menu_groups')

    menu_generator = import_string(settings.MENU_GENERATOR)(request, site, active_menu_groups)
    menu_items = menu_generator.get_menu_items(menu_generator.get_menu_structure())
    context.update({'menu_items': menu_items, 'site_name': site_name})
    return context

@register.inclusion_tag('is_core/menu/bread_crumbs.html', takes_context=True)
def bread_crumbs(context):
    bread_crumbs_menu_items = context.get('bread_crumbs_menu_items')

    menu_items = []

    for menu_item in bread_crumbs_menu_items or []:
        menu_items.append(menu_item)
    return {'menu_items': menu_items}

@register.simple_tag
def header_image():
    return settings.HEADER_IMAGE

@register.simple_tag
def environment():
    return settings.ENVIRONMENT


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>kr.bydelta.koala.util</title>
<meta name="date" content="2018-03-19">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

kr.bydelta.koala.util

Classes

BasicWordLearner

SentenceSplitter

SentenceSplitter$

SimpleWordLearner


text:
package com.tlkzzz.jeesite.modules.ck.entity;

import com.tlkzzz.jeesite.common.persistence.DataEntity;
import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotNull;
import java.util.Date;

/**
 * 入库记录Entity
 * @author xrc
 * @version 2017-03-15
 */
public class CRkinfo extends DataEntity<CRkinfo> {

	private static final long serialVersionUID = 1L;
	private CGoods goods;		// 商品
	private CHouse house;		// 仓库
	private String rknub;		// 入库数量
	private String rkhnub;		// 入库后的总数量
	private String rkqcbj;		// 入库前成本价
	private String rkhcbj;		// 入库成本价
	private String cgzbid;		// 采购总订单ID
	private CSupplier supplier;	// 供应商
	private String state;		// 入库类型 0进货入库1其他入库8(调整库存)9(移库入库)
	private CStore storeId;      //客户ID

	private Date startDate;		//开始入库时间
	private Date endDate;		//结束入库时间
	private String total;		//入库总金额

	private Integer fybs;		//分页标识

	public CRkinfo() {
		super();
	}

	public CRkinfo(String id){
		super(id);
	}

	@NotNull(message = "商品不能为空")
	public CGoods getGoods() {
		return goods;
	}

	public void setGoods(CGoods goods) {
		this.goods = goods;
	}

	@NotNull(message = "仓库不能为空")
	public CHouse getHouse() {
		return house;
	}

	public void setHouse(CHouse house) {
		this.house = house;
	}

	@Length(min=0, max=11, message="入库数量长度必须介于 0 和 11 之间")
	public String getRknub() {
		return rknub;
	}

	public void setRknub(String rknub) {
		this.rknub = rknub;
	}

	@Length(min=0, max=11, message="入库后的总数量长度必须介于 0 和 11 之间")
	public String getRkhnub() {
		return rkhnub;
	}

	public void setRkhnub(String rkhnub) {
		this.rkhnub = rkhnub;
	}

	public String getRkqcbj() {
		return rkqcbj;
	}

	public void setRkqcbj(String rkqcbj) {
		this.rkqcbj = rkqcbj;
	}

	public String getRkhcbj() {
		return rkhcbj;
	}

	public void setRkhcbj(String rkhcbj) {
		this.rkhcbj = rkhcbj;
	}

	public CSupplier getSupplier() {
		return supplier;
	}

	public String getCgzbid() {
		return cgzbid;
	}

	public void setCgzbid(String cgzbid) {
		this.cgzbid = cgzbid;
	}

	public void setSupplier(CSupplier supplier) {
		this.supplier = supplier;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public CStore getStoreId() {
		return storeId;
	}

	public void setStoreId(CStore storeId) {
		this.storeId = storeId;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public String getTotal() {
		return total;
	}

	public void setTotal(String total) {
		this.total = total;
	}

	public Integer getFybs() {
		return fybs;
	}

	public void setFybs(Integer fybs) {
		this.fybs = fybs;
	}
}


text:
/* $Id: Graphics2DAdapter.java 679326 2008-07-24 09:35:34Z vhennebert $ */

package org.apache.fop.render;

import java.io.IOException;

/**
 * This interface represents an optional feature that can be provided by
 * a renderer. It is exposed by calling the getGraphics2DAdapter() method
 * on the renderer. Renderers that support this feature allow painting
 * of arbitrary images through a Graphics2D instance.
 */
public interface Graphics2DAdapter {

    /**
     * Paints an arbitrary images on a given Graphics2D instance. The renderer
     * providing this functionality must set up a Graphics2D instance so that
     * the image with the given extents (in mpt) can be painted by the painter
     * passed to this method. The Graphics2DImagePainter is then passed this
     * Graphics2D instance so the image can be painted.
     * @param painter the painter which will paint the actual image
     * @param context the renderer context for the current renderer
     * @param x X position of the image
     * @param y Y position of the image
     * @param width width of the image
     * @param height height of the image
     * @throws IOException In case of an I/O error while writing the output format
     */
    void paintImage(org.apache.xmlgraphics.java2d.Graphics2DImagePainter painter,
            RendererContext context,
            int x, int y, int width, int height) throws IOException;

    /**
     * Paints an arbitrary images on a given Graphics2D instance. The renderer
     * providing this functionality must set up a Graphics2D instance so that
     * the image with the given extents (in mpt) can be painted by the painter
     * passed to this method. The Graphics2DImagePainter is then passed this
     * Graphics2D instance so the image can be painted.
     * @param painter the painter which will paint the actual image
     * @param context the renderer context for the current renderer
     * @param x X position of the image
     * @param y Y position of the image
     * @param width width of the image
     * @param height height of the image
     * @throws IOException In case of an I/O error while writing the output format
     * @deprecated Use the variant with the Graphics2DImagePainter from XML Graphics Commons instead
     */
    void paintImage(Graphics2DImagePainter painter,
            RendererContext context,
            int x, int y, int width, int height) throws IOException;

}


text:
'use strict';

const _ = require('underscore');
const path = require('path');
const CLIEngine = require('eslint').CLIEngine;
const linter = require('eslint').linter;

const memoize = _.memoize;

const debug = require('abacus-debug')('abacus-schema');

// Lint the specified JS code using the specified ESLint config file
const lint = (code, eslintConfigFile) => {
  const configFile = eslintConfigFile || path.resolve(__dirname, '../config/.eslintrc');

  // Get an ESLint configuration from the config file
  // Memoize to avoid loading the same config file more than once
  const getConfig = memoize((conifgFile) => {
    const cli = new CLIEngine({
      configFile: configFile,
      fix: false,
      useEslintrc: false
    });
    return cli.getConfigForFile(__filename);
  });
  const config = getConfig(configFile);

  // Verify the code
  debug('Executing ESLint on code %s', code);
  const messages = linter.verify(code, config, {
    allowInlineConfig: false
  });
  debug('ESLint messages: %o', messages);

  // Filter only fatal and error messages and return an appropriate result
  const errors = messages.filter((m) => m.fatal || m.severity === 2);
  return {
    ok: errors.length === 0,
    errors: errors
  };
};

module.exports = lint;


text:
module Roomiverse {
	export class RoomState extends Phaser.State {
		group: Phaser.Group
		serenity: Phaser.Sound
		celestial: Phaser.Sound
		timeAccum: number = 0
		state: { [k: string]: boolean }

		player: Player

		nextID: number = 0
		itemsGroup: Phaser.Group
		items: { [id: number]: Item } = {}

		recipe: RecipeInstance = null
		recipeAccum: number = 0

		create() {
			this.group = this.add.group()
			this.group.alpha = 0
			this.add.tween(this.group).to({alpha: 1}, 3000, Phaser.Easing.Linear.None, true)

			this.serenity = this.add.audio('serenity')
			this.celestial = this.add.audio('celestial')

			this.serenity.onStop.add(() => {
				this.celestial.play()
			})
			this.celestial.onStop.add(() => {
				this.serenity.play()
			})

			this.serenity.play()

			var graphics = this.add.graphics(0, 0, this.group)
			graphics.lineStyle(4, 0xffffff, 1)
			graphics.moveTo(400, 120)
			graphics.lineTo(880, 120)
			graphics.lineTo(880, 600)
			graphics.lineTo(400, 600)
			graphics.lineTo(400, 120)

			this.itemsGroup = this.add.group(this.group)

			this.player = new Player(this, this.group)

			this.makeKeyState(Phaser.Keyboard.W, 'KeyW')
			this.makeKeyState(Phaser.Keyboard.A, 'KeyA')
			this.makeKeyState(Phaser.Keyboard.S, 'KeyS')
			this.makeKeyState(Phaser.Keyboard.D, 'KeyD')
			this.makeKeyState(Phaser.Keyboard.Z, 'KeyZ')
			this.makeKeyState(Phaser.Keyboard.X, 'KeyX')
			this.makeKeyState(Phaser.Keyboard.C, 'KeyC')
			this.makeKeyState(Phaser.Keyboard.V, 'KeyV')
			this.makeKeyState(Phaser.Keyboard.ONE,   'KeyOne')
			this.makeKeyState(Phaser.Keyboard.TWO,   'KeyTwo')
			this.makeKeyState(Phaser.Keyboard.THREE, 'KeyThree')
			this.makeKeyState(Phaser.Keyboard.FOUR,  'KeyFour')
			this.makeKeyState(Phaser.Keyboard.FIVE,  'KeyFive')
		}

		update() {
			this.timeAccum += this.game.time.elapsed / 1000
			const timestep = 1 / 60

			if(this.timeAccum >= timestep) {
				this.timeAccum -= timestep
				this.tick(timestep)
			}
		}

		tick(seconds: number) {
			this.recipeAccum += seconds

			const playerAccel = 4000
			const elementAccel = 20
			const elementDecelFactor = 0.13

			var direction = Point.create()
			if(this.state['KeyW']) { direction.y -= 1 }
			if(this.state['KeyA']) { direction.x -= 1 }
			if(this.state['KeyS']) { direction.y += 1 }
			if(this.state['KeyD']) { direction.x += 1 }

			if(direction.length() !== 0) {
				direction.normalize(playerAccel * seconds)
				this.player.accelBy(direction)
			}
			direction.pool()

			this.player.tick(seconds)

			var types: ItemType[] = []

			this.chanceSpawn(types, ItemType.Hydrogen)
			this.chanceSpawn(types, ItemType.Oxygen)
			this.chanceSpawn(types, ItemType.Silicon)
			this.chanceSpawn(types, ItemType.Aluminium)

			if(this.state['KeyZ']) { types.push(ItemType.Hydrogen) }
			if(this.state['KeyX']) { types.push(ItemType.Sodium) }
			if(this.state['KeyC']) { types.push(ItemType.Magnesium) }
			if(this.state['KeyV']) { types.push(ItemType.Chlorine) }

			// craft water (H2O)
			if(this.recipe === null && this.recipeAccum >= 0.5) {
				if(this.state['KeyOne']) {
					this.recipe = recipes[0].get()
					this.recipeAccum = 0
				}
				if(this.state['KeyTwo']) {
					this.recipe = recipes[1].get()
					this.recipeAccum = 0
				}
				if(this.state['KeyThree']) {
					this.recipe = recipes[2].get()
					this.recipeAccum = 0
				}
				if(this.state['KeyFour']) {
					this.recipe = recipes[3].get()
					this.recipeAccum = 0
				}
				if(this.state['KeyFive']) {
					this.recipe = recipes[4].get()
					this.recipeAccum = 0
				}
			}

			// crafting
			if(this.recipe !== null && this.recipe.complete()) {
				types.push(this.recipe.result)
				this.recipe.consumes.forEach(item => {
					if(!item.dying) {
						item.die()
						item.velocity.pool()
						this.items[item.id] = undefined
						delete this.items[item.id]
					}
				})
				this.recipe = null
			}

			types.forEach(t => {
				var theta = this.rnd.realInRange(0, Math.PI * 2)
				var phi = this.rnd.realInRange(260, 680)
				var pos = Point.create(640 + phi * Math.cos(theta), 360 + phi * Math.sin(theta))

				var id = this.nextID++
				var element = new Item(this, this.itemsGroup, id, t, pos, this.rnd.realInRange(50, 500))
				element.velocity.x = this.rnd.integerInRange(-20, 20)
				element.velocity.y = this.rnd.integerInRange(-20, 20)
				this.items[id] = element

				pos.pool()
			})

			Object.keys(this.items).forEach(k => {
				var item: Item = this.items[k]

				// crafting
				if(this.recipe && !item.attached) {
					for(var i = 0; i < this.recipe.needs.length; ++i) {
						if(this.recipe.needs[i] === item.type) {
							item.attached = true
							item.factor = 20
							item.graphics.alpha = 0.5
							this.recipe.needs.splice(i, 1)
							this.recipe.consumes.push(item)
							break
						}
					}
				}

				if(item.amount <= 0 && !item.attached) {
					if(!item.dying) {
						item.die()
						this.items[k].velocity.pool()
						this.items[k] = undefined
						delete this.items[k]
					}
				}

				var dir = Point.create(this.player.group.x - item.group.x, this.player.group.y - item.group.y)
				dir.normalize()

				if(Math.sqrt(Math.pow(this.player.group.x - item.group.x, 2) + Math.pow(this.player.group.y - item.group.y, 2)) < this.player.radius + item.radius) {
					item.remove(seconds * 100)
					this.player.inventory.add(item.type, seconds * 100)
					dir.scale(-3)
				}

				item.velocity.x += dir.x * Math.abs(dir.x) * elementAccel * item.factor * seconds / (item.amount / 100)
				item.velocity.y += dir.y * Math.abs(dir.y) * elementAccel * item.factor * seconds / (item.amount / 100)
				item.velocity = item.velocity.scaled(Math.max(0, 1 - elementDecelFactor * seconds))
				dir.pool()

				item.group.x += item.velocity.x * seconds
				item.group.y += item.velocity.y * seconds
			})
		}

		shutdown() {
			this.serenity.stop()
			this.celestial.stop()
		}

		makeKeyState(keyCode: number, stateName: string) {
			var key = this.game.input.keyboard.addKey(keyCode)
			key.onDown.add(() => {
				this.state[stateName] = true
			})
			key.onUp.add(() => {
				this.state[stateName] = false
			})
		}

		chanceSpawn(types: ItemType[], type: ItemType) {
			var chance = 5 / Math.pow(Item.initialTTLForType(type), 1.2)
			if(this.rnd.realInRange(0, 100) < chance) {
				types.push(type)
			}
		}
	}
}


text:
<?php

namespace AppBundle\Tests\DependencyInjection;

use AppBundle\DependencyInjection\AppExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Verifies that the bundles configuration is properly loaded
 *
 * @author Daniel S. Reichenbach <daniel@kogitoapp.com>
 */
class AppExtensionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Tests if all required bundle parameters are available and set
     *
     * @param string $parameter
     * @param string $expected
     *
     * @dataProvider getDataToTestDefinedParameter
     */
    public function testDefinedParameter($parameter, $expected)
    {
        $container = $this->createContainer($this->getMinimalConfigs());

        $this->assertTrue(
            $container->hasParameter($parameter),
            sprintf('The parameter \'%s\' is defined.', $parameter)
        );
        $this->assertEquals(
            $expected,
            $container->getParameter($parameter),
            sprintf('The parameter \'%s\' has the right value.', $parameter)
        );
    }

    /**
     * Creates a Container with a given configuration
     *
     * @param array $configs
     *
     * @return ContainerBuilder
     */
    public function createContainer(array $configs)
    {
        $container = new ContainerBuilder();
        $extension = new AppExtension('testkernel');
        $extension->load($configs, $container);

        return $container;
    }

    /**
     * Returns a minimal default configuration
     *
     * @return array
     */
    public function getMinimalConfigs()
    {
        return array(
            array(
                'maintenance' => array(
                    'opcache' => array(
                        'secret'    => 'ThisKeyIsNotSecret',
                        'host_ip'   => '127.0.0.1:80',
                        'host_name' => 'acme.com',
                    ),
                ),
                'users' => array(
                    'default_group' => 'Users',
                ),
                'request_context' => array(
                    'host'          => 'acme.com',
                ),
            ),
        );
    }

    /**
     * Tests bundle services
     *
     * @param string $id
     *
     * @dataProvider getDataToTestDefinedService
     */
    public function testDefinedService($id)
    {
        $container = $this->createContainer($this->getMinimalConfigs());

        $this->assertTrue(
            ($container->has($id) || $container->get($id)),
            sprintf('The service (or alias) \'%s\' is defined.', $id)
        );
    }

    /**
     * Provides a list of bundle parameters and settings to test
     *
     * @return array
     */
    public function getDataToTestDefinedParameter()
    {
        return array(
            array(
                'app.maintenance.opcache.secret',
                'ThisKeyIsNotSecret',
            ),
            array(
                'app.maintenance.opcache.host_ip',
                '127.0.0.1:80',
            ),
            array(
                'app.maintenance.opcache.host_name',
                'acme.com',
            ),
            array(
                'app.maintenance.opcache.protocol',
                'http',
            ),
            array(
                'app.maintenance.opcache.web_dir',
                '%kernel.root_dir%/../web',
            ),
            array(
                'app.users.default_group',
                'Users',
            ),
            array(
                'app.request_context.host',
                'acme.com',
            ),
            array(
                'app.request_context.protocol',
                'http',
            ),
        );
    }

    /**
     * Provides a list of bundle services to test
     *
     * @return array
     */
    public function getDataToTestDefinedService()
    {
        return array(
            array('app.listener.user.events'),
            array('app.listener.request.locale'),
            array('app.listener.session.user.locale'),
            array('app.registration.form.type'),
            array('app.invitation.form.type'),
            array('app.invitation.form.data_transformer'),
            array('app.service.user'),
            array('app.service.menu'),
            array('app.service.menu.user'),
        );
    }
}


text:
import { Component } from "@angular/core";

@Component({
  selector: "sd-about",
  templateUrl: "app/+about/components/about.component.html",
  styleUrls: ["app/+about/components/about.component.css"]
})
export class AboutComponent {}


text:
//pppBuffer.hpp

/*
Ping-Pong-Pung buffer implementation
aka:
Tick-Tack-Tock or Flip-Flap-Flop buffer

//Code by Samuel Petrocelli
//July 2011
*/

#ifndef __MIO_PPP_BUFFER_H__
#define __MIO_PPP_BUFFER_H__

#include <iostream>
#include <pthread.h>
#include <stdio.h>

namespace mio{

#define DEFAULT_PPP_BUF_SIZE 3

class pppBuffer{
  private:
    int m_nCurrentRead,
        m_nCurrentWrite,
        m_nPreviousWrite,
        m_nReadCount;

    pthread_mutex_t m_buffer_mutex;
    pthread_mutex_t m_cond_mutex;
    pthread_cond_t  m_condition_var;

    int nNext(int nCurIdx, int nNotAvail){
      if( ( (++nCurIdx) >= m_nSize) || (nCurIdx < 0) ) //reached end of ring buffer, reset to start index
        nCurIdx = 0;
      if(nCurIdx == nNotAvail)
        nCurIdx++;
      if( (nCurIdx >= m_nSize) || (nCurIdx < 0) )
        nCurIdx = 0;
      return(nCurIdx);
    }

  public:
    const int m_nSize; //zero inclusive
    /*
      Constructor of the Ringbuffer
      nSize determines how many elements are stored in it.

      Note that nSize needs to be at least 2
    */
    pppBuffer() : m_nCurrentRead(0), m_nPreviousWrite(0), m_nCurrentWrite(1),
      m_nSize(DEFAULT_PPP_BUF_SIZE), m_nReadCount(0){}

    ~pppBuffer(){}

    void PrintParams(){
      std::cout << "Current Read:   " << m_nCurrentRead << std::endl;
      std::cout << "Current Write:  " << m_nCurrentWrite << std::endl;
      std::cout << "Previous Write: " << m_nPreviousWrite << std::endl;
      std::cout << "Read Count:     " << m_nReadCount << std::endl << std::endl;
    }

    int Init(){
      if( pthread_mutex_init(&m_buffer_mutex, NULL) != 0 ){
        perror("pppBuffer: nInit() - pthread_mutex_init(m_buffer_mutex) error");
        return(-1);
      }
      if( pthread_mutex_init(&m_cond_mutex, NULL) != 0 ){
        perror("pppBuffer: nInit() - pthread_mutex_init(m_cond_mutex) error");
        return(-1);
      }
      if( pthread_cond_init(&m_condition_var, NULL) != 0 ){
        perror("pppBuffer: nInit() - pthread_cond_init(m_condition_var) error");
        return(-1);
      }
      return(0);
    }

    /*
      gets the index to the next write-bin
    */
    int GetNextWrite(){
      int nResult;
      //std::cout << "called a write" << std::endl;

      pthread_mutex_lock(&m_buffer_mutex);
      {
        m_nPreviousWrite = m_nCurrentWrite; //the buffer just written to is now the previous write
        m_nCurrentWrite = nNext(m_nCurrentWrite, m_nCurrentRead); //m_nCurrentWrite the index that can-be/has-currently-been written to
        nResult = m_nCurrentWrite;

        //signal nGetNextRead incase it is waiting for a new buffer frame
        pthread_mutex_lock(&m_cond_mutex);
        {
          pthread_cond_signal(&m_condition_var);
        }
        pthread_mutex_unlock(&m_cond_mutex);

        m_nReadCount = (m_nReadCount <= 0) ? 0 : (m_nReadCount - 1);
      }
      pthread_mutex_unlock(&m_buffer_mutex);

      return(nResult);
    }

    /*
      gets the index to the next read-bin

      If bMostRecentReadable is true then this will return the bin that was most
      recently written. In other words, we always jump directly ahead to the most
      recent data available.
      If bMostRecentReadable is false then we only move to the next read-bin in order
      (we will not jump ahead).
    */
    int GetNextRead(bool bMostRecentReadable){
      int nResult;
      //std::cout << "called a read" << std::endl;

      m_nReadCount = (m_nReadCount >= m_nSize) ? m_nSize : (m_nReadCount + 1);

      if(m_nReadCount == m_nSize){
        //std::cout << "Blocking read..." << std::endl;
        pthread_mutex_lock(&m_cond_mutex);
        {
          pthread_cond_wait(&m_condition_var, &m_cond_mutex);
        }
        pthread_mutex_unlock(&m_cond_mutex);
      }

      pthread_mutex_lock(&m_buffer_mutex);
      {
        m_nCurrentRead = bMostRecentReadable ? m_nPreviousWrite : nNext(m_nCurrentRead, m_nCurrentWrite);
        nResult = m_nCurrentRead;
      }
      pthread_mutex_unlock(&m_buffer_mutex);

      return(nResult);
    }

    /*
      returns the index of the current write-bin
    */
    int CurWrite(){
      int nResult;
      pthread_mutex_lock(&m_buffer_mutex);
        nResult = m_nCurrentWrite;
      pthread_mutex_unlock(&m_buffer_mutex);
      return(nResult);
    }

    /*
      returns the index of the current read-bin
    */
    int CurRead(){
      int nResult;
      pthread_mutex_lock(&m_buffer_mutex);
        nResult = m_nCurrentRead;
      pthread_mutex_unlock(&m_buffer_mutex);
      return(nResult);
    }
};

} //namespace mio

#endif /*__MIO_PPP_BUFFER_H__*/


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.skgadi.controltoolbox.MainActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:id="@+id/Settings"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:visibility="gone">

                <LinearLayout
                    android:id="@+id/SettingsSeekBars"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:orientation="vertical"></LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <Button
                        android:id="@+id/button"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:onClick="SettingsSave"
                        android:text="@string/BUTTON_SAVE" />

                    <Button
                        android:id="@+id/button2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:onClick="SettingsReset"
                        android:text="@string/BUTTON_RESET" />

                    <Button
                        android:id="@+id/button3"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:onClick="SettingsCancel"
                        android:text="@string/BUTTON_CANCEL" />

                    <Button
                        android:id="@+id/button5"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:onClick="SettingsResetNSave"
                        android:text="@string/BUTTON_RESET_SAVE" />
                </LinearLayout>

            </LinearLayout>

            <LinearLayout
                android:id="@+id/Main"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:visibility="visible">

            </LinearLayout>

            <LinearLayout
                android:id="@+id/ModelView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"></LinearLayout>

            <LinearLayout
                android:id="@+id/PID"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:visibility="gone">

                <ImageView
                    android:id="@+id/imageView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:adjustViewBounds="false"
                    android:cropToPadding="false"
                    android:visibility="visible"
                    app:srcCompat="@drawable/pid" />

                <com.jjoe64.graphview.GraphView
                    android:layout_width="match_parent"
                    android:layout_height="300dip"
                    android:id="@+id/pid_chart00" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/IDENTIFICATION0"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:visibility="gone"></LinearLayout>

            <LinearLayout
                android:id="@+id/IDENTIFICATION1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:visibility="gone"></LinearLayout>

            <LinearLayout
                android:id="@+id/IDENTIFICATION2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:visibility="gone"></LinearLayout>

        </LinearLayout>

    </ScrollView>

</android.support.constraint.ConstraintLayout>


text:
<?xml version="1.0" encoding="utf-8"?>

<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2012/deployment" AppPlatformVersion="8.0">
  <DefaultLanguage xmlns="" code="en-US"/>
  <App xmlns="" ProductID="{86f9d708-55d0-464f-bb56-afda8c986b86}" Title="Jasper" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal"  Author="Jasper author" Description="Sample description" Publisher="Jasper" PublisherID="{d9d85ada-155d-4760-9893-b09dfec8f9f4}">
    <IconPath IsRelative="true" IsResource="false">Assets\ApplicationIcon.png</IconPath>
    <Capabilities>
      <Capability Name="ID_CAP_NETWORKING"/>
      <Capability Name="ID_CAP_MEDIALIB_AUDIO"/>
      <Capability Name="ID_CAP_MEDIALIB_PLAYBACK"/>
      <Capability Name="ID_CAP_SENSORS"/>
      <Capability Name="ID_CAP_WEBBROWSERCOMPONENT"/>
    </Capabilities>
    <Tasks>
      <DefaultTask  Name ="_default" NavigationPage="MainPage.xaml"/>
    </Tasks>
    <Tokens>
      <PrimaryToken TokenID="JasperToken" TaskName="_default">
        <TemplateFlip>
          <SmallImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileSmall.png</SmallImageURI>
          <Count>0</Count>
          <BackgroundImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileMedium.png</BackgroundImageURI>
          <Title>Jasper</Title>
          <BackContent></BackContent>
          <BackBackgroundImageURI></BackBackgroundImageURI>
          <BackTitle></BackTitle>
          <DeviceLockImageURI></DeviceLockImageURI>
          <HasLarge></HasLarge>
        </TemplateFlip>
      </PrimaryToken>
    </Tokens>
    <ScreenResolutions>
      <ScreenResolution Name="ID_RESOLUTION_WVGA"/>
      <ScreenResolution Name="ID_RESOLUTION_WXGA"/>
      <ScreenResolution Name="ID_RESOLUTION_HD720P"/>
    </ScreenResolutions>
  </App>
</Deployment>


text:
package io.teknek.nibiru.sponsor;

import java.util.SortedMap;
import java.util.TreeMap;

import junit.framework.Assert;
import io.teknek.nibiru.AbstractTestServer;
import io.teknek.nibiru.TestUtil;
import io.teknek.nibiru.Token;
import io.teknek.nibiru.client.InternodeClient;
import io.teknek.nibiru.engine.DefaultColumnFamily;
import io.teknek.nibiru.engine.atom.AtomKey;
import io.teknek.nibiru.engine.atom.AtomValue;
import io.teknek.nibiru.engine.atom.ColumnKey;
import io.teknek.nibiru.engine.atom.ColumnValue;

import org.junit.Test;

public class BulkWriterTest extends AbstractTestServer {

  @Test
  public void aTest(){
    InternodeClient i = new InternodeClient(server.getConfiguration().getTransportHost(),
            server.getConfiguration().getTransportPort());
    i.createSsTable(TestUtil.DATA_KEYSPACE, TestUtil.PETS_COLUMN_FAMILY, 1+"");
    DefaultColumnFamily store = (DefaultColumnFamily) server.getKeyspaces().get(TestUtil.DATA_KEYSPACE).getStores().get(TestUtil.PETS_COLUMN_FAMILY);
    Assert.assertEquals(1, store.getStreamSessions().size());
    Token t = new Token("a", "a");
    SortedMap<AtomKey,AtomValue> a= new TreeMap<>();
    ColumnKey k = new ColumnKey("a") ;
    ColumnValue v = new ColumnValue();
    v.setCreateTime(1);
    v.setTime(1);
    v.setValue("b");
    a.put(k, v);
    i.transmit(TestUtil.DATA_KEYSPACE, TestUtil.PETS_COLUMN_FAMILY, t, a, 1+"");
    i.closeSsTable(TestUtil.DATA_KEYSPACE, TestUtil.PETS_COLUMN_FAMILY, 1+"");
    Assert.assertEquals(1, store.getSstable().size());
    Assert.assertEquals(0, store.getStreamSessions().size());
    Assert.assertEquals("b", ((ColumnValue) server.get(TestUtil.DATA_KEYSPACE, TestUtil.PETS_COLUMN_FAMILY, "a", "a")).getValue());
  }
}


text:
'use strict';

var isNumeric = require('fast-isnumeric');
var tinycolor = require('tinycolor2');

var Color = require('../../components/color');
var helpers = require('./helpers');

module.exports = function calc(gd, trace) {
    var vals = trace.values;
    var hasVals = Array.isArray(vals) && vals.length;
    var labels = trace.labels;
    var colors = trace.marker.colors;
    var cd = [];
    var fullLayout = gd._fullLayout;
    var colorWay = fullLayout.colorway;
    var colorMap = fullLayout._piecolormap;
    var allThisTraceLabels = {};
    var vTotal = 0;
    var hiddenLabels = fullLayout.hiddenlabels || [];

    var i, v, label, hidden, pt;

    if(!fullLayout._piecolorway && colorWay !== Color.defaults) {
        fullLayout._piecolorway = generateDefaultColors(colorWay);
    }

    if(trace.dlabel) {
        labels = new Array(vals.length);
        for(i = 0; i < vals.length; i++) {
            labels[i] = String(trace.label0 + i * trace.dlabel);
        }
    }

    function pullColor(color, label) {
        if(!color) return false;

        color = tinycolor(color);
        if(!color.isValid()) return false;

        color = Color.addOpacity(color, color.getAlpha());
        if(!colorMap[label]) colorMap[label] = color;

        return color;
    }

    var seriesLen = (hasVals ? vals : labels).length;

    for(i = 0; i < seriesLen; i++) {
        if(hasVals) {
            v = vals[i];
            if(!isNumeric(v)) continue;
            v = +v;
            if(v < 0) continue;
        }
        else v = 1;

        label = labels[i];
        if(label === undefined || label === '') label = i;
        label = String(label);

        var thisLabelIndex = allThisTraceLabels[label];
        if(thisLabelIndex === undefined) {
            allThisTraceLabels[label] = cd.length;

            hidden = hiddenLabels.indexOf(label) !== -1;

            if(!hidden) vTotal += v;

            cd.push({
                v: v,
                label: label,
                color: pullColor(colors[i]),
                i: i,
                pts: [i],
                hidden: hidden
            });
        }
        else {
            pt = cd[thisLabelIndex];
            pt.v += v;
            pt.pts.push(i);
            if(!pt.hidden) vTotal += v;

            if(pt.color === false && colors[i]) {
                pt.color = pullColor(colors[i], label);
            }
        }
    }

    if(trace.sort) cd.sort(function(a, b) { return b.v - a.v; });

    /**
     * now go back and fill in colors we're still missing
     * this is done after sorting, so we pick defaults
     * in the order slices will be displayed
     */

    for(i = 0; i < cd.length; i++) {
        pt = cd[i];
        if(pt.color === false) {
            // have we seen this label and assigned a color to it in a previous trace?
            if(colorMap[pt.label]) {
                pt.color = colorMap[pt.label];
            }
            else {
                colorMap[pt.label] = pt.color = nextDefaultColor(
                    fullLayout._piedefaultcolorcount,
                    fullLayout._piecolorway
                );
                fullLayout._piedefaultcolorcount++;
            }
        }
    }

    // include the sum of all values in the first point
    if(cd[0]) cd[0].vTotal = vTotal;

    // now insert text
    if(trace.textinfo && trace.textinfo !== 'none') {
        var hasLabel = trace.textinfo.indexOf('label') !== -1;
        var hasText = trace.textinfo.indexOf('text') !== -1;
        var hasValue = trace.textinfo.indexOf('value') !== -1;
        var hasPercent = trace.textinfo.indexOf('percent') !== -1;
        var separators = fullLayout.separators;

        var thisText;

        for(i = 0; i < cd.length; i++) {
            pt = cd[i];
            thisText = hasLabel ? [pt.label] : [];
            if(hasText) {
                var texti = helpers.getFirstFilled(trace.text, pt.pts);
                if(texti) thisText.push(texti);
            }
            if(hasValue) thisText.push(helpers.formatPieValue(pt.v, separators));
            if(hasPercent) thisText.push(helpers.formatPiePercent(pt.v / vTotal, separators));
            pt.text = thisText.join('<br>');
        }
    }

    return cd;
};

/**
 * pick a default color from the main default set, augmented by
 * itself lighter then darker before repeating
 */
var pieDefaultColors;

function nextDefaultColor(index, pieColorWay) {
    if(!pieDefaultColors) {
        // generate this default set on demand (but then it gets saved in the module)
        var mainDefaults = Color.defaults;
        pieDefaultColors = generateDefaultColors(mainDefaults);
    }

    var pieColors = pieColorWay || pieDefaultColors;
    return pieColors[index % pieColors.length];
}

function generateDefaultColors(colorList) {
    var i;

    var pieColors = colorList.slice();

    for(i = 0; i < colorList.length; i++) {
        pieColors.push(tinycolor(colorList[i]).lighten(20).toHexString());
    }

    for(i = 0; i < colorList.length; i++) {
        pieColors.push(tinycolor(colorList[i]).darken(20).toHexString());
    }

    return pieColors;
}


text:
package com.nextbreakpoint.shop.common.model;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.Objects;

public class Message {
    private String messageId;
    private String messageType;
    private String messageBody;
    private String messageSource;
    private String partitionKey;
    private Long timestamp;

    @JsonCreator
    public Message(@JsonProperty("messageId") String messageId,
                   @JsonProperty("messageType") String messageType,
                   @JsonProperty("messageBody") String messageBody,
                   @JsonProperty("messageSource") String messageSource,
                   @JsonProperty("partitionKey") String partitionKey,
                   @JsonProperty("timestamp") Long timestamp) {
        this.messageId = Objects.requireNonNull(messageId);
        this.messageType = Objects.requireNonNull(messageType);
        this.messageBody = Objects.requireNonNull(messageBody);
        this.messageSource = Objects.requireNonNull(messageSource);
        this.partitionKey = Objects.requireNonNull(partitionKey);
        this.timestamp = Objects.requireNonNull(timestamp);
    }

    public String getMessageId() {
        return messageId;
    }

    public String getMessageType() {
        return messageType;
    }

    public String getMessageBody() {
        return messageBody;
    }

    public String getMessageSource() {
        return messageSource;
    }

    public String getPartitionKey() {
        return partitionKey;
    }

    public Long getTimestamp() {
        return timestamp;
    }
}


text:
{-# LANGUAGE FlexibleInstances     #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RecordWildCards       #-}
{-# LANGUAGE ScopedTypeVariables   #-}

-- |
-- Module      :  Network.Ethereum.Account.LocalKey
-- Copyright   :  Aleksandr Krupenkin 2016-2021
--                Roy Blankman 2018
-- License     :  Apache-2.0
--
-- Maintainer  :  mail@akru.me
-- Stability   :  experimental
-- Portability :  unportable
--
-- Using ECC for singing transactions locally, e.g. out of Ethereum node.
-- Transaction will send using 'eth_sendRawTransacion' JSON-RPC method.
--

module Network.Ethereum.Account.LocalKey where

import           Control.Exception                 (TypeError (..))
import           Control.Monad.Catch               (throwM)
import           Control.Monad.State.Strict        (get, runStateT)
import           Control.Monad.Trans               (lift)
import           Crypto.Ethereum                   (PrivateKey)
import           Data.ByteArray                    (convert)
import           Data.ByteString                   (empty)
import           Data.Default                      (Default (..))
import           Data.Proxy                        (Proxy (..))

import           Crypto.Ethereum                   (derivePubKey, importKey)
import           Crypto.Ethereum.Signature         (signTransaction)
import           Data.Solidity.Abi.Codec           (decode, encode)
import           Data.Solidity.Prim.Address        (fromPubKey)
import           Network.Ethereum.Account.Class    (Account (..))
import           Network.Ethereum.Account.Internal (AccountT (..),
                                                    CallParam (..),
                                                    defaultCallParam, getCall,
                                                    getReceipt)
import qualified Network.Ethereum.Api.Eth          as Eth (call, estimateGas,
                                                           getTransactionCount,
                                                           sendRawTransaction)
import           Network.Ethereum.Api.Types        (Call (..))
import           Network.Ethereum.Chain            (foundation)
import           Network.Ethereum.Contract.Method  (selector)
import           Network.Ethereum.Transaction      (encodeTransaction)

-- | Local EOA params
data LocalKey = LocalKey
    { localKeyPrivate :: !PrivateKey
    , localKeyChainId :: !Integer
    }
    deriving (Eq, Show)

instance Default LocalKey where
    def = LocalKey (importKey empty) foundation

type LocalKeyAccount = AccountT LocalKey

instance Account LocalKey LocalKeyAccount where
    withAccount a =
        fmap fst . flip runStateT (defaultCallParam a) . runAccountT

    send (args :: a) = do
        CallParam{..} <- get
        c <- getCall

        let dat     = selector (Proxy :: Proxy a) <> encode args
            address = fromPubKey (derivePubKey $ localKeyPrivate _account)

        nonce <- lift $ Eth.getTransactionCount address _block
        let params = c { callFrom  = Just address
                       , callNonce = Just nonce
                       , callData  = Just $ convert dat }

        params' <- case callGas params of
            Just _  -> return params
            Nothing -> do
                gasLimit <- lift $ Eth.estimateGas params
                return $ params { callGas = Just gasLimit }

        let packer = encodeTransaction params' (localKeyChainId _account)
            signed = signTransaction packer (localKeyPrivate _account)
        lift $ getReceipt _timeout =<< Eth.sendRawTransaction signed

    call (args :: a) = do
        CallParam{..} <- get
        c <- getCall
        let dat = selector (Proxy :: Proxy a) <> encode args
            address = fromPubKey (derivePubKey $ localKeyPrivate _account)
            params = c { callFrom = Just address, callData = Just $ convert dat }

        res <- lift $ Eth.call params _block
        case decode res of
            Right r -> return r
            Left e  -> lift (throwM $ TypeError e)


text:
using System.ComponentModel.DataAnnotations;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;

namespace Gdn.WeChat
{
    /// <summary>
    /// Represents a WeChat account.
    /// </summary>
    public class WeChatAccount : FullAuditedAggregateRoot<string>, IMustHaveTenant
    {
        /// <inheritdoc />
        [MaxLength(64)]
        public override string Id { get; set; }

        /// <inheritdoc />
        public int TenantId { get; set; }

        /// <summary>
        /// Account name.
        /// </summary>
        [Required]
        [MaxLength(256)]
        public string Name { get; set; }

        /// <summary>
        /// Account type.
        /// </summary>
        public WeChatAccountType AccountType { get; set; }

        /// <summary>
        /// App ID to request access token.
        /// </summary>
        [MaxLength(64)]
        public string AppId { get; set; }

        /// <summary>
        /// App secret to request access token.
        /// </summary>
        [MaxLength(64)]
        public string AppSecret { get; set; }

        /// <summary>
        /// Server URL to provide response for the account.
        /// </summary>
        public string Url { get; set; }

        /// <summary>
        /// Account token to verify requests from WeChat server.
        /// </summary>
        [MaxLength(64)]
        public string Token { get; set; }

        /// <summary>
        /// Encoding AES key for message encryption.
        /// </summary>
        [MaxLength(64)]
        public string EncodingAesKey { get; set; }

        /// <summary>
        /// Message security mode.
        /// </summary>
        public WeChatMessageSecurityMode? SecurityMode { get; set; }

        /// <summary>
        /// Account description.
        /// </summary>
        public string Description { get; set; }
    }
}


text:
/**
 * Created by JYOTHIPRASAD on 3/1/2017.
 */
(function() {
    angular
        .module("Hangman")
        .controller("GameController", GameController);

    function GameController(GameService) {
        var vm = this;
        vm.keyEvent = keyEvent;
        vm.checkGuess = checkGuess;
        vm.startNewGame = startNewGame;

        function init() {
            vm.alphabet = [];
            vm.error = '';
            /*
             * generate the alphabet for the user input
             * buttons to guess letters
             *
             * */
            for(var i=97;i<=122;i++) {
                vm.alphabet.push(String.fromCharCode(i));
            }
            GameService
                .getClientSession()
                .success(function(client) {
                    initiateGame(client);
                    $(document).ready(function() {
                        document.getElementById('keyEventArea').focus();
                    });
                })
                .error(function(err) {
                    vm.error = err;
                });
        }
        init();

        function keyEvent(event) {
            var key = event.keyCode;
            /*
             * if the key press was a valid input
             * then send it to the server as a guess
             *
             * */
            if((key>96 && key<123) || (key>64 && key<91)) {
                var letter = String.fromCharCode(key);
                checkGuess((letter));
            }
        }

        function checkGuess(letter) {
            GameService
                .updateGuess(letter.toLowerCase())
                .success(function(client) {
                    vm.client = client;
                    if(vm.client.currWinStatus || vm.client.currLoseStatus) {
                        /*
                         * show end game modal if the game is over
                         *
                         * */
                        $('#gameOver').modal({keyboard: true});
                    }
                })
                .error(function(err) {
                    vm.error = err;
                });
        }

        function startNewGame(newGame) {
            vm.error = '';
            if(newGame) {
                GameService
                    .startNewGame()
                    .success(function(client) {
                        initiateGame(client);
                    })
                    .error(function(err) {
                        vm.error = err;
                    });
            }
        }

        function initiateGame(client) {
            if(!client) {
                vm.error = "You have played all the words available." +
                    " To continue playing, upload a new word set.";
            }
            else {
                vm.client = client;
                vm.currWordArray = client.currentWord.split('');    // used by UI to render the word to be guessed
            }
        }
    }
})();


text:
module Landable
  module Traffic
    class Cookie < ActiveRecord::Base
      include Landable::TableName

      lookup_by :cookie_id, cache: 100, find: true

      has_many :ownerships
      has_many :visits

      after_initialize do
        self.id ||= SecureRandom.uuid
      end
    end
  end
end


text:
template<typename T,typename _AuxType,typename _StateType>
class SA_Base{ //Interface Template class for SA
public:

    SA_Base(_StateType state):_state(state){};

    using auxType = _AuxType;
    using stateType = _StateType;

    void turnState(auxType aux){ static_cast<T*>(this)->turnState(aux); }
    void initState(auxType aux){ static_cast<T*>(this)->initState(aux); }

    int calcEvalution(auxType& aux){ static_cast<T*>(this)->calcEvalution(); }

    bool operator<(const T* rhs){return this->_evalution < rhs->_evalution;}
    bool operator>(const T* rhs){return this->_evalution > rhs->_evalution;}

    void setEvalution(int eval){_evalution = eval;}
    int getEvalution(){return _evalution;}

    stateType getState(){return _state;}
    void setState(stateType state){_state = state;}

protected:
    stateType _state;
    int _evalution;
};

#endif


text:
XBee Data Acquisition Remote Firmware Experimental Bootloader Development
-------------------------------------------------------------------------

This is a test firmware for the remote unit. Written in C under avr-gcc.

This particular code example is identical to the node-example. It is used to
develop the bootloader interface for the ATTiny AVRs that do not have a separate
bootloader section.

A dummy message is sent to the coordinator at timed intervals and PORTB0 is
toggled in the timer ISR.

The XBee is intended to not use hardware flow control, although RTS may be
possible. This is due to a lack of ports on the AVR package intended for use
(ATTiny841).

The AVR is set to 1MHz for low power, and a baud rate of 9600 to aimed at
giving time for processing messages.

No bootloader section is provided with many of the ATTiny AVRs, so it must
reside with the program that it will eventually overwrite. It is placed in a
section at the top of memory and is linked with the application program. A call
to the bootloader is made at the start following a test of the bootloader pin.

The node is transmitting the messages but the bootloader code is not working.

--------------------

The MCU variable is passed to the source in various places to allow:

make MCU=xxx

where xxx is either attiny841, attiny4313 or atmega48.

The makefile may need to be changed for other AVR types to account for
differences. A separate defines-xxx.h file may need to be incorporated.

K. Sarkies
12 November 2014

--------------------
                            BOOTLOADER NOTES

So far it has not been possible to trace reliably the action of the bootloader
past the point where incoming characters are received. There is also evidence
that the gcc compiler produces invalid code. Currently optimization level 1
only works with this code. Other optimization levels create faulty code.

The programming is unreliable and relies on the application code to effect a
jump to the bootloader. Thus if the programming fails and the application
is corrupted, the bootloader may never be re-entered.

An existing open source bootloader for these AVRS is TinySafeBoot:
http://jtxp.org/tech/tinysafeboot_en.htm

For future work, a possible solution may be to keep the first page of memory
unchanged and ensure that application ISRs are placed in fixed locations in
memory, possibly with just a call to the ISR code to allow flexibility. A small
main program at the start could call either the bootloader or the application
code at fixed locations according to the setting of the bootloader pin, so that
only the core application code can be changed by programming. Compilation must
ensure that all parts of the system remain in the correct memory relationship.

--------------------