text:
<?php

namespace Illuminate\Tests\Integration\Database;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class EloquentPivotEventsTest extends DatabaseTestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        // clear event log between requests
        PivotEventsTestCollaborator::$eventsCalled = [];
    }

    protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email');
            $table->timestamps();
        });

        Schema::create('projects', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });

        Schema::create('project_users', function (Blueprint $table) {
            $table->integer('user_id');
            $table->integer('project_id');
            $table->text('permissions')->nullable();
            $table->string('role')->nullable();
        });
    }

    public function testPivotWillTriggerEventsToBeFired()
    {
        $user = PivotEventsTestUser::forceCreate(['email' => 'taylor@laravel.com']);
        $user2 = PivotEventsTestUser::forceCreate(['email' => 'ralph@ralphschindler.com']);
        $project = PivotEventsTestProject::forceCreate(['name' => 'Test Project']);

        $project->collaborators()->attach($user);
        $this->assertEquals(['saving', 'creating', 'created', 'saved'], PivotEventsTestCollaborator::$eventsCalled);

        PivotEventsTestCollaborator::$eventsCalled = [];
        $project->collaborators()->sync([$user2->id]);
        $this->assertEquals(['deleting', 'deleted', 'saving', 'creating', 'created', 'saved'], PivotEventsTestCollaborator::$eventsCalled);

        PivotEventsTestCollaborator::$eventsCalled = [];
        $project->collaborators()->sync([$user->id => ['role' => 'owner'], $user2->id => ['role' => 'contributor']]);
        $this->assertEquals(['saving', 'creating', 'created', 'saved', 'saving', 'updating', 'updated', 'saved'], PivotEventsTestCollaborator::$eventsCalled);

        PivotEventsTestCollaborator::$eventsCalled = [];
        $project->collaborators()->detach($user);
        $this->assertEquals(['deleting', 'deleted'], PivotEventsTestCollaborator::$eventsCalled);
    }

    public function testPivotWithPivotCriteriaTriggerEventsToBeFiredOnCreateUpdateNoneOnDetach()
    {
        $user = PivotEventsTestUser::forceCreate(['email' => 'taylor@laravel.com']);
        $user2 = PivotEventsTestUser::forceCreate(['email' => 'ralph@ralphschindler.com']);
        $project = PivotEventsTestProject::forceCreate(['name' => 'Test Project']);

        $project->contributors()->sync([$user->id, $user2->id]);
        $this->assertEquals(['saving', 'creating', 'created', 'saved', 'saving', 'creating', 'created', 'saved'], PivotEventsTestCollaborator::$eventsCalled);

        PivotEventsTestCollaborator::$eventsCalled = [];
        $project->contributors()->detach($user->id);
        $this->assertEquals([], PivotEventsTestCollaborator::$eventsCalled);
    }

    public function testCustomPivotUpdateEventHasExistingAttributes()
    {
        $_SERVER['pivot_attributes'] = false;

        $user = PivotEventsTestUser::forceCreate([
            'email' => 'taylor@laravel.com',
        ]);

        $project = PivotEventsTestProject::forceCreate([
            'name' => 'Test Project',
        ]);

        $project->collaborators()->attach($user, ['permissions' => ['foo', 'bar']]);

        $project->collaborators()->updateExistingPivot($user->id, ['role' => 'Lead Developer']);

        $this->assertEquals(
            [
                'user_id' => '1',
                'project_id' => '1',
                'permissions' => '["foo","bar"]',
                'role' => 'Lead Developer',
            ],
            $_SERVER['pivot_attributes']
        );
    }

    public function testCustomPivotUpdateEventHasDirtyCorrect()
    {
        $_SERVER['pivot_dirty_attributes'] = false;

        $user = PivotEventsTestUser::forceCreate([
            'email' => 'taylor@laravel.com',
        ]);

        $project = PivotEventsTestProject::forceCreate([
            'name' => 'Test Project',
        ]);

        $project->collaborators()->attach($user, ['permissions' => ['foo', 'bar'], 'role' => 'Developer']);

        $project->collaborators()->updateExistingPivot($user->id, ['role' => 'Lead Developer']);

        $this->assertSame(['role' => 'Lead Developer'], $_SERVER['pivot_dirty_attributes']);
    }
}

class PivotEventsTestUser extends Model
{
    public $table = 'users';
}

class PivotEventsTestProject extends Model
{
    public $table = 'projects';

    public function collaborators()
    {
        return $this->belongsToMany(
            PivotEventsTestUser::class, 'project_users', 'project_id', 'user_id'
        )->using(PivotEventsTestCollaborator::class);
    }

    public function contributors()
    {
        return $this->belongsToMany(PivotEventsTestUser::class, 'project_users', 'project_id', 'user_id')
            ->using(PivotEventsTestCollaborator::class)
            ->wherePivot('role', 'contributor');
    }
}

class PivotEventsTestCollaborator extends Pivot
{
    public $table = 'project_users';

    protected $casts = [
        'permissions' => 'json',
    ];

    public static $eventsCalled = [];

    public static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            static::$eventsCalled[] = 'creating';
        });

        static::created(function ($model) {
            static::$eventsCalled[] = 'created';
        });

        static::updating(function ($model) {
            static::$eventsCalled[] = 'updating';
        });

        static::updated(function ($model) {
            $_SERVER['pivot_attributes'] = $model->getAttributes();
            $_SERVER['pivot_dirty_attributes'] = $model->getDirty();
            static::$eventsCalled[] = 'updated';
        });

        static::saving(function ($model) {
            static::$eventsCalled[] = 'saving';
        });

        static::saved(function ($model) {
            static::$eventsCalled[] = 'saved';
        });

        static::deleting(function ($model) {
            static::$eventsCalled[] = 'deleting';
        });

        static::deleted(function ($model) {
            static::$eventsCalled[] = 'deleted';
        });
    }
}


text:
package jp.a34910.android.accelerogram2;

import java.util.Timer;
import java.util.TimerTask;

import android.os.Handler;

public abstract class PeriodicTask {
	/**
	 * 周期的に処理を行うための抽象クラス。
	 * 周期カウントはこのクラスのインスタンスで作るTimerのDaemonスレッドで行われる。
	 * periodicTaskOnUIThread()処理はこのインスタンスを作成したスレッドで実行する。
	 * periodicTaskOnTimerThread()処理はTimerのDaemonスレッドで実行する。
	 */
	private long period;
	private boolean isDaemon = true;
	private Timer timer;
	private TimerTask timerTask;
	private Handler handler;

	/**
	 * periodミリ秒の周期で動かす
	 * @param period 周期指定(ミリ秒)
	 */
	public PeriodicTask(long period) {
		this.handler = new Handler();
		this.period = period;
		this.timer = null;
	}

	/**
	 * 周期タスクの実行を開始する
	 */
	public void execute(){
		if (timer == null) { //timer == null(周期タスクは存在しない)
			timerTask = new TimerTask() {
				@Override
				public void run() {
					periodicTaskOnTimerThread();
					handler.post(new Runnable() {
						@Override
						public void run() {
							periodicTaskOnUIThread();
						}
					});
				}
			};
			timer = new Timer(isDaemon);
			timer.scheduleAtFixedRate(timerTask, period, period);
		}
	}

	/**
	 * 周期タスクの実行をキャンセルする
	 */
	public void cancel() {
		if(timer != null) {
			timer.cancel();
			timer = null;
		}
	}

	/**
	 * インスタンスを作成したスレッド(例えばUIスレッド)で処理させるTask
	 */
	abstract protected void periodicTaskOnUIThread();

	/**
	 * タイマースレッドで処理させるTask
	 * doPeriodicTaskの直前に呼ばれる。
	 */
	abstract protected void periodicTaskOnTimerThread();
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using TTengine.Core;
using Microsoft.Xna.Framework;
using TreeSharp;
using Artemis;
using Game1.Core;
using Game1.Comps;

namespace Game1.Behaviors
{
    ///
    /// lets a ThingComp chase another ThingComp when it's visible.
    ///
    public class ChaseBehavior: Behavior
    {
        /// followed target of this chase behavior
        public Entity ChaseTarget;

        /// chase range in pixels
        public float ChaseRange = 10.0f;

        /// range reached when chaser is satisfied and stops chasing (0 means chase all the way)
        public float SatisfiedRange = 0f;

        /// if true, inverts the Chase into an Avoid behavior
        public bool Avoidance = false;

        public ChaseBehavior(Entity chaseTarget)
        {
            this.ChaseTarget = chaseTarget;
        }

        public override IEnumerable<RunStatus> Execute(object context)
        {
            var ctx = context as BTAIContext;
            var tc = ctx.Entity.GetComponent<ThingComp>();

            if (ChaseTarget != null && ChaseTarget.IsActive)
            {
                var targetTc = ChaseTarget.GetComponent<ThingComp>();
                Vector2 dif;
                if (targetTc.Visible)
                {
                    dif = targetTc.Position - tc.Target;
                    float dist = dif.Length();
                    if (dist > 0f && dist <= ChaseRange && dist > SatisfiedRange)
                    {
                        // compute direction towards chase-target
                        dif = targetTc.Position - tc.Target;
                        if (Avoidance)
                            dif = -dif;
                        var tcc = ctx.Entity.GetComponent<ThingControlComp>();
                        tcc.TargetMove = dif;
                        tcc.DeltaTimeBetweenMoves = this.DeltaTimeBetweenMoves;
                        yield return RunStatus.Success;
                    }
                }
            }
            yield return RunStatus.Failure;
        }

    }
}


text:
<?php

namespace Canducci\ZipCode\Contracts;

use Canducci\ZipCode\ZipCodeResponse;

interface ZipCodeRequestContract
{
    /**
     * @param $url
     * @return mixed
     */
    public function get($url): ZipCodeResponse;
}


text:
: ${TCGAFMP_ROOT_DIR:?" environment variable must be set and non-empty; defines the path to the TCGA FMP scripts directory"}
source ${TCGAFMP_ROOT_DIR}/../../gidget/util/env.sh

# =============================================================================

# outer loop is over center
for c in bcgsc.ca broad.mit.edu genome.wustl.edu hgsc.bcm.edu ucsc.edu
    do
        echo " "
        echo " "
        date
        echo " ************************************************************** "
        echo " CENTER " $c

        # next loop is over platform / pipeline
        for p in abi illuminaga_dnaseq illuminaga_dnaseq_automated illuminaga_dnaseq_curated \
                 illuminahiseq_dnaseq illuminahiseq_dnaseq_automated illuminahiseq_dnaseq_curated \
                 mixed_dnaseq_curated solid_dnaseq
            do
                echo "     PLATFORM " $p

                # and then over tumors ...
                for d in `cat $TCGAFMP_ROOT_DIR/config/tumor_list.txt`
                    do
                        echo "         TUMOR " $d

	                cd $TCGAFMP_DCC_REPOSITORIES/dcc-mirror/public/tumor/

                        # check that tumor subdirectory exists ...
                        if [ ! -d "$d" ]; then
                            mkdir $d
                            chmod g+w $d
                        fi
                        cd $d

                        # check that "gsc" subdirectory exists ...
                        if [ ! -d "gsc" ]; then
                            mkdir gsc
                            chmod g+w gsc
                        fi
                        cd gsc

                        # check that center subdirectory exists ...
                        if [ ! -d "$c" ]; then
                            mkdir $c
                            chmod g+w $c
                        fi
                        cd $c

                        # check that platform subdirectory exists ...
                        if [ ! -d "$p" ]; then
                            mkdir $p
                            chmod g+w $p
                        fi
                        cd $p

                        # check that "mutations" subdirectory exists ...
                        if [ ! -d "mutations" ]; then
                            mkdir mutations
                            chmod g+w mutations
                        fi
                        cd mutations

                        echo "             CWD " `pwd`

	                rm -fr index.html
	                wget -e robots=off --wait 1 --debug --no-clobber --continue \
                             --server-response --no-directories \
	                     --accept "*Level_2*.tar.gz" --accept "*mage-tab*.tar.gz" \
                             --accept "*CHANGES*txt"  -R "*images*" \
	                     --verbose --recursive --level=1 \
	                     https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/$d/gsc/$c/$p/mutations

                    done
            done
    done


text:
import { isEmpty, isDate } from 'lodash';

import { Field } from './field';

export const DateFieldType = "date";

export class DateField extends Field {
  default: Date;

  type(): string {
    return DateFieldType;
  }

  serialize(): any {
    let res = super.serialize();
    if (isDate(this.default)) {
      res['default'] = this.default.toJSON();
    }
    return res;
  }

  deserialize(obj: any): DateField {
    super.deserialize(obj);
    if (!isEmpty(obj.default)) {
      this.default = new Date(obj.default);
    }
    return this;
  }
}


text:
Docker Images for Confluent Plaform
===

Docker images for deploying and running the Confluent Platform.  The images are currently available on [DockerHub](https://hub.docker.com/u/confluentinc/).  They are currently only available for Confluent Platform 3.0.1 and after.

Full documentation for using the images can be found [here](http://docs.confluent.io/current/cp-docker-images/docs/intro.html).

# Important Caveat - Images Not Supported for Docker for Mac

We recommend not using these images with Docker for Mac at this time.  There are a couple of reasons for this:  first, Docker for Mac does not add hostname to `/etc/hosts`.  Kafka needs the hostname to be resolveable.  Furthermore, the semantics for `--net=host` are not clear, so you are likely to encounter issues if using host networking on Docker for Mac.  For more details on these known issues, you can refer to the following links:

* [Hostname Issue](https://forums.docker.com/t/docker-for-mac-does-not-add-docker-hostname-to-etc-hosts/8620/4)
* Host networking on Docker for Mac: [link 1](https://forums.docker.com/t/should-docker-run-net-host-work/14215), [link 2](https://forums.docker.com/t/net-host-does-not-work/17378/7), [link 3](https://forums.docker.com/t/explain-networking-known-limitations-explain-host/15205/4)

# Contribute

Start by reading our guidelines on contributing to this project found [here](http://docs.confluent.io/current/docker/contributing.html).

- Source Code: https://github.com/confluentinc/cp-docker-images
- Issue Tracker: https://github.com/confluentinc/cp-docker-images/issues

# License

The project is licensed under the Apache 2 license. For more information on the licenses for each of the individual Confluent Platform components packaged in the images, please refer to the respective [Confluent Platform documentation for each component](http://docs.confluent.io/current/platform.html).


text:
import unittest
from datetime import datetime

from pymap.flags import FlagOp, PermanentFlags, SessionFlags
from pymap.message import BaseMessage
from pymap.parsing.command.select import SearchCommand, UidSearchCommand
from pymap.parsing.response import ResponseOk
from pymap.parsing.specials import SequenceSet, ObjectId
from pymap.parsing.specials.flag import Seen, Flagged, Flag
from pymap.selected import SelectedMailbox

_Keyword = Flag(b'$Keyword')

class _Message(BaseMessage):

    async def load_content(self, requirement):
        raise RuntimeError()

class TestSelectedMailbox(unittest.TestCase):

    def setUp(self) -> None:
        self.response = ResponseOk(b'.', b'testing')

    @classmethod
    def new_selected(cls, guid: bytes = b'test') -> SelectedMailbox:
        return SelectedMailbox(ObjectId(guid), False,
                               PermanentFlags([Seen, Flagged]),
                               SessionFlags([_Keyword]))

    @classmethod
    def set_messages(cls, selected: SelectedMailbox,
                     expunged, messages) -> None:
        updates = [_Message(uid, datetime.now(), flags)
                   for uid, flags in messages]
        selected.add_updates(updates, expunged)

    @property
    def command(self) -> SearchCommand:
        return SearchCommand(b'.', [], None)

    @property
    def uid_command(self) -> SearchCommand:
        return UidSearchCommand(b'.', [], None)

    def test_add_untagged_recent_equal(self) -> None:
        selected = self.new_selected()
        selected.session_flags.add_recent(1)
        selected.session_flags.add_recent(2)
        self.set_messages(selected, [],
                          [(1, []), (2, [])])
        forked, _ = selected.fork(self.command)
        self.set_messages(forked, [],
                          [(1, []), (2, [])])
        _, untagged = forked.fork(self.command)
        self.response.add_untagged(*untagged)
        self.assertEqual(b'. OK testing\r\n', bytes(self.response))

    def test_add_untagged_recent_increase(self) -> None:
        selected = self.new_selected()
        selected.session_flags.add_recent(1)
        selected.session_flags.add_recent(2)
        self.set_messages(selected, [],
                          [(1, []), (2, []), (3, [])])
        forked, _ = selected.fork(self.command)
        forked.session_flags.add_recent(3)
        self.set_messages(forked, [], [])
        _, untagged = forked.fork(self.command)
        self.response.add_untagged(*untagged)
        self.assertEqual(b'* 3 RECENT\r\n'
                         b'* 3 FETCH (FLAGS (\\Recent))\r\n'
                         b'. OK testing\r\n', bytes(self.response))

    def test_add_untagged_session_flag_add(self) -> None:
        selected = self.new_selected()
        self.set_messages(selected, [],
                          [(1, []), (2, [Seen]), (3, [])])
        forked, _ = selected.fork(self.command)
        forked.session_flags.update(2, [_Keyword], FlagOp.ADD)
        self.set_messages(forked, [], [])
        _, untagged = forked.fork(self.command)
        self.response.add_untagged(*untagged)
        self.assertEqual(b'* 2 FETCH (FLAGS (\\Seen $Keyword))\r\n'
                         b'. OK testing\r\n', bytes(self.response))

    def test_add_untagged_recent_expunge(self) -> None:
        selected = self.new_selected()
        selected.session_flags.add_recent(1)
        selected.session_flags.add_recent(2)
        self.set_messages(selected, [],
                          [(1, []), (2, []), (3, [])])
        forked, _ = selected.fork(self.command)
        self.set_messages(forked, [2, 3],
                          [(1, [])])
        _, untagged = forked.fork(self.command)
        self.response.add_untagged(*untagged)
        self.assertEqual(b'* 3 EXPUNGE\r\n'
                         b'* 2 EXPUNGE\r\n'
                         b'* 1 RECENT\r\n'
                         b'. OK testing\r\n', bytes(self.response))

    def test_add_untagged_equal(self) -> None:
        selected = self.new_selected()
        self.set_messages(selected, [],
                          [(1, []), (2, [])])
        forked, _ = selected.fork(self.command)
        self.set_messages(forked, [],
                          [(1, []), (2, [])])
        _, untagged = forked.fork(self.command)
        self.response.add_untagged(*untagged)
        self.assertEqual(b'. OK testing\r\n', bytes(self.response))

    def test_add_untagged_fetch(self) -> None:
        selected = self.new_selected()
        self.set_messages(selected, [],
                          [(1, []), (2, [])])
        forked, _ = selected.fork(self.command)
        self.set_messages(forked, [],
                          [(2, [Seen]), (3, [Seen, Flagged]), (4, [])])
        _, untagged = forked.fork(self.command)
        self.response.add_untagged(*untagged)
        self.assertEqual(b'* 4 EXISTS\r\n'
                         b'* 2 FETCH (FLAGS (\\Seen))\r\n'
                         b'* 3 FETCH (FLAGS (\\Flagged \\Seen))\r\n'
                         b'* 4 FETCH (FLAGS ())\r\n'
                         b'. OK testing\r\n', bytes(self.response))

    def test_add_untagged_fetch_uid(self) -> None:
        selected = self.new_selected()
        self.set_messages(selected, [],
                          [(1, []), (2, [])])
        forked, _ = selected.fork(self.uid_command)
        self.set_messages(forked, [],
                          [(2, [Seen]), (3, [Seen, Flagged]), (4, [])])
        _, untagged = forked.fork(self.uid_command)
        self.response.add_untagged(*untagged)
        self.assertEqual(b'* 4 EXISTS\r\n'
                         b'* 2 FETCH (FLAGS (\\Seen) UID 2)\r\n'
                         b'* 3 FETCH (FLAGS (\\Flagged \\Seen) UID 3)\r\n'
                         b'* 4 FETCH (FLAGS () UID 4)\r\n'
                         b'. OK testing\r\n', bytes(self.response))

    def test_add_untagged_fetch_silenced(self) -> None:
        selected = self.new_selected()
        self.set_messages(selected, [],
                          [(1, []), (2, []), (3, [Seen, Flagged]),
                           (4, [Seen, Flagged]), (5, [Flagged]), (6, [Seen])])
        forked, _ = selected.fork(self.uid_command)
        forked.silence(SequenceSet.build([1, 2]),
                       frozenset([Seen]), FlagOp.ADD)
        forked.silence(SequenceSet.build([3, 4]),
                       frozenset([Seen]), FlagOp.DELETE)
        forked.silence(SequenceSet.build([5, 6]),
                       frozenset([Seen]), FlagOp.REPLACE)
        self.set_messages(forked, [],
                          [(1, [Seen, Flagged]), (2, [Seen]), (3, []),
                           (4, [Flagged]), (5, [Seen, Flagged]), (6, [Seen])])
        _, untagged = forked.fork(self.uid_command)
        self.response.add_untagged(*untagged)
        self.assertEqual(b'* 1 FETCH (FLAGS (\\Flagged \\Seen) UID 1)\r\n'
                         b'* 3 FETCH (FLAGS () UID 3)\r\n'
                         b'* 5 FETCH (FLAGS (\\Flagged \\Seen) UID 5)\r\n'
                         b'. OK testing\r\n', bytes(self.response))

    def test_add_untagged_expunge_hidden(self) -> None:
        selected = self.new_selected()
        self.set_messages(selected, [],
                          [(1, []), (2, []), (3, []), (4, [])])
        forked, _ = selected.fork(self.command)
        forked.hide_expunged = True
        self.set_messages(forked, [2, 3],
                          [(5, [Flagged])])
        _, untagged = forked.fork(self.command)
        self.response.add_untagged(*untagged)
        self.assertEqual(b'* 5 EXISTS\r\n'
                         b'* 5 FETCH (FLAGS (\\Flagged))\r\n'
                         b'. OK testing\r\n', bytes(self.response))

    def test_add_untagged_expunge(self) -> None:
        selected = self.new_selected()
        self.set_messages(selected, [],
                          [(1, []), (2, []), (3, []), (4, [])])
        forked, _ = selected.fork(self.command)
        self.set_messages(forked, [2, 3],
                          [(5, [])])
        _, untagged = forked.fork(self.command)
        self.response.add_untagged(*untagged)
        self.assertEqual(b'* 3 EXPUNGE\r\n'
                         b'* 2 EXPUNGE\r\n'
                         b'* 3 EXISTS\r\n'
                         b'* 3 FETCH (FLAGS ())\r\n'
                         b'. OK testing\r\n', bytes(self.response))

    def test_add_untagged_all(self) -> None:
        selected = self.new_selected()
        self.set_messages(selected, [],
                          [(1, [Flagged]), (2, []), (3, [])])
        forked, _ = selected.fork(self.uid_command)
        selected.session_flags.add_recent(6)
        self.set_messages(forked, [2, 3],
                          [(1, [Seen, Flagged]), (4, [Seen]), (5, [Seen]),
                           (6, [Flagged]), (7, [Seen])])
        _, untagged = forked.fork(self.uid_command)
        self.response.add_untagged(*untagged)
        self.assertEqual(b'* 3 EXPUNGE\r\n'
                         b'* 2 EXPUNGE\r\n'
                         b'* 5 EXISTS\r\n'
                         b'* 1 RECENT\r\n'
                         b'* 1 FETCH (FLAGS (\\Flagged \\Seen) UID 1)\r\n'
                         b'* 2 FETCH (FLAGS (\\Seen) UID 4)\r\n'
                         b'* 3 FETCH (FLAGS (\\Seen) UID 5)\r\n'
                         b'* 4 FETCH (FLAGS (\\Flagged \\Recent) UID 6)\r\n'
                         b'* 5 FETCH (FLAGS (\\Seen) UID 7)\r\n'
                         b'. OK testing\r\n', bytes(self.response))

    def test_add_untagged_deleted_bye(self) -> None:
        selected = self.new_selected()
        self.set_messages(selected, [],
                          [(1, [])])
        forked, _ = selected.fork(self.command)
        self.set_messages(forked, [1],
                          [(2, [])])
        forked.set_deleted()
        _, untagged = forked.fork(self.command)
        self.response.add_untagged(*untagged)
        self.assertEqual(b'* BYE Selected mailbox no longer exists.\r\n'
                         b'. OK testing\r\n', bytes(self.response))


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Essential CSS Libraries for Web Designers - Lesson 03</title>

        <link rel="stylesheet" href="bower_components/hover/css/hover-min.css" media="screen">
        <link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css" media="screen">

A simple example of using Hover.css

            This is a simple button.

        This is a button

            Here's another button with an icon inside it.

        Subscribe

                This is the container content.


text:
import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Platform,
    TouchableOpacity,
    StatusBar,
    AsyncStorage
} from 'react-native';

import { Toast,ActivityIndicator } from  'antd-mobile'
import Coupons_Item from './component/List_Item_Coupons'
import config from '../../utils/Config'//接口配置
import { netRequest } from '../../utils/FetchRequest'//网络请求方法
import { NullPage , NoNetPage }from '../../components/NullPage'
import RefreshListView, {RefreshState} from '../../components/MyRefreshFlatList'

export default class Coupons extends Component {
    // 获取
    async get(key) {
        return AsyncStorage.getItem(key).then((value) => {
            const jsonValue = JSON.parse(value);
            this.setState({
                userInfo:jsonValue
            })
            return jsonValue;
        });
    }
    static navigationOptions=({navigation,screenProps})=>({
        headerTitle:'优惠券',
        headerTitleStyle:{
            fontSize:18,
            color:'white'
        },
    });

    constructor(props) {
        super(props);

        this.state = {
            dataList: "",
            refreshState: RefreshState.Idle,
            animating:false
        }
    }

    componentDidMount() {
        this.get('userInfo').then(()=>this._fetchData());
    }

    render() {
        return (
            <View style={styles.container}>
                <StatusBar barStyle={'light-content'} />
                {this._renderList()}
            </View>
        )
    }

    _renderList() {
        // if(this.state.dataList!="") {
            if (this.state.dataList.length > 0) {
                return (
                    <RefreshListView
                        data={this.state.dataList}
                        keyExtractor={this.keyExtractor}
                        renderItem={this._renderRow}

                        refreshState={this.state.refreshState}
                        onHeaderRefresh={this.onHeaderRefresh}

                    />

                )
            } else {
                return ( isNet ? this.NullPage() : <NoNetPage/> );
            }
        // }
    }

    NullPage(){
        return(
            <View style={{flex:1,backgroundColor:'#fff',alignItems:'center'}}>
                <ActivityIndicator
                    size='large'
                    color="#1aa0f7"
                    text="正在加载..."
                    toast={true}
                    animating={this.state.animating}
                />
                <Image style={{marginTop:140}} source={require('../../image/dingdan/cry.png')}/>
                <Text style={{marginTop:20}}>暂无优惠卷</Text>
                <View style={{width:100,height:30,borderWidth:1,borderRadius:5,marginTop:10,borderColor:'#1aa0f7',justifyContent:'center',alignItems:'center'}}>
                    <Text style={{color:'#1aa0f7'}} onPress={()=>this._fetchData()}>
                        点击刷新
                    </Text>
                </View>

            </View>
        )
    }

    _fetchData() {
        this.setState({
            animating:true
        })
        this.setState({refreshState: RefreshState.HeaderRefreshing})
        netRequest(
            config.api.base + config.api.youhuiquan,
            {
                userid:this.state.userInfo.id,
                sign: '1',//
            },

            (data)=>{
                console.log('返回的数据为data---',data)
                if (data.code =='1'){
                    this.setState({
                        dataList:data.data,
                        refreshState: RefreshState.Idle,
                        animating:false
                    });
                    // Toast.success('查询列表成功',1)
                }

            },
            (err)=>{
                this.setState({refreshState: RefreshState.Idle})
                // console.error(err)
                Toast.info('请求数据失败',1)
            },
            ()=> {
                this.setState({refreshState: RefreshState.Idle})
                Toast.offline('当前网络不可用')
            }
        )

    }

    keyExtractor = (item: any, index: number) => {
        return index
    }

    _renderRow = (rowData) => {
        console.log('rowData-->',rowData.item.couponname);
        rowData =rowData.item
        return (
            <Coupons_Item
                onPress={() => this.cellOnPress()}
                rowData={rowData}
            />

        );
    }

    cellOnPress(){
        // alert('4444')
    }

    //下拉刷新
    onHeaderRefresh = () => {
        this.setState({refreshState: RefreshState.HeaderRefreshing})

        netRequest(
            config.api.base + config.api.youhuiquan,
            {
                userid:this.state.userInfo.id,
                sign: '1',//
            },

            (data)=>{
                console.log('下拉刷新返回的数据为data---',data)
                this.setState({
                    refreshState: RefreshState.Idle,
                    dataList:data.data,
                });
            },
            (err)=>{
                this.setState({ refreshState: RefreshState.Idle });
                // console.error(err)
                Toast.info('请求数据失败',1)
            },
            ()=> {
                this.setState({ refreshState: RefreshState.Idle});
                Toast.offline('当前网络不可用')
            }
        )

    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginTop: Platform.OS == 'ios' ? 0 : 0,
    },
    title: {
        fontSize: 18,
        height: 84,
        textAlign: 'center'
    }
})


text:
package cz.lukashruby.api.xml.shoptet;

import javax.xml.bind.annotation.XmlRegistry;

@XmlRegistry
public class ObjectFactory {

    public ObjectFactory() {
    }

    public SHOP createSHOP() {
        return new SHOP();
    }

    public SHOPITEM createSHOPSHOPITEM() {
        return new SHOPITEM();
    }

    public VARIANTS createSHOPSHOPITEMVARIANTS() {
        return new VARIANTS();
    }

    public VARIANT createSHOPSHOPITEMVARIANTSVARIANT() {
        return new VARIANT();
    }

    public PARAMETERS createSHOPSHOPITEMVARIANTSVARIANTPARAMETERS() {
        return new PARAMETERS();
    }

    public TEXTPROPERTIES createSHOPSHOPITEMTEXTPROPERTIES() {
        return new TEXTPROPERTIES();
    }

    public CATEGORIES createSHOPSHOPITEMCATEGORIES() {
        return new CATEGORIES();
    }

    public IMAGES createSHOPSHOPITEMIMAGES() {
        return new IMAGES();
    }

    public RELATEDPRODUCTS createSHOPSHOPITEMRELATEDPRODUCTS() {
        return new RELATEDPRODUCTS();
    }

    public ALTERNATIVEPRODUCTS createSHOPSHOPITEMALTERNATIVEPRODUCTS() {
        return new ALTERNATIVEPRODUCTS();
    }

    public FLAGS createSHOPSHOPITEMFLAGS() {
        return new FLAGS();
    }

    public STOCK createSHOPSHOPITEMSTOCK() {
        return new STOCK();
    }

    public PARAMETER createSHOPSHOPITEMVARIANTSVARIANTPARAMETERSPARAMETER() {
        return new PARAMETER();
    }

    public TEXTPROPERTY createSHOPSHOPITEMTEXTPROPERTIESTEXTPROPERTY() {
        return new TEXTPROPERTY();
    }

}


text:
"""API payload decoders."""

import json
from typing import Dict, Union

from rbtools.api.utils import parse_mimetype
from rbtools.utils.encoding import force_unicode

def DefaultDecoder(
    payload: Union[bytes, str],
) -> Dict:
    """Default decoder for API payloads.

    The default decoder is used when a decoder is not found in the
    DECODER_MAP. This will stick the body of the response into the
    'data' field.

    Args:
        payload (bytes or str):
            The API payload.

    Returns:
        dict:
        The decoded API object.
    """
    return {
        'resource': {
            'data': payload,
        },
    }

def JsonDecoder(
    payload: Union[bytes, str],
) -> Dict:
    """Decode an application/json-encoded API response.

    Args:
        payload (bytes or str):
            The API payload.

    Returns:
        dict:
        The decoded API object.
    """
    return json.loads(force_unicode(payload))

#: Mapping from API format to decoder method.
#:
#: Type: dict
DECODER_MAP = {
    'application/json': JsonDecoder,
}

def decode_response(
    payload: Union[bytes, str],
    mime_type: str,
) -> Dict:
    """Decode a Web API response.

    The body of a Web API response will be decoded into a dictionary,
    according to the provided mime_type.
    """
    mime = parse_mimetype(mime_type)

    format = '%s/%s' % (mime['main_type'], mime['format'])
    decoder = DECODER_MAP.get(format, DefaultDecoder)

    return decoder(payload)


text:
'use strict';

module.exports = {
	compare
}

function compareOnYear(date1, date2)
{
	return date1
}

function compareIfAlreadyExists(date) {
  var now = new Date();

  return date.getFullYear() <= now.getFullYear() &&
         date.getMonth() <= now.getMonth() &&
         date.getDay() <= now.getDay() &&
         date.getHours() <= now.getHours() &&
         date.getMinutes() <= now.getMinutes() &&
         date.getSeconds() <= now.getSecondes()
}

module.exports = ;


text:
package com.github.thesmartenergy.ontop.jersey;

import com.github.thesmartenergy.ontop.OntopException;
import com.github.thesmartenergy.rdfp.RDFP;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.ws.rs.core.MediaType;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.system.stream.LocationMapper;
import org.apache.jena.riot.system.stream.StreamManager;
import org.apache.jena.vocabulary.RDFS;

/**
 * A representations map is generated from a turtle document. It is parsed by
 * the dependency to be used by jersey filters and resources.
 *
 * @author Maxime Lefrançois <maxime.lefrancois at emse.fr>
 */
public class RepresentationsMap {

    private static final Logger LOG = Logger.getLogger(RepresentationsMap.class.getSimpleName());

    private static RepresentationsMap INSTANCE = null;

    static RepresentationsMap get(String base) {
        if (base == null) {
            throw new NullPointerException();
        }
        if (INSTANCE == null) {
            INSTANCE = new RepresentationsMap(base);
        }
        if (!INSTANCE.base.equals(base)) {
            throw new IllegalArgumentException();
        }
        return INSTANCE;
    }

    private final String base;

    /**
     * value rdfs:isDefinedBy key
     */
    private final Map<String, String> redirections = new HashMap<>();

    /**
     * value ontop:alias key
     */
    private final Map<String, String> aliases = new HashMap<>();

    /**
     * key ontop:representedBy one of values
     */
    private final Map<String, Set<Representation>> multiRepresentations = new HashMap<>();

    /**
     * key ontop:mediaType some media type
     */
    private final Map<String, Representation> representations = new HashMap<>();

    private Model conf = null;

    private LocationMapper loc;

    private RepresentationsMap(String base) {
        this.base = base;
        System.out.println("Constructing representations map...");

        loc = StreamManager.get().getLocationMapper();

        final String confpath = "_ontop/config.ttl";
        try {
            conf = RDFDataMgr.loadModel(RepresentationsMap.class.getClassLoader().getResource(confpath).toURI().toString());
        } catch (Exception ex) {
            LOG.warning("Configuration file '" + confpath + "'. ONTOP will be disabled.");
            return;
        }

        try {
            readRedirections();
        } catch (OntopException ex) {
            throw new RuntimeException(ex);
        }

        try {
            readAliases();
        } catch (OntopException ex) {
            throw new RuntimeException(ex);
        }

        try {
            readRepresentations();
        } catch (OntopException ex) {
            throw new RuntimeException(ex);
        }

        try {
            readMultiRepresentations();
        } catch (OntopException ex) {
            throw new RuntimeException(ex);
        }

        // close alts.
        boolean changed = true;
        while (changed) {
            changed = false;
            Iterator<String> it = loc.listAltEntries();
            Set<String> entries = new HashSet<>();
            while (it.hasNext()) {
                entries.add(it.next());
            }
            for (String entry : entries) {
                String target = loc.getAltEntry(entry);
                if (entry.equals(target)) {
                    loc.removeAltEntry(entry);
                    continue;
                }
                String targetTarget = loc.getAltEntry(target);
                if (target.equals(targetTarget)) {
                    loc.removeAltEntry(target);
                    continue;
                }
                if (targetTarget != null) {
                    loc.removeAltEntry(entry);
                    loc.addAltEntry(entry, targetTarget);
                    changed = true;
                }
                System.out.println("");
            }
        }
        System.out.println("Jena StreamManager FileLocator contains:");
        Iterator<String> it = loc.listAltEntries();
        while (it.hasNext()) {
            String entry = it.next();
            System.out.println("Entry " + entry + " --> " + loc.getAltEntry(entry));
        }
    }

    public Map<String, String> getRedirections() {
        return redirections;
    }

    public Map<String, String> getAliases() {
        return aliases;
    }

    public Map<String, Set<Representation>> getMultiRepresentations() {
        return multiRepresentations;
    }

    public Map<String, Representation> getRepresentations() {
        return representations;
    }

    private void readRedirections() throws OntopException {
        StmtIterator sit = conf.listStatements(null, RDFS.isDefinedBy, (RDFNode) null);
        while (sit.hasNext()) {
            Statement s = sit.next();
            final Resource subject = s.getSubject();
            final RDFNode object = s.getObject();
            if (!subject.isURIResource()) {
                throw new OntopException("resource " + subject + " should be a URI resource");
            }
            if (!object.isURIResource()) {
                throw new OntopException("resource " + object + " should be a URI resource");
            }
            try {
                String source = getLocalPath(subject.getURI());
                String target = getLocalPath(object.asResource().getURI());
                redirections.put(source, target);
                loc.addAltEntry(subject.getURI(), object.asResource().getURI());
                System.out.println("redirection " + subject.getURI() + " -> " + object.asResource().getURI());
            } catch (OntopException ex) {
                throw new OntopException(ex.getMessage());
            }
        }

    }

    private void readRepresentations() throws OntopException {
        StmtIterator sit = conf.listStatements(null, RDFP.mediaType, (RDFNode) null);
        while (sit.hasNext()) {
            Statement s = sit.next();
            final Resource subject = s.getSubject();
            final RDFNode object = s.getObject();
            if (!subject.isURIResource()) {
                throw new OntopException("resource " + subject + " should be a URI resource");
            }
            if (!object.isLiteral()) {
                throw new OntopException("resource " + object + " should be a literal");
            }
            try {
                String localPath = getLocalPath(subject.getURI());
                MediaType mt = MediaType.valueOf(object.asLiteral().getLexicalForm());
                Representation representation = new Representation(mt, localPath);
                representations.put(localPath, representation);
                try {
                    String localUrl = RepresentationsMap.class.getClassLoader().getResource(representation.getLocalPath()).toString();
                    loc.addAltEntry(base + localPath, localUrl);
                    System.out.println("new RDF representation " + base + localPath + " -> " + localUrl);
                } catch (Exception ex) {
                }
            } catch (Exception ex) {
                throw new OntopException(ex.getClass().getName() + ": " + ex.getMessage());
            }
        }
    }

    private void readMultiRepresentations() throws OntopException {
        StmtIterator sit = conf.listStatements(null, RDFP.representedBy, (RDFNode) null);
        while (sit.hasNext()) {
            Statement s = sit.next();
            final Resource subject = s.getSubject();
            final RDFNode object = s.getObject();
            if (!subject.isURIResource()) {
                throw new OntopException("resource " + subject + " should be a URI resource");
            }
            if (!object.isURIResource()) {
                throw new OntopException("resource " + object + " should be a URI resource");
            }
            try {
                String localPath = getLocalPath(subject.getURI());
                String objectLocalPath = getLocalPath(object.asResource().getURI());
                Representation representation = representations.get(objectLocalPath);
                if (representation == null) {
                    throw new OntopException("representation should not be null for " + objectLocalPath);
                }
                Set<Representation> set = multiRepresentations.get(localPath);
                if (set == null) {
                    set = new HashSet<>();
                    multiRepresentations.put(localPath, set);
                }
                set.add(representation);
                loc.addAltEntry(subject.getURI(), object.asResource().getURI());
                System.out.println("new multi-representation " + subject.getURI() + " -> " + object.asResource().getURI());
            } catch (Exception ex) {
                throw new OntopException(ex.getClass().getName() + ": " + ex.getMessage());
            }
        }
    }

    private void readAliases() throws OntopException {
        StmtIterator sit = conf.listStatements(null, RDFP.alias, (RDFNode) null);
        while (sit.hasNext()) {
            Statement s = sit.next();

            final Resource subject = s.getSubject();
            final RDFNode object = s.getObject();
            if (!subject.isURIResource()) {
                throw new OntopException("resource " + subject + " should be a URI resource");
            }
            if (!object.isURIResource()) {
                throw new OntopException("resource " + object + " should be a URI resource");
            }
            try {
                String localPath = getLocalPath(subject.getURI());
                String aliasLocalPath = getLocalPath(object.asResource().getURI());
                aliases.put(aliasLocalPath, localPath);
                loc.addAltEntry(object.asResource().getURI(), subject.getURI());
                System.out.println("new alias " + object.asResource().getURI() + " -> " + subject.getURI());
            } catch (Exception ex) {
                throw new OntopException(ex.getClass().getName() + ": " + ex.getMessage());
            }
        }
    }

    private String getLocalPath(String path) throws OntopException {
        if (!path.startsWith(base)) {
            throw new OntopException("path must start with " + base + ". got " + path);
        }
        return path.substring(base.length());
    }

}


text:
def pad!(array, min_size, value = nil) #destructive
  if min_size <= array.length
    return array
  else
    difference = min_size - array.length
    for i in 1..difference
      array.push(value)
    end
    return array
  end
end

def pad(array, min_size, value = nil) #non-destructive
  new_array = Array.new
  new_array = array.clone
  if min_size <= array.length
    return new_array
  else
    difference = min_size - array.length
    for i in 1..difference
      new_array.push(value)
    end
    return new_array
  end
end

# 3. Refactored Solution
def pad!(array, min_size, value = nil) #destructive
  array.fill(value, array.length...min_size)
end

def pad(array, min_size, value = nil) #non-destructive
  new_array = Array.new
  new_array = array.clone
  new_array.fill(value, array.length...min_size)
end
# 4. Reflection
=begin
Were you successful in breaking the problem down into small steps?
Yes, writing out the pseudocode helped give us an idea of how to code the problem.
Once you had written your pseudocode, were you able to easily translate it into code? What difficulties and successes did you have?
Yes, the most difficult part was just figuring out what the problem was asking and what if/else checks we needed to make.
Was your initial solution successful at passing the tests? If so, why do you think that is? If not, what were the errors you encountered and what did you do to resolve them?
Yes our initial solution was successful at passing the tests. The problem that took us longest to figure out was making the pad method non-destructive. It took us aawhile to figure out how to make a new array that was based on the original array.
When you refactored, did you find any existing methods in Ruby to clean up your code?
Yes, we found a method fill that is basically a built-in method for adding padding to an array.
How readable is your solution? Did you and your pair choose descriptive variable names? We didn't have many new variables but I think the names we chose made sense.
What is the difference between destructive and non-destructive methods in your own words?
Destructive modifies the original data structure while non-destructive creates a new data structure to modify and returns that in lieu of the original.
=end


text:
using namespace charto;

template class charto::QuadTree<Tile<double, double>>;
template class charto::QuadTree<Tile<uint32_t, uint16_t>>;

typedef QuadTree<Tile<double, double>> BigTree;
typedef QuadTree<Tile<uint32_t, uint16_t>> SmallTree;

#include "nbind/nbind.h"

NBIND_CLASS(BigTree, Tree) {}

NBIND_CLASS(SmallTree) {}


text:
package cn.byhieg.betterload.operator;

import rx.Observable;
import rx.functions.Func1;
import rx.functions.Function;

/**
 * Created by byhieg on 17/5/12.
 * Contact with byhieg@gmail.com
 */

public interface BaseFlatMapOp<T,R> extends Func1<T, Observable<R>>{

}


text:
gcloud compute instances delete launcher-eu --zone europe-west3-a --quiet
gcloud compute instances create "launcher-eu" --description "This instance is for calling your services from Europe" --zone "europe-west3-a" --machine-type "g1-small" --subnet "default" --maintenance-policy "MIGRATE" --image-family "debian-9" --image-project "debian-cloud" --boot-disk-size "10" --boot-disk-type "pd-standard" --boot-disk-device-name "launcher-eu" --metadata 'startup-script=#!/bin/bash
sudo su
apt-get update
apt-get install apache2-utils -y
apt-get install git-core -y
git clone https://github.com/favsto/intech-compute-balancing/
rm -rf /usr/local/intech
mv intech-compute-balancing/support/help/ /usr/local/intech
rm -rf intech-compute-balancing/support/help/
cd /usr/local/intech
chmod +x *.sh'

gcloud compute instances delete launcher-us --zone us-east4-a --quiet
gcloud compute instances create "launcher-us" --description "This instance is for calling your services from America" --zone "us-east4-a" --machine-type "g1-small" --subnet "default" --maintenance-policy "MIGRATE" --image-family "debian-9" --image-project "debian-cloud" --boot-disk-size "10" --boot-disk-type "pd-standard" --boot-disk-device-name "launcher-us" --metadata 'startup-script=#!/bin/bash
sudo su
apt-get update
apt-get install apache2-utils -y
apt-get install git-core -y
git clone https://github.com/favsto/intech-compute-balancing/
rm -rf /usr/local/intech
mv intech-compute-balancing/support/help/ /usr/local/intech
rm -rf intech-compute-balancing/support/help/
cd /usr/local/intech
chmod +x *.sh'


text:
package fast.glibrary.views;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.EditText;

import fast.glibrary.R;

/**
 * Created by gege on 2016/12/15.
 */
public class TextIndentEditText extends EditText {

    private String str = "";
    private String itemSuf = "";

    public TextIndentEditText(Context context) {

        super(context);
        init(context, null, 0, 0);
    }

    public TextIndentEditText(Context context, AttributeSet attrs) {

        super(context, attrs);
        init(context, attrs, 0, 0);

    }

    @TargetApi(21)
    public TextIndentEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs, defStyleAttr, defStyleRes);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        if (attrs != null) {
            TypedArray a = context.getTheme().obtainStyledAttributes(
                    attrs,
                    R.styleable.TextIndentEditText,
                    defStyleAttr,
                    defStyleAttr
            );
            itemSuf = a.getString(R.styleable.TextIndentEditText_itemSuf);
            a.recycle();
        }
        for (int i = 0; i < itemSuf.length(); i++) {
            str += "\u3000";
        }
    }

    public TextIndentEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle, 0);
    }

    public void setStr(String str) {
        this.str = str;
    }

    @Override

    protected void onDraw(Canvas canvas) {
        if (!getText().toString().startsWith(str) && getText().length() >= str.length()) {
            this.setText(str + getText().toString());
        }
        if (getText().length() < str.length()) {
            this.setText(str);
        }
        if (getSelectionEnd() < str.length()) {
            setSelection(str.length());
        }
        super.onDraw(canvas);
    }

}


text:
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

namespace SalaryCalculator.Data.Contracts
{
    public interface ISalaryCalculatorDbContext : IDisposable
    {
        DbSet<TEntity> Set<TEntity>() where TEntity : class;

        DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;

        int SaveChanges();
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send"
        android:id="@+id/button"
        android:onClick="send"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:singleLine="false"
        android:layout_above="@+id/button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignRight="@+id/button2"
        android:layout_alignEnd="@+id/button2" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView"
        android:maxLines = "255"
        android:scrollbars = "vertical"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/editText"
        android:layout_alignEnd="@+id/editText"
        android:layout_above="@+id/editText" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Clear"
        android:id="@+id/button2"
        android:onClick="clear"
        android:layout_alignTop="@+id/button4"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button4"
        android:onClick="drops"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>


text:
require "qaxqa/testcase"
require "qaxqa/testsuite"
require "qaxqa/step"

module Qaxqa

	# Module class to set XML parsed attributes
	class AllSuite

		attr_accessor :testsuites, :doc

		def initialize(path = nil)
			@testsuites = []
			@doc = nil
			fetch! path unless path.nil?
		end

		private

		def fetch!(path)
			require 'nokogiri'
			@doc = Nokogiri::XML(File.open(path))

			@testsuites = Testsuite.parse(@doc)
		end

	end

end


text:
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var exporter = require(__dirname + '/../../lib/exporter.js');

// enabling production mode requires that all exporter remote calls
// have correct signatures included. for testing, this is disabled.
// process.env.NODE_ENV = 'production';
// var signatures = [ ... ];

var app = express();

// support cors by default - again this is an example server
app.use(cors());

// create application/json parser
var jsonParser = bodyParser.json();

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });

app.use(urlencodedParser);
app.use(jsonParser);

// expose a demo in index.html
app.use('/', express.static(__dirname + '/public'));

app.post('/export', urlencodedParser, function (req, res) {
  if (!req.body) {
    return res.sendStatus(400);
  }

  var commands = req.body;
  var saver = commands.saver;

  if (process.env.EXPORT_ROOT) {
    commands.root = process.env.EXPORT_ROOT;
  }

  exporter().config({
    // this would be populated with hashes in production mode
    // signatures: signatures,
  })
  .remote(commands)
  .save(saver.filename, saver.type, saver.args.pop())
  .then(function (saver) {
    res.writeHead(200, 'OK', {
      'Content-Type': saver.mime,
      'Content-Disposition': 'inline; filename=' + saver.filename,
    });
    saver.pipe(res);
  })
  .catch(function (error) {
    console.log(error.stack);
    res.status(500).send(error.message);
  });
});

// test endpoint to catch 404s...
app.get('*', function (req, res) {
  res.end('pong');
});

app.listen(process.env.PORT || 8000, function (server) {
  console.log('Running on http://localhost:' + (process.env.PORT || 8000));
});


text:
/**
 * User
 *
 * @module      :: Model
 * @description :: This is the base user model
 * @docs        :: http://waterlock.ninja/documentation
 */

module.exports = {

  attributes: require('waterlock').models.user.attributes({

    name: {
      type: 'string',
      required: true,
      minLength: 2
    },
    last_name: {
      type: 'string',
      required: true,
      minLength: 2
    },
    email: {
      type: 'string',
      email: true,
      required: true,
      unique: true
    },
    encrypted_password: {
      type: 'string'
    }

  }),

  beforeCreate: require('waterlock').models.user.beforeCreate,
  beforeUpdate: require('waterlock').models.user.beforeUpdate
};


text:
namespace clang {
  namespace diag {
    enum {
#define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\
             SFINAE,NOWERROR,SHOWINSYSHEADER,CATEGORY) ENUM,
#define DRIVERSTART
#include "clang/Basic/DiagnosticDriverKinds.inc"
#undef DIAG
      NUM_BUILTIN_DRIVER_DIAGNOSTICS
    };
  }  // end namespace diag
}  // end namespace clang

#endif


text:
<?php

namespace Symfony\Component\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;

/**
 * Checks if arguments of methods are properly configured.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 * @author Nicolas Grekas <p@tchwork.com>
 */
class CheckArgumentsValidityPass extends AbstractRecursivePass
{
    private $throwExceptions;

    public function __construct(bool $throwExceptions = true)
    {
        $this->throwExceptions = $throwExceptions;
    }

    /**
     * {@inheritdoc}
     */
    protected function processValue($value, bool $isRoot = false)
    {
        if (!$value instanceof Definition) {
            return parent::processValue($value, $isRoot);
        }

        $i = 0;
        foreach ($value->getArguments() as $k => $v) {
            if ($k !== $i++) {
                if (!\is_int($k)) {
                    $msg = sprintf('Invalid constructor argument for service "%s": integer expected but found string "%s". Check your service definition.', $this->currentId, $k);
                    $value->addError($msg);
                    if ($this->throwExceptions) {
                        throw new RuntimeException($msg);
                    }

                    break;
                }

                $msg = sprintf('Invalid constructor argument %d for service "%s": argument %d must be defined before. Check your service definition.', 1 + $k, $this->currentId, $i);
                $value->addError($msg);
                if ($this->throwExceptions) {
                    throw new RuntimeException($msg);
                }
            }
        }

        foreach ($value->getMethodCalls() as $methodCall) {
            $i = 0;
            foreach ($methodCall[1] as $k => $v) {
                if ($k !== $i++) {
                    if (!\is_int($k)) {
                        $msg = sprintf('Invalid argument for method call "%s" of service "%s": integer expected but found string "%s". Check your service definition.', $methodCall[0], $this->currentId, $k);
                        $value->addError($msg);
                        if ($this->throwExceptions) {
                            throw new RuntimeException($msg);
                        }

                        break;
                    }

                    $msg = sprintf('Invalid argument %d for method call "%s" of service "%s": argument %d must be defined before. Check your service definition.', 1 + $k, $methodCall[0], $this->currentId, $i);
                    $value->addError($msg);
                    if ($this->throwExceptions) {
                        throw new RuntimeException($msg);
                    }
                }
            }
        }
    }
}


text:
<?php

namespace ccxt;

class vaultoro extends Exchange {

    public function describe () {
        return array_replace_recursive (parent::describe (), array (
            'id' => 'vaultoro',
            'name' => 'Vaultoro',
            'countries' => 'CH',
            'rateLimit' => 1000,
            'version' => '1',
            'hasCORS' => true,
            'urls' => array (
                'logo' => 'https://user-images.githubusercontent.com/1294454/27766880-f205e870-5ee9-11e7-8fe2-0d5b15880752.jpg',
                'api' => 'https://api.vaultoro.com',
                'www' => 'https://www.vaultoro.com',
                'doc' => 'https://api.vaultoro.com',
            ),
            'api' => array (
                'public' => array (
                    'get' => array (
                        'bidandask',
                        'buyorders',
                        'latest',
                        'latesttrades',
                        'markets',
                        'orderbook',
                        'sellorders',
                        'transactions/day',
                        'transactions/hour',
                        'transactions/month',
                    ),
                ),
                'private' => array (
                    'get' => array (
                        'balance',
                        'mytrades',
                        'orders',
                    ),
                    'post' => array (
                        'buy/{symbol}/{type}',
                        'cancel/{id}',
                        'sell/{symbol}/{type}',
                        'withdraw',
                    ),
                ),
            ),
        ));
    }

    public function fetch_markets () {
        $result = array ();
        $markets = $this->publicGetMarkets ();
        $market = $markets['data'];
        $base = $market['BaseCurrency'];
        $quote = $market['MarketCurrency'];
        $symbol = $base . '/' . $quote;
        $baseId = $base;
        $quoteId = $quote;
        $id = $market['MarketName'];
        $result[] = array (
            'id' => $id,
            'symbol' => $symbol,
            'base' => $base,
            'quote' => $quote,
            'baseId' => $baseId,
            'quoteId' => $quoteId,
            'info' => $market,
        );
        return $result;
    }

    public function fetch_balance ($params = array ()) {
        $this->load_markets();
        $response = $this->privateGetBalance ();
        $balances = $response['data'];
        $result = array ( 'info' => $balances );
        for ($b = 0; $b < count ($balances); $b++) {
            $balance = $balances[$b];
            $currency = $balance['currency_code'];
            $uppercase = strtoupper ($currency);
            $free = $balance['cash'];
            $used = $balance['reserved'];
            $total = $this->sum ($free, $used);
            $account = array (
                'free' => $free,
                'used' => $used,
                'total' => $total,
            );
            $result[$uppercase] = $account;
        }
        return $this->parse_balance($result);
    }

    public function fetch_order_book ($symbol, $params = array ()) {
        $this->load_markets();
        $response = $this->publicGetOrderbook ($params);
        $orderbook = array (
            'bids' => $response['data'][0]['b'],
            'asks' => $response['data'][1]['s'],
        );
        $result = $this->parse_order_book($orderbook, null, 'bids', 'asks', 'Gold_Price', 'Gold_Amount');
        $result['bids'] = $this->sort_by($result['bids'], 0, true);
        return $result;
    }

    public function fetch_ticker ($symbol, $params = array ()) {
        $this->load_markets();
        $quote = $this->publicGetBidandask ($params);
        $bidsLength = is_array ($quote['bids']) ? count ($quote['bids']) : 0;
        $bid = $quote['bids'][$bidsLength - 1];
        $ask = $quote['asks'][0];
        $response = $this->publicGetMarkets ($params);
        $ticker = $response['data'];
        $timestamp = $this->milliseconds ();
        return array (
            'symbol' => $symbol,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601 ($timestamp),
            'high' => floatval ($ticker['24hHigh']),
            'low' => floatval ($ticker['24hLow']),
            'bid' => $bid[0],
            'ask' => $ask[0],
            'vwap' => null,
            'open' => null,
            'close' => null,
            'first' => null,
            'last' => floatval ($ticker['LastPrice']),
            'change' => null,
            'percentage' => null,
            'average' => null,
            'baseVolume' => null,
            'quoteVolume' => floatval ($ticker['24hVolume']),
            'info' => $ticker,
        );
    }

    public function parse_trade ($trade, $market) {
        $timestamp = $this->parse8601 ($trade['Time']);
        return array (
            'id' => null,
            'info' => $trade,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601 ($timestamp),
            'symbol' => $market['symbol'],
            'order' => null,
            'type' => null,
            'side' => null,
            'price' => $trade['Gold_Price'],
            'amount' => $trade['Gold_Amount'],
        );
    }

    public function fetch_trades ($symbol, $since = null, $limit = null, $params = array ()) {
        $this->load_markets();
        $market = $this->market ($symbol);
        $response = $this->publicGetTransactionsDay ($params);
        return $this->parse_trades($response, $market, $since, $limit);
    }

    public function create_order ($symbol, $type, $side, $amount, $price = null, $params = array ()) {
        $this->load_markets();
        $market = $this->market ($symbol);
        $method = 'privatePost' . $this->capitalize ($side) . 'SymbolType';
        $response = $this->$method (array_merge (array (
            'symbol' => strtolower ($market['quoteId']),
            'type' => $type,
            'gld' => $amount,
            'price' => $price || 1,
        ), $params));
        return array (
            'info' => $response,
            'id' => $response['data']['Order_ID'],
        );
    }

    public function cancel_order ($id, $symbol = null, $params = array ()) {
        $this->load_markets();
        return $this->privatePostCancelId (array_merge (array (
            'id' => $id,
        ), $params));
    }

    public function sign ($path, $api = 'public', $method = 'GET', $params = array (), $headers = null, $body = null) {
        $url = $this->urls['api'] . '/';
        if ($api == 'public') {
            $url .= $path;
        } else {
            $this->check_required_credentials();
            $nonce = $this->nonce ();
            $url .= $this->version . '/' . $this->implode_params($path, $params);
            $query = array_merge (array (
                'nonce' => $nonce,
                'apikey' => $this->apiKey,
            ), $this->omit ($params, $this->extract_params($path)));
            $url .= '?' . $this->urlencode ($query);
            $headers = array (
                'Content-Type' => 'application/json',
                'X-Signature' => $this->hmac ($this->encode ($url), $this->encode ($this->secret))
            );
        }
        return array ( 'url' => $url, 'method' => $method, 'body' => $body, 'headers' => $headers );
    }
}


text:
require "yaml"
#settings = YAML::load_file("config/db.yml")
# Sequel Configuration
#DB = Sequel.connect(settings[ENV['RACK_ENV']])


text:
define(function() {
	var UnewnavigationModel = Upfront.Models.ObjectModel.extend({
		/**
		 * A quasi-constructor, called after actual constructor *and* the built-in `initialize()` method.
		 * Used for setting up instance defaults, initialization and the like.
		 */
		init: function () {
			var properties = _.clone(Upfront.data.unewnavigation.defaults);
			properties.element_id = Upfront.Util.get_unique_id(properties.id_slug + "-object");
			this.init_properties(properties);

		}
	});

	return UnewnavigationModel;
});


text:
use std::collections::HashMap;

enum_string! {
    TargetPath {
        Translation = "translation",
        Rotation = "rotation",
        Scale = "scale",
    }
}

enum_string! {
    Interpolation {
        Linear = "LINEAR",
        Step = "STEP",
    }
}

impl Default for Interpolation {
    fn default() -> Interpolation {
        Interpolation::Linear
    }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Target {
    /// The ID of the node to target.
    pub id: String,

    /// The name of the node's TRS property to modify.
    pub path: TargetPath,

    // TODO: extension
    // TODO: extras
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Channel {
    /// The ID of a sampler in this animation used to compute the value for the
    /// target, e.g., a node's translation, rotation, or scale (TRS).
    pub sampler: String,

    /// The ID of the node and TRS property to target.
    pub target: Target,

    // TODO: extension
    // TODO: extras
}

#[derive(Debug, Default, Deserialize, Serialize)]
pub struct Sampler {
    /// The ID of a parameter in this animation to use as keyframe input.
    ///
    /// This parameter must have type FLOAT. The values represent time in
    /// seconds with `time[0] >= 0.0`, and monotonically increasing values,
    /// i.e., time[n + 1] >= time[n]
    pub input: String,

    /// Interpolation algorithm.
    ///
    /// When an animation targets a node's rotation, and the animation's
    /// interpolation is "LINEAR", spherical linear interpolation (slerp) should
    /// be used to interpolate quaternions.
    #[serde(default)]
    pub interpolation: Interpolation,

    /// The ID of a parameter in this animation to use as keyframe output.
    pub output: String,

    // TODO: extension
    // TODO: extras
}

#[derive(Debug, Default, Deserialize, Serialize)]
pub struct Animation {
    /// An array of channels, each of which targets an animation's sampler at a
    /// node's property.
    #[serde(default)]
    pub channels: Vec<Channel>,

    /// A dictionary object of strings whose values are IDs of accessors with
    /// keyframe data, e.g., time, translation, rotation, etc.
    #[serde(default)]
    pub parameters: HashMap<String, String>,

    /// A dictionary object of animation.sampler objects that combines input and
    /// output parameters with an interpolation algorithm to define a keyframe
    /// graph (but not its target).
    #[serde(default)]
    pub samplers: HashMap<String, Sampler>,

    /// The user-defined name of this object.
    ///
    /// This is not necessarily unique, e.g., an animation and a buffer could
    /// have the same name, or two animations could even have the same name.
    pub name: Option<String>,

    // TODO: extension
    // TODO: extras
}

#[cfg(test)]
mod test {
    extern crate serde_json;
    use super::*;

    #[test]
    fn it_deserializes_an_animation() {
        let data = r#"{
    "channels": [
        {
            "sampler": "a_sampler",
            "target": {
                "id": "node_id",
                "path": "rotation",
                "extensions": {
                    "extension_name": {
                        "extension specific": "value"
                    }
                },
                "extras": {
                    "Application specific": "The extra object can contain any properties."
                }
            },
            "extensions": {
                "extension_name": {
                    "extension specific": "value"
                }
            },
            "extras": {
                "Application specific": "The extra object can contain any properties."
            }
        }
    ],
    "name": "user-defined animation name",
    "parameters": {
        "TIME": "time_accessor",
        "rotation": "rotation_accessor"
    },
    "samplers": {
        "a_sampler": {
            "input": "TIME",
            "interpolation": "LINEAR",
            "output": "rotation",
            "extensions": {
                "extension_name": {
                    "extension specific": "value"
                }
            },
            "extras": {
                "Application specific": "The extra object can contain any properties."
            }
        }
    },
    "extensions": {
        "extension_name": {
            "extension specific": "value"
        }
    },
    "extras": {
        "Application specific": "The extra object can contain any properties."
    }
}"#;
        let animation: Animation = serde_json::from_str(data).unwrap();

        assert_eq!("user-defined animation name", animation.name.unwrap());
        assert_eq!(2, animation.parameters.len());
    }
}


text:
@interface TKDataFormMinimumLengthValidator : TKDataFormPropertyValidator

@property (nonatomic) NSInteger minimumLength;

- (id)initWithMinimumLength:(NSInteger)minimumLength;

@end


text:
<?php

/**
 * @Entity
 * @Table(name="users")
 */
class User {

    /**
     * @Id
     * @Column(type="integer")
     * @GeneratedValue
     */
    private $id;

    /** @Column(length=64, unique=true) */
    private $username;

    /** @Column(length=60) */
    private $password;

    /** @Column(length=128, unique=true) */
    private $email;

    /** @Column(length=64) */
    private $firstName;

    /** @Column(length=64) */
    private $lastName;

    /** @Column(type="datetime") */
    private $registeredOn;

    /** @Column(length=40) */
    private $activationKey;

    /** @Column(type="boolean") */
    private $activated;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set username
     *
     * @param string $username
     *
     * @return User
     */
    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    /**
     * Get username
     *
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * Set password
     *
     * @param string $password
     *
     * @return User
     */
    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Get password
     *
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * Set email
     *
     * @param string $email
     *
     * @return User
     */
    public function setEmail($email)
    {
        $this->email = $email;

        return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set firstName
     *
     * @param string $firstName
     *
     * @return User
     */
    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;

        return $this;
    }

    /**
     * Get firstName
     *
     * @return string
     */
    public function getFirstName()
    {
        return $this->firstName;
    }

    /**
     * Set lastName
     *
     * @param string $lastName
     *
     * @return User
     */
    public function setLastName($lastName)
    {
        $this->lastName = $lastName;

        return $this;
    }

    /**
     * Get lastName
     *
     * @return string
     */
    public function getLastName()
    {
        return $this->lastName;
    }

    /**
     * Set registeredOn
     *
     * @param \DateTime $registeredOn
     *
     * @return User
     */
    public function setRegisteredOn($registeredOn)
    {
        $this->registeredOn = $registeredOn;

        return $this;
    }

    /**
     * Get registeredOn
     *
     * @return \DateTime
     */
    public function getRegisteredOn()
    {
        return $this->registeredOn;
    }

    /**
     * Set activationKey
     *
     * @param string $activationKey
     *
     * @return User
     */
    public function setActivationKey($activationKey)
    {
        $this->activationKey = $activationKey;

        return $this;
    }

    /**
     * Get activationKey
     *
     * @return string
     */
    public function getActivationKey()
    {
        return $this->activationKey;
    }

    /**
     * Set activated
     *
     * @param boolean $activated
     *
     * @return User
     */
    public function setActivated($activated)
    {
        $this->activated = $activated;

        return $this;
    }

    /**
     * Get activated
     *
     * @return boolean
     */
    public function getActivated()
    {
        return $this->activated;
    }
}


text:
package org.apache.aries.jpa.container.context.transaction.impl;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.TransactionRequiredException;
import javax.transaction.TransactionSynchronizationRegistry;

import org.apache.aries.unittest.mocks.MethodCall;
import org.apache.aries.unittest.mocks.Skeleton;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

public class JTAPersistenceContextRegistryTest {

  private TranSyncRegistryMock reg;

  private EntityManagerFactory emf1;
  private Map<Object,Object> props1;
  private EntityManagerFactory emf2;
  private Map<Object,Object> props2;

  private JTAPersistenceContextRegistry contexts;
  private BundleContext ctx;
  private TransactionSynchronizationRegistry tsr;

  private ServiceReference ref;

  @Before
  public void setup()
  {
    reg = new TranSyncRegistryMock();
    tsr = Skeleton.newMock(reg, TransactionSynchronizationRegistry.class);
    ctx = Skeleton.newMock(BundleContext.class);

    props1 = new HashMap<Object, Object>();
    props1.put("prop1", "value1");

    props2 = new HashMap<Object, Object>();
    props2.put("prop2", "value2");

    emf1 = Skeleton.newMock(EntityManagerFactory.class);

    Skeleton.getSkeleton(emf1).setReturnValue(new MethodCall(EntityManagerFactory.class,
        "createEntityManager", props1), Skeleton.newMock(EntityManager.class));
    Skeleton.getSkeleton(emf1).setReturnValue(new MethodCall(EntityManagerFactory.class,
        "createEntityManager", props2), Skeleton.newMock(EntityManager.class));

    emf2 = Skeleton.newMock(EntityManagerFactory.class);

    Skeleton.getSkeleton(emf2).setReturnValue(new MethodCall(EntityManagerFactory.class,
        "createEntityManager", props1), Skeleton.newMock(EntityManager.class));
    Skeleton.getSkeleton(emf2).setReturnValue(new MethodCall(EntityManagerFactory.class,
        "createEntityManager", props2), Skeleton.newMock(EntityManager.class));

    contexts = new JTAPersistenceContextRegistry(ctx);
    ref = Skeleton.newMock(ServiceReference.class);
    Skeleton.getSkeleton(ctx).setReturnValue(new MethodCall(BundleContext.class,
        "getService", ref), tsr);
    contexts.addingService(ref);
  }

  @Test
  public void testIsTranActive()
  {
    reg.setTransactionKey(null);

    assertFalse(contexts.isTransactionActive());

    reg.setTransactionKey("");

    assertTrue(contexts.isTransactionActive());
  }

  @Test
  public void testMultiGetsOneTran()
  {
    AtomicLong useCount = new AtomicLong(0);
    DestroyCallback cbk = Skeleton.newMock(DestroyCallback.class);
    reg.setTransactionKey("");

    EntityManager em1a = contexts.getCurrentPersistenceContext(emf1, props1, useCount, cbk);
    EntityManager em1b = contexts.getCurrentPersistenceContext(emf1, props1, useCount, cbk);

    Skeleton.getSkeleton(emf1).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props1), 1);
    Skeleton.getSkeleton(emf1).assertNotCalled(new MethodCall(EntityManagerFactory.class, "createEntityManager"));
    Skeleton.getSkeleton(em1a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
    assertSame("We should get the same delegate!", em1a, em1b);
    assertEquals("Expected only one creation", 1, useCount.get());
    Skeleton.getSkeleton(cbk).assertSkeletonNotCalled();

    EntityManager em2a = contexts.getCurrentPersistenceContext(emf2, props1, useCount, cbk);
    EntityManager em2b = contexts.getCurrentPersistenceContext(emf2, props1, useCount, cbk);

    Skeleton.getSkeleton(emf2).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props1), 1);
    Skeleton.getSkeleton(emf2).assertNotCalled(new MethodCall(EntityManagerFactory.class, "createEntityManager"));
    Skeleton.getSkeleton(em2a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
    assertSame("We should get the same delegate!", em2a, em2b);
    assertEquals("Expected a second creation", 2, useCount.get());
    Skeleton.getSkeleton(cbk).assertSkeletonNotCalled();

    reg.afterCompletion("");

    Skeleton.getSkeleton(em1a).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"),1);
    Skeleton.getSkeleton(em2a).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"),1);
    assertEquals("Expected creations to be uncounted", 0, useCount.get());
    Skeleton.getSkeleton(cbk).assertCalledExactNumberOfTimes(new MethodCall(DestroyCallback.class,
        "callback"), 2);
  }

  @Test
  public void testMultiGetsMultiTrans()
  {
    AtomicLong useCount = new AtomicLong(0);
    DestroyCallback cbk = Skeleton.newMock(DestroyCallback.class);

    reg.setTransactionKey("a");
    EntityManager em1a = contexts.getCurrentPersistenceContext(emf1, props1, useCount, cbk);
    reg.setTransactionKey("b");
    EntityManager em1b = contexts.getCurrentPersistenceContext(emf1, props2, useCount, cbk);

    Skeleton.getSkeleton(emf1).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props1), 1);
    Skeleton.getSkeleton(emf1).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props2), 1);

    assertNotSame("We should not get the same delegate!", em1a, em1b);

    Skeleton.getSkeleton(em1a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
    Skeleton.getSkeleton(em1b).assertNotCalled(new MethodCall(EntityManager.class, "close"));

    assertEquals("Expected two creations", 2, useCount.get());
    Skeleton.getSkeleton(cbk).assertSkeletonNotCalled();

    reg.setTransactionKey("a");
    EntityManager em2a = contexts.getCurrentPersistenceContext(emf2, props1, useCount, cbk);
    reg.setTransactionKey("b");
    EntityManager em2b = contexts.getCurrentPersistenceContext(emf2, props2, useCount, cbk);

    Skeleton.getSkeleton(emf2).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props1), 1);
    Skeleton.getSkeleton(emf2).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props2), 1);

    assertNotSame("We should get the same delegate!", em2a, em2b);

    Skeleton.getSkeleton(em2a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
    Skeleton.getSkeleton(em2b).assertNotCalled(new MethodCall(EntityManager.class, "close"));

    assertEquals("Expected four creations", 4, useCount.get());
    Skeleton.getSkeleton(cbk).assertSkeletonNotCalled();

    reg.setTransactionKey("b");
    reg.afterCompletion("b");

    Skeleton.getSkeleton(em1a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
    Skeleton.getSkeleton(em1b).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);
    Skeleton.getSkeleton(em2a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
    Skeleton.getSkeleton(em2b).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);

    assertEquals("Expected two uncreations", 2, useCount.get());
    Skeleton.getSkeleton(cbk).assertCalledExactNumberOfTimes(new MethodCall(DestroyCallback.class,
    "callback"), 2);

    reg.setTransactionKey("a");
    reg.afterCompletion("a");

    Skeleton.getSkeleton(em1a).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);
    Skeleton.getSkeleton(em1b).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);
    Skeleton.getSkeleton(em2a).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);
    Skeleton.getSkeleton(em2b).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);
    assertEquals("Expected no remaining instances", 0, useCount.get());
    Skeleton.getSkeleton(cbk).assertCalledExactNumberOfTimes(new MethodCall(DestroyCallback.class,
    "callback"), 4);
  }

  @Test
  public void testNoTranSyncRegistry() {
    JTAPersistenceContextRegistry registry = new JTAPersistenceContextRegistry(ctx);

    reg.setTransactionKey(null);

    assertFalse(registry.jtaIntegrationAvailable());
    assertFalse(registry.isTransactionActive());

    Skeleton.getSkeleton(tsr).assertSkeletonNotCalled();

    reg.setTransactionKey("");

    assertFalse(registry.jtaIntegrationAvailable());
    assertFalse(registry.isTransactionActive());

    reg.setTransactionKey(null);
    contexts.removedService(ref, ref);

    assertFalse(contexts.jtaIntegrationAvailable());
    assertFalse(contexts.isTransactionActive());

    Skeleton.getSkeleton(tsr).assertSkeletonNotCalled();

    reg.setTransactionKey("");

    assertFalse(contexts.jtaIntegrationAvailable());
    assertFalse(contexts.isTransactionActive());

    Skeleton.getSkeleton(tsr).assertSkeletonNotCalled();
  }

  @Test(expected=TransactionRequiredException.class)
  public void testGetNoTran() {
    reg.setTransactionKey(null);
    contexts.getCurrentPersistenceContext(emf1, props1, new AtomicLong(), Skeleton.newMock(DestroyCallback.class));
  }

  @Test(expected=TransactionRequiredException.class)
  public void testGetNoTranSyncRegistry() {
    reg.setTransactionKey("");
    contexts.removedService(ref, ref);
    contexts.getCurrentPersistenceContext(emf1, props1, new AtomicLong(), Skeleton.newMock(DestroyCallback.class));
  }

  @Test(expected=TransactionRequiredException.class)
  public void testGetExistingNoTran() {
    reg.setTransactionKey(null);
    contexts.getExistingPersistenceContext(emf1);
  }

  @Test(expected=TransactionRequiredException.class)
  public void testGetExistingNoTranSyncRegistry() {
    reg.setTransactionKey("");
    contexts.removedService(ref, ref);
    contexts.getExistingPersistenceContext(emf1);
  }

  @Test
  public void testGetExisting()
  {
    reg.setTransactionKey("");

    assertNull(contexts.getExistingPersistenceContext(emf1));
    assertNull(contexts.getExistingPersistenceContext(emf2));

    AtomicLong useCount = new AtomicLong(0);
    DestroyCallback cbk = Skeleton.newMock(DestroyCallback.class);
    reg.setTransactionKey("");

    EntityManager em1a = contexts.getCurrentPersistenceContext(emf1, props1, useCount, cbk);
    EntityManager em1b = contexts.getExistingPersistenceContext(emf1);

    Skeleton.getSkeleton(emf1).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props1), 1);
    Skeleton.getSkeleton(emf1).assertNotCalled(new MethodCall(EntityManagerFactory.class, "createEntityManager"));
    Skeleton.getSkeleton(em1a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
    assertSame("We should get the same delegate!", em1a, em1b);
    assertEquals("Expected only one creation", 1, useCount.get());
    Skeleton.getSkeleton(cbk).assertSkeletonNotCalled();

    EntityManager em2a = contexts.getCurrentPersistenceContext(emf2, props1, useCount, cbk);
    EntityManager em2b = contexts.getExistingPersistenceContext(emf2);

    Skeleton.getSkeleton(emf2).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props1), 1);
    Skeleton.getSkeleton(emf2).assertNotCalled(new MethodCall(EntityManagerFactory.class, "createEntityManager"));
    Skeleton.getSkeleton(em2a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
    assertSame("We should get the same delegate!", em2a, em2b);
    assertEquals("Expected a second creation", 2, useCount.get());
    Skeleton.getSkeleton(cbk).assertSkeletonNotCalled();

    reg.afterCompletion("");

    Skeleton.getSkeleton(em1a).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"),1);
    Skeleton.getSkeleton(em2a).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"),1);
    assertEquals("Expected creations to be uncounted", 0, useCount.get());
    Skeleton.getSkeleton(cbk).assertCalledExactNumberOfTimes(new MethodCall(DestroyCallback.class,
        "callback"), 2);
  }

  @Test
  public void testManageExisting()
  {
    reg.setTransactionKey("");

    assertNull(contexts.getExistingPersistenceContext(emf1));
    assertNull(contexts.getExistingPersistenceContext(emf2));

    EntityManager em1a = emf1.createEntityManager(props1);
    contexts.manageExistingPersistenceContext(emf1, em1a);

    Skeleton.getSkeleton(em1a).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "joinTransaction"), 1);

    EntityManager em1b = contexts.getExistingPersistenceContext(emf1);

    Skeleton.getSkeleton(emf1).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props1), 1);
    Skeleton.getSkeleton(emf1).assertNotCalled(new MethodCall(EntityManagerFactory.class, "createEntityManager"));
    Skeleton.getSkeleton(em1a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
    assertSame("We should get the same delegate!", em1a, em1b);

    EntityManager em2a = emf2.createEntityManager(props1);
    contexts.manageExistingPersistenceContext(emf2, em2a);

    Skeleton.getSkeleton(em2a).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "joinTransaction"), 1);

    EntityManager em2b = contexts.getExistingPersistenceContext(emf2);

    Skeleton.getSkeleton(emf2).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props1), 1);
    Skeleton.getSkeleton(emf2).assertNotCalled(new MethodCall(EntityManagerFactory.class, "createEntityManager"));
    Skeleton.getSkeleton(em2a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
    assertSame("We should get the same delegate!", em2a, em2b);

    reg.afterCompletion("");

    Skeleton.getSkeleton(em1a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
    Skeleton.getSkeleton(em2a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
  }

}


text:
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template

from tastypie.api import Api
from .api import UserResource, ActionResource

v1_api = Api(api_name='v1')
v1_api.register(UserResource())
v1_api.register(ActionResource())

urlpatterns = patterns('',
    url(r'^email$', 'gratitude.gratitude.views.email', name="email"),
    (r'^api/', include(v1_api.urls)),
)


text:
Socialprofiles

    <jh-alert></jh-alert>

                <button class="btn btn-primary" ui-sref="socialprofile.new">
                     Create a new Socialprofile
                </button>

                <form name="deleteForm" ng-submit="confirmDelete(socialprofile.id)">

                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true"
                                ng-click="clear()">×</button>

Confirm delete operation

Are you sure you want to delete this Socialprofile?

                        <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="clear()">
                             Cancel
                        </button>
                        <button type="submit" ng-disabled="deleteForm.$invalid" class="btn btn-danger">
                             Delete
                        </button>

                </form>

                    ID
                    Twitter
                    Facebook
                    Email
                    Instagram
                    Pinterest
                    Googleplus

                    {{socialprofile.id}}
                    {{socialprofile.twitter}}
                    {{socialprofile.facebook}}
                    {{socialprofile.email}}
                    {{socialprofile.instagram}}
                    {{socialprofile.pinterest}}
                    {{socialprofile.googleplus}}

                        <button type="submit"
                                ui-sref="socialprofile.detail({id:socialprofile.id})"
                                class="btn btn-info btn-sm">
                              View
                        </button>
                        <button type="submit"
                                ui-sref="socialprofile.edit({id:socialprofile.id})"
                                class="btn btn-primary btn-sm">
                              Edit
                        </button>
                        <button type="submit"
                                ng-click="delete(socialprofile.id)"
                                class="btn btn-danger btn-sm">
                              Delete
                        </button>

<<

<

>

>>


text:
using System;
using System.Reflection;

public static class GObjectIntPtrCtorVerifier
{
    public static void Main (string [] args)
    {
        foreach (var path in args) {
            Verify (path);
        }
    }

    private static void Verify (string path)
    {
        foreach (var type in Assembly.LoadFrom (path).GetTypes ()) {
            if (!type.IsSubclassOf (typeof (GLib.Object))) {
                continue;
            }

            bool safe = false;

            foreach (var ctor in type.GetConstructors (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) {
                var args = ctor.GetParameters ();
                if ((safe = (ctor.Attributes & (MethodAttributes.Public |
                    MethodAttributes.Family)) != 0 &&
                    args != null &&
                    args.Length == 1 &&
                    args[0].ParameterType == typeof (IntPtr))) {
                    break;
                }
            }

            if (!safe) {
                Console.WriteLine (type);
            }
        }
    }
}


text:
package name.guke.commons.excel;

/**
 * Created by Guke on 2016/11/3.
 */
public class ExcelLog {
    private Integer rowNum;
    private Object object;
    private String log;

    /**
     * @return the rowNum
     */
    public Integer getRowNum() {
        return rowNum;
    }

    /**
     * @param rowNum
     *            the rowNum to set
     */
    public void setRowNum(Integer rowNum) {
        this.rowNum = rowNum;
    }

    /**
     * @return the object
     */
    public Object getObject() {
        return object;
    }

    /**
     * @param object
     *            the object to set
     */
    public void setObject(Object object) {
        this.object = object;
    }

    /**
     * @return the log
     */
    public String getLog() {
        return log;
    }

    /**
     * @param object
     * @param log
     */
    public ExcelLog(Object object, String log) {
        super();
        this.object = object;
        this.log = log;
    }

    /**
     * @param rowNum
     * @param object
     * @param log
     */
    public ExcelLog(Object object, String log, Integer rowNum) {
        super();
        this.rowNum = rowNum;
        this.object = object;
        this.log = log;
    }

    /**
     * @param log
     *            the log to set
     */
    public void setLog(String log) {
        this.log = log;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/LandscapeVideoCapture/LandscapeVideoCapture.iml" filepath="$PROJECT_DIR$/LandscapeVideoCapture/LandscapeVideoCapture.iml" />
      <module fileurl="file://$PROJECT_DIR$/LandscapeVideoCapture-sample/LandscapeVideoCapture-sample.iml" filepath="$PROJECT_DIR$/LandscapeVideoCapture-sample/LandscapeVideoCapture-sample.iml" />
      <module fileurl="file://$PROJECT_DIR$/LandscapeVideoCaptureTest/LandscapeVideoCaptureTest.iml" filepath="$PROJECT_DIR$/LandscapeVideoCaptureTest/LandscapeVideoCaptureTest.iml" />
      <module fileurl="file://$PROJECT_DIR$/landscape_video_camera.iml" filepath="$PROJECT_DIR$/landscape_video_camera.iml" />
    </modules>
  </component>
</project>


text:
import { runView } from '../run';

import * as cases from './cases';

runView('simple', cases);