text:
<?php

/**
 * @namespace
 */
namespace Zend\Search\Lucene\Analysis\TokenFilter;

use Zend\Search\Lucene\Analysis\TokenFilter,
    Zend\Search\Lucene\Analysis\Token,
    Zend\Search\Lucene,
    Zend\Search\Lucene\Exception\ExtensionNotLoadedExtension;

/**
 * Lower case Token filter.
 *
 * @uses       \Zend\Search\Lucene\Analysis\Token
 * @uses       \Zend\Search\Lucene\Analysis\TokenFilter
 * @uses       \Zend\Search\Lucene\Exception\ExtensionNotLoadedException
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class LowerCaseUtf8 implements TokenFilter
{
    /**
     * Object constructor
     * @throws \Zend\Search\Lucene\Exception\ExtensionNotLoadedException
     */
    public function __construct()
    {
        if (!function_exists('mb_strtolower')) {
            // mbstring extension is disabled
            throw new ExtensionNotLoadedException('Utf8 compatible lower case filter needs mbstring extension to be enabled.');
        }
    }

    /**
     * Normalize Token or remove it (if null is returned)
     *
     * @param \Zend\Search\Lucene\Analysis\Token $srcToken
     * @return \Zend\Search\Lucene\Analysis\Token
     */
    public function normalize(Token $srcToken)
    {
        $newToken = new Token(mb_strtolower($srcToken->getTermText(), 'UTF-8'),
                                       $srcToken->getStartOffset(),
                                       $srcToken->getEndOffset());

        $newToken->setPositionIncrement($srcToken->getPositionIncrement());

        return $newToken;
    }
}


text:
package ring

import (
	fmt "fmt"
	"sync"
	"time"

	"github.com/go-kit/kit/log/level"
	consul "github.com/hashicorp/consul/api"
	"github.com/weaveworks/cortex/pkg/util"
)

type mockKV struct {
	mtx     sync.Mutex
	cond    *sync.Cond
	kvps    map[string]*consul.KVPair
	current uint64 // the current 'index in the log'
}

// NewInMemoryKVClient makes a new mock consul client.
func NewInMemoryKVClient() KVClient {
	m := mockKV{
		kvps: map[string]*consul.KVPair{},
	}
	m.cond = sync.NewCond(&m.mtx)
	go m.loop()
	return &consulClient{
		kv:               &m,
		codec:            ProtoCodec{Factory: ProtoDescFactory},
		longPollDuration: time.Minute,
	}
}

func copyKVPair(in *consul.KVPair) *consul.KVPair {
	out := *in
	out.Value = make([]byte, len(in.Value))
	copy(out.Value, in.Value)
	return &out
}

// periodic loop to wake people up, so they can honour timeouts
func (m *mockKV) loop() {
	for range time.Tick(1 * time.Second) {
		m.mtx.Lock()
		m.cond.Broadcast()
		m.mtx.Unlock()
	}
}

func (m *mockKV) Put(p *consul.KVPair, q *consul.WriteOptions) (*consul.WriteMeta, error) {
	m.mtx.Lock()
	defer m.mtx.Unlock()

	m.current++
	existing, ok := m.kvps[p.Key]
	if ok {
		existing.Value = p.Value
		existing.ModifyIndex = m.current
	} else {
		m.kvps[p.Key] = &consul.KVPair{
			Key:         p.Key,
			Value:       p.Value,
			CreateIndex: m.current,
			ModifyIndex: m.current,
		}
	}

	m.cond.Broadcast()
	return nil, nil
}

func (m *mockKV) CAS(p *consul.KVPair, q *consul.WriteOptions) (bool, *consul.WriteMeta, error) {
	level.Debug(util.Logger).Log("msg", "CAS", "key", p.Key, "modify_index", p.ModifyIndex, "value", fmt.Sprintf("%.40q", p.Value))

	m.mtx.Lock()
	defer m.mtx.Unlock()
	existing, ok := m.kvps[p.Key]
	if ok && existing.ModifyIndex != p.ModifyIndex {
		return false, nil, nil
	}

	m.current++
	if ok {
		existing.Value = p.Value
		existing.ModifyIndex = m.current
	} else {
		m.kvps[p.Key] = &consul.KVPair{
			Key:         p.Key,
			Value:       p.Value,
			CreateIndex: m.current,
			ModifyIndex: m.current,
		}
	}

	m.cond.Broadcast()
	return true, nil, nil
}

func (m *mockKV) Get(key string, q *consul.QueryOptions) (*consul.KVPair, *consul.QueryMeta, error) {
	level.Debug(util.Logger).Log("msg", "Get", "key", key, "wait_index", q.WaitIndex)

	m.mtx.Lock()
	defer m.mtx.Unlock()

	value, ok := m.kvps[key]
	if !ok {
		level.Debug(util.Logger).Log("msg", "Get - not found", "key", key)
		return nil, &consul.QueryMeta{LastIndex: m.current}, nil
	}

	if q.WaitTime > 0 {
		deadline := time.Now().Add(q.WaitTime)
		for q.WaitIndex >= value.ModifyIndex && time.Now().Before(deadline) {
			m.cond.Wait()
		}
		if time.Now().After(deadline) {
			level.Debug(util.Logger).Log("msg", "Get - deadline exceeded", "key", key)
			return nil, &consul.QueryMeta{LastIndex: q.WaitIndex}, nil
		}
	}

	level.Debug(util.Logger).Log("msg", "Get", "key", key, "modify_index", value.ModifyIndex, "value", fmt.Sprintf("%.40q", value.Value))
	return copyKVPair(value), &consul.QueryMeta{LastIndex: value.ModifyIndex}, nil
}

func (m *mockKV) List(prefix string, q *consul.QueryOptions) (consul.KVPairs, *consul.QueryMeta, error) {
	m.mtx.Lock()
	defer m.mtx.Unlock()

	deadline := time.Now().Add(q.WaitTime)
	for q.WaitIndex >= m.current && time.Now().Before(deadline) {
		m.cond.Wait()
	}
	if time.Now().After(deadline) {
		return nil, &consul.QueryMeta{LastIndex: q.WaitIndex}, nil
	}

	result := consul.KVPairs{}
	for _, kvp := range m.kvps {
		if kvp.ModifyIndex >= q.WaitIndex {
			result = append(result, copyKVPair(kvp))
		}
	}
	return result, &consul.QueryMeta{LastIndex: m.current}, nil
}

redpajama_set_name: RedPajamaGithub


text:
/**
 */
package gluemodel.COSEM.COSEMObjects.impl;

import gluemodel.COSEM.COSEMObjects.COSEMObjectsPackage;
import gluemodel.COSEM.COSEMObjects.PRIME_NB_OFDM_PLC_MAC_counters_object;

import gluemodel.COSEM.InterfaceClasses.impl.PRIME_NB_OFDM_PLC_MAC_countersImpl;

import org.eclipse.emf.ecore.EClass;

/**
 *
 * An implementation of the model object 'PRIME NB OFDM PLC MAC counters object'.
 *
 *
 * @generated
 */
public class PRIME_NB_OFDM_PLC_MAC_counters_objectImpl extends PRIME_NB_OFDM_PLC_MAC_countersImpl implements PRIME_NB_OFDM_PLC_MAC_counters_object {
	/**
	 *
	 *
	 * @generated
	 */
	protected PRIME_NB_OFDM_PLC_MAC_counters_objectImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return COSEMObjectsPackage.eINSTANCE.getPRIME_NB_OFDM_PLC_MAC_counters_object();
	}

} //PRIME_NB_OFDM_PLC_MAC_counters_objectImpl


text:
import socket
import time
import visuals

class Client():

	def __init__(self, server):
		self.server = server
		self.connection = None

		self.data = None
		self.gamecontroller = None
		self.current_state = None

		self.lights = visuals.Lights()

	def signal_handler(self, signal, frame):
		self.lights.set_lights_off()
		sys.exit(0)

	def connect(self):
		try:
			self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			self.connection.connect(self.server)
			return 1
		except Exception as e:
			print("[!] Error connecting to server: " + str(e))
			raise e

	def set_game_controller(self, controller):
		self.gamecontroller = controller
		self.gamecontroller.init_curses()

	def send(self, message):
		try:
			self.connection.sendall(message)
		except Exception as e:
			print("[!] Error sending to server: " + str(e))

	def recv(self):
		try:
			self.data = self.connection.recv(2048)
		except Exception as e:
			print("[!] Error receiving data from server: " + str(e))

	def get_state(self):
		return self.current_state

	def process(self):
		#Process and send new board layout to LEDs
		self.color_str = self.data[:12]
		self.gamecontroller.set_colors(self.color_str)
		self.data = self.data[12:]

		self.current_state = [int(x) for x in self.data]
		self.gamecontroller.set_game_matrix(self.current_state)
		self.gamecontroller.n_win.clear()

		self.gamecontroller.draw_grid(None, self.gamecontroller.get_partial_grid())
		self.gamecontroller.n_win.refresh()
		self.update_lights()

	def update_lights(self):
		# read /tmp/fallback.pid. if it has a p_id, check if p active
		# if p not active replace with own, if active, keep trying
		#self.lights.change_color(self.gamecontroller.get_color())
		self.lights.update(self.gamecontroller.get_partial_grid())
		return 0

	def close(self):
		self.connection.close()
		return 0

def main():

	client = Client(('0.0.0.0', 8000))

	while(True):
		# Connect to server, send request for updated board,
		# receive updated board, process and send data to LEDs,
		# close connection. Repeat @ 10Hz.
		client.connect()
		client.send("heartbeat")
		client.recv()
		data = client.getdata()
		if(data):
			print(data)
		client.close()
		time.sleep(0.1)

if __name__ == '__main__':
	main()


text:
import Vue from 'vue';
import Vuex from 'vuex';
import auth from './modules/auth';
import nv from './modules/nv';

Vue.use(Vuex);

export const SET_THEME = 'SET_THEME';
export const SET_QUERY = 'SET_QUERY';
export const SET_RESULT_INDEX = 'SET_RESULT_INDEX';
export const SET_RENAMING_ID = 'SET_RENAMING_ID';
export const SET_EDITING_ID = 'SET_EDITING_ID';

export const SET_ACTIVE_NOTE = 'SET_ACTIVE_NOTE';
export const SET_ACTIVE_KEY = 'SET_ACTIVE_KEY';
export const SET_NOTES = 'SET_NOTES';

const store = new Vuex.Store({
  modules: {
    auth,
    nv,
  },
  state: {
    query: '',
    resultIndex: -1,
    renamingId: null,
    editingId: null,
  },
  actions: {
    RESET_ACTIVE_NOTE: ({ commit }) => {
      commit(SET_RESULT_INDEX, -1);
      commit(SET_ACTIVE_NOTE, null);
      commit(SET_ACTIVE_KEY, null);
    },
    RESET_APP: ({ commit }) => {
      commit(SET_THEME, 'light');
      commit(SET_QUERY, '');
      commit(SET_RESULT_INDEX, -1);
      commit(SET_NOTES, []);
      commit(SET_ACTIVE_NOTE, null);
      commit(SET_ACTIVE_KEY, null);
    },
  },
  mutations: {
    [SET_QUERY](state, query) {
      state.query = query;
    },
    [SET_RESULT_INDEX](state, resultIndex) {
      state.resultIndex = resultIndex;
    },
    [SET_RENAMING_ID](state, renamingId) {
      state.renamingId = renamingId;
    },
    [SET_EDITING_ID](state, editingId) {
      state.editingId = editingId;
    },
  },
  getters: {
    query: state => state.query,
    resultIndex: state => state.resultIndex,
    renamingId: state => state.renamingId,
    editingId: state => state.editingId,
  },
});

export default store;


text:
<?php

namespace app\controllers;

use app\models\Question;
use app\models\QuestionAnswer;
use app\models\QuestionFavorite;
use app\models\QuestionAnswerForm;
use app\models\QuestionForm;
use app\models\QuestionSearch;
use Yii;
use yii\base\Action;
use yii\filters\AccessControl;
use yii\filters\AccessRule;
use yii\filters\VerbFilter;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;

/**
 * Class QaController
  */
class QaController extends Controller
{
    /**
     * @inheritdoc
     */
    const PAGE_SIZE = 15;

    /**
     * @inheritdoc
     */
    public $layout = "common";

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['index', 'favorite'],
                'rules' => [
                    [
                        'actions' => ['index'],
                        'allow' => true,
                        'matchCallback' => function (AccessRule $rule, Action $action) {
                            $isIndividual = Yii::$app->request->get('individual');
                            return !$isIndividual || ($isIndividual && !Yii::$app->user->isGuest);
                        }
                    ],
                    [
                        'actions' => [
                            'favorite',
                            'create',
                            'update-question',
                            'delete-question',
                            'update-answer',
                            'delete-answer'
                        ],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete-question' => ['post'],
                    'delete-answer' => ['post'],
                    'favorite' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actionIndex()
    {
        $searchModel = new QuestionSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->getPagination()->setPageSize(self::PAGE_SIZE);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Question model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException
     */
    public function actionView($id)
    {
        /** @var $question \app\models\Question */
        $question = Question::find()
            ->with(['user', 'questionTags', 'questionFavorites'
            ])
            ->andWhere([
                'question.id' => $id,
                'question.status' => Question::STATUS_PUBLISHED
            ])
            ->one();

        if ($question === null) {
            throw new NotFoundHttpException();
        }

        $answerForm = new QuestionAnswerForm([
            'question_id' => $question->id
        ]);

        if ($answerForm->load(Yii::$app->request->post())) {
            /** @var $answer \app\models\QuestionAnswer */
            if ($answer = $answerForm->save()) {
                $question->updateCounters(['answer_count' => 1]);
                Yii::$app->session->setFlash('success', Yii::t('app', 'Your answer published'));
                return $this->refresh();
            }
        }

        $answers = QuestionAnswer::find()
            ->with(['user'])
            ->andWhere([
                'question_id' => $id,
                'status' => QuestionAnswer::STATUS_PUBLISHED
            ])
            ->all();

        $question->updateCounters(['view_count' => 1]);

        return $this->render('view', [
            'question' => $question,
            'answers' => $answers,
            'answerForm' => $answerForm
        ]);
    }

    /**
     * @param integer $id
     * @return string|\yii\web\Response
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionUpdateAnswer($id)
    {
        $answer = $this->findModelAnswer($id);

        if (Yii::$app->user->getId() !== $answer->user_id) {
            throw new ForbiddenHttpException();
        }

        $answerForm = new QuestionAnswerForm([
            'answer' => $answer
        ]);

        if ($answerForm->load(Yii::$app->request->post())) {
            /** @var $answer \app\models\QuestionAnswer */
            if ($answer = $answerForm->save()) {
                Yii::$app->session->setFlash('success', Yii::t('app', 'Your answer was updated'));
                return $this->redirect(['view', 'id' => $answer->question_id]);
            }
        }

        return $this->render('update-answer', [
            'answerForm' => $answerForm
        ]);
    }

    /**
     * Creates a new Question model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $questionModel = new Question();

        $questionForm = new QuestionForm($questionModel);

        if ($questionForm->load(Yii::$app->request->post())) {
            /** @var $question \app\models\Question */
            if ($question = $questionForm->save()) {
                return $this->redirect(['view', 'id' => $question->id]);
            }
        }

        return $this->render('create', [
            'questionForm' => $questionForm
        ]);
    }

    /**
     * Updates an existing Question model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     * @throws \Exception
     */
    public function actionUpdateQuestion($id)
    {
        $question = $this->findModel($id);

        if (Yii::$app->user->getId() !== $question->user_id) {
            throw new ForbiddenHttpException();
        }

        $questionForm = new QuestionForm($question);

        if ($questionForm->load(Yii::$app->request->post()) && $questionForm->save()) {
            return $this->redirect(['view', 'id' => $questionForm->question->id]);
        } else {
            return $this->render(
                'update',
                [
                    'questionForm' => $questionForm,
                ]
            );
        }
    }

    /**
     * The question will be added as a favorite question to the current user.
     * @return int
     * @throws BadRequestHttpException
     */
    public function actionFavorite()
    {
        $id = Yii::$app->request->post('questionId');
        $questionFavoriteModel = new QuestionFavorite([
            'user_id' => Yii::$app->user->id,
            'question_id' => $id,
        ]);

        $result = $questionFavoriteModel->impact();
        if ($result === false) {
            throw new BadRequestHttpException();
        }

        return $result;
    }

    /**
     * Change of status of the issue to delete
     * @param $id
     * @return \yii\web\Response
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionDeleteQuestion($id)
    {
        $question = $this->findModel($id);
        if (Yii::$app->user->getId() !== $question->user_id) {
            throw new ForbiddenHttpException();
        }

        $question->status = $question::STATUS_DELETED;

        $question->save();

        return $this->redirect(['index']);
    }

    /**
     * Change of status of the answer to delete
     * @param $id
     * @return \yii\web\Response
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionDeleteAnswer($id)
    {
        $answer = $this->findModelAnswer($id);
        if (Yii::$app->user->getId() !== $answer->user_id) {
            throw new ForbiddenHttpException();
        }

        $answer->status = $answer::STATUS_DELETED;

        if ($answer->save()) {
            $answer->question->updateCounters(['answer_count' => -1]);
        }

        return $this->redirect(['view', 'id' => $answer->question_id]);
    }

    /**
     * Finds the QuestionAnswer model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return QuestionAnswer the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelAnswer($id)
    {
        if (($model = QuestionAnswer::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * Finds the Question model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Question the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Question::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
namespace DeepEqual.Test.Features
{
	using DeepEqual.Test.Helper;
	using DeepEqual.Test.VB;
	using Xunit;

	public class ComparingObjectsPropertiesWithArguments
	{
		[Fact]
		public void ShouldBeAbleToHandleComparingObjectsWithPropertiesWithArguments()
		{
			var x = new HasPropertiesWithArguments();
			var y = new HasPropertiesWithArguments();

			DeepAssert.AreEqual(x, y);
		}
	}
}


text:
@implementation DeepLinkData

- (instancetype)init:(DeeplinkUrlType)urlType success:(BOOL)success {
  self = [super init];
  if (self) {
    _urlType = urlType;
    _success = success;
  }
  return self;
}

@end


text:
from .exceptions import AzureTestError

def patch_time_sleep_api(unit_test):
    def _time_sleep_skip(*_):
        return

    mock_in_unit_test(unit_test, 'time.sleep', _time_sleep_skip)

def patch_long_run_operation_delay(unit_test):
    def _shortcut_long_run_operation(*args, **kwargs):  # pylint: disable=unused-argument
        return

    mock_in_unit_test(unit_test,
                      'msrestazure.azure_operation.AzureOperationPoller._delay',
                      _shortcut_long_run_operation)

def mock_in_unit_test(unit_test, target, replacement):
    try:
        import unittest.mock as mock
    except ImportError:
        import mock
    import unittest

    if not isinstance(unit_test, unittest.TestCase):
        raise AzureTestError('Patches can be only called from a unit test')

    mp = mock.patch(target, replacement)
    mp.__enter__()
    unit_test.addCleanup(mp.__exit__, None, None, None)


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

	<parent>
		<groupId>com.composum.nodes</groupId>
		<artifactId>composum-nodes</artifactId>
		<version>3.3.2-SNAPSHOT</version>
		<relativePath>../../../</relativePath>
	</parent>

	<groupId>com.composum.nodes.test</groupId>
	<artifactId>maven-package-test</artifactId>
	<packaging>pom</packaging>

	<name>VLT Package Manager Test</name>

	<repositories>
		<repository>
			<id>adobe-public-releases</id>
			<name>Adobe Basel Public Repository</name>
			<url>https://repo.adobe.com/nexus/content/groups/public</url>
			<releases>
				<enabled>true</enabled>
				<updatePolicy>never</updatePolicy>
			</releases>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
	<pluginRepositories>
		<pluginRepository>
			<id>adobe-public-releases</id>
			<name>Adobe Basel Public Repository</name>
			<url>https://repo.adobe.com/nexus/content/groups/public</url>
			<releases>
				<enabled>true</enabled>
				<updatePolicy>never</updatePolicy>
			</releases>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</pluginRepository>
	</pluginRepositories>

	<modules>
		<module>bundle</module>
		<module>package</module>
	</modules>

	<build>
		<pluginManagement>
			<plugins>

				<plugin>
					<groupId>com.day.jcr.vault</groupId>
					<artifactId>content-package-maven-plugin</artifactId>
					<version>0.0.24</version>
					<extensions>true</extensions>
					<configuration>
						<failOnError>true</failOnError>
						<targetURL>http://${sling.host}:${sling.port}${sling.context}/bin/cpm/package.service.html</targetURL>
						<userId>admin</userId>
						<password>admin</password>
						<useProxy>false</useProxy>
						<failOnMissingEmbed>true</failOnMissingEmbed>
					</configuration>
				</plugin>

			</plugins>
		</pluginManagement>
	</build>

</project>


text:
import {schema, doc, p, a} from "prosemirror-test-builder"
import ist from "ist"
import {Decoration, DecorationSet} from "prosemirror-view"
import {TextSelection} from "prosemirror-state"
import {tempEditor} from "./view"

describe("EditorView.endOfTextblock", () => {
  it("works at the left side of a textblock", () => {
    let view = tempEditor({doc: doc(p("a"), p("bcd"))})
    ist(view.endOfTextblock("left"))
    ist(view.endOfTextblock("backward"))
    ist(!view.endOfTextblock("right"))
    ist(!view.endOfTextblock("forward"))
  })

  it("works at the right side of a textblock", () => {
    let view = tempEditor({doc: doc(p("abc"), p("d"))})
    ist(!view.endOfTextblock("left"))
    ist(!view.endOfTextblock("backward"))
    ist(view.endOfTextblock("right"))
    ist(view.endOfTextblock("forward"))
  })

  it("works in the middle of a textblock", () => {
    let view = tempEditor({doc: doc(p("ab"))})
    ist(!view.endOfTextblock("left"))
    ist(!view.endOfTextblock("backward"))
    ist(!view.endOfTextblock("right"))
    ist(!view.endOfTextblock("forward"))
  })

  it("works at the start of the document", () => {
    let view = tempEditor({doc: doc(p("bcd"))})
    ist(view.endOfTextblock("left"))
    ist(view.endOfTextblock("backward"))
    ist(!view.endOfTextblock("right"))
    ist(!view.endOfTextblock("forward"))
  })

  it("works at the end of the document", () => {
    let view = tempEditor({doc: doc(p("abc"))})
    ist(!view.endOfTextblock("left"))
    ist(!view.endOfTextblock("backward"))
    ist(view.endOfTextblock("right"))
    ist(view.endOfTextblock("forward"))
  })

  it("works for vertical motion in a one-line block", () => {
    let view = tempEditor({doc: doc(p("abc"))})
    ist(view.endOfTextblock("up"))
    ist(view.endOfTextblock("down"))
  })

  it("works for vertical motion at the end of a wrapped block", () => {
    let view = tempEditor({doc: doc(p(new Array(100).join("foo ") + "foo"))})
    ist(!view.endOfTextblock("up"))
    ist(view.endOfTextblock("down"))
  })

  it("works for vertical motion at the start of a wrapped block", () => {
    let view = tempEditor({doc: doc(p("foo " + new Array(100).join("foo ")))})
    ist(view.endOfTextblock("up"))
    ist(!view.endOfTextblock("down"))
  })

  it("works for virtual motion when in a mark", () => {
    let view = tempEditor({doc: doc(p(a("foo "), new Array(50).join("foo "), a("foo "),
                                      new Array(50).join("foo "), a("fo<c>o")))})
    ist(view.endOfTextblock("up"))
    ist(!view.endOfTextblock("down"))
    view.dispatch(view.state.tr.setSelection(TextSelection.create(view.state.doc, (view.state.doc as any).tag.b)))
    ist(!view.endOfTextblock("up"))
    ist(!view.endOfTextblock("down"))
    view.dispatch(view.state.tr.setSelection(TextSelection.create(view.state.doc, (view.state.doc as any).tag.c)))
    ist(!view.endOfTextblock("up"))
    ist(view.endOfTextblock("down"))
  })

  // Bidi functionality only works when the browser has Selection.modify
  if (!(getSelection() as any).modify) return

  it("works at the start of an RTL block", () => {
    let view = tempEditor({doc: doc(p("مرآة"))})
    view.dom.style.direction = "rtl"
    ist(!view.endOfTextblock("left"))
    ist(view.endOfTextblock("backward"))
    ist(view.endOfTextblock("right"))
    ist(!view.endOfTextblock("forward"))
  })

  it("works at the end of an RTL block", () => {
    let view = tempEditor({doc: doc(p("مرآة"))})
    view.dom.style.direction = "rtl"
    ist(view.endOfTextblock("left"))
    ist(!view.endOfTextblock("backward"))
    ist(!view.endOfTextblock("right"))
    ist(view.endOfTextblock("forward"))
  })

  it("works inside an RTL block", () => {
    let view = tempEditor({doc: doc(p("مرآة"))})
    view.dom.style.direction = "rtl"
    ist(!view.endOfTextblock("left"))
    ist(!view.endOfTextblock("backward"))
    ist(!view.endOfTextblock("right"))
    ist(!view.endOfTextblock("forward"))
  })

  it("works in a bidirectional block", () => {
    let view = tempEditor({doc: doc(p("proseمرآة"))})
    ist(!view.endOfTextblock("left"))
    ist(!view.endOfTextblock("backward"))
    ist(view.endOfTextblock("forward"))
  })

  it("works in a cursor wrapper", () => {
    let view = tempEditor({doc: doc(p("foo"))})
    view.dispatch(view.state.tr.setStoredMarks([schema.marks.em.create()]))
    ist(!view.endOfTextblock("backward"))
  })

  it("works after a widget", () => {
    let d = doc(p("foo")), w = document.createElement("span")
    w.textContent = "!"
    let view = tempEditor({doc: d, decorations() {
      return DecorationSet.create(d, [Decoration.widget(3, w)])
    }})
    ist(!view.endOfTextblock("backward"))
  })
})


text:
import React from 'react';
import Input from "react-toolbox/lib/input";
import Button from "react-toolbox/lib/button";
import { Card, Icon } from "../../components/UI";
import logo from "../netlify-auth/netlify_logo.svg";
import styles from "../netlify-auth/AuthenticationPage.css";

export default class AuthenticationPage extends React.Component {
  static propTypes = {
    onLogin: React.PropTypes.func.isRequired,
  };

  state = { email: '' };

  handleLogin = (e) => {
    e.preventDefault();
    this.props.onLogin(this.state);
  };

  handleEmailChange = (value) => {
    this.setState({ email: value });
  };

  render() {
    return (

      <Card className={styles.card}>

This is a demo, enter your email to start

        <Input
          type="text"
          label="Email"
          name="email"
          value={this.state.email}
          onChange={this.handleEmailChange}
        />
        <Button
          className={styles.button}
          raised
          onClick={this.handleLogin}
        >
          <Icon type="login" /> Login
        </Button>
      </Card>

);
  }
}


text:
<?php
class Kwc_Basic_Space_Model extends Kwf_Model_Db
{
    protected $_table = 'kwc_basic_space';
}


text:
'use strict';
require('../common');
const assert = require('assert');

const rusage = process.resourceUsage();
const fields = [
  'userCPUTime',
  'systemCPUTime',
  'maxRSS',
  'sharedMemorySize',
  'unsharedDataSize',
  'unsharedStackSize',
  'minorPageFault',
  'majorPageFault',
  'swappedOut',
  'fsRead',
  'fsWrite',
  'ipcSent',
  'ipcReceived',
  'signalsCount',
  'voluntaryContextSwitches',
  'involuntaryContextSwitches'
];

assert.deepStrictEqual(Object.keys(rusage).sort(), fields.sort());

fields.forEach((n) => {
  assert.strictEqual(typeof rusage[n], 'number', `${n} should be a number`);
  assert(rusage[n] >= 0, `${n} should be above or equal 0`);
});


text:
package main

import (
	"flag"
	"os"

	log "github.com/golang/glog"
	"github.com/youtube/vitess/go/tb"
	"github.com/youtube/vitess/go/vt/topo"
	"github.com/youtube/vitess/go/vt/topotools"
)

var fromTopo = flag.String("from", "", "topology to copy data from")
var toTopo = flag.String("to", "", "topology to copy data to")

var doKeyspaces = flag.Bool("do-keyspaces", false, "copies the keyspace information")
var doShards = flag.Bool("do-shards", false, "copies the shard information")
var doShardReplications = flag.Bool("do-shard-replications", false, "copies the shard replication information")
var doTablets = flag.Bool("do-tablets", false, "copies the tablet information")

var deleteKeyspaceShards = flag.Bool("delete-keyspace-shards", false, "when copying shards, first removes the destination shards (will nuke the replication graph)")

func main() {
	defer func() {
		if panicErr := recover(); panicErr != nil {
			log.Fatalf("panic: %v", tb.Errorf("%v", panicErr))
		}
	}()

	flag.Parse()
	args := flag.Args()
	if len(args) != 0 {
		flag.Usage()
		os.Exit(1)
	}

	if *fromTopo == "" || *toTopo == "" {
		log.Fatalf("Need both from and to topo")
	}

	fromTS := topo.GetServerByName(*fromTopo)
	toTS := topo.GetServerByName(*toTopo)

	if *doKeyspaces {
		topotools.CopyKeyspaces(fromTS, toTS)
	}
	if *doShards {
		topotools.CopyShards(fromTS, toTS, *deleteKeyspaceShards)
	}
	if *doShardReplications {
		topotools.CopyShardReplications(fromTS, toTS)
	}
	if *doTablets {
		topotools.CopyTablets(fromTS, toTS)
	}
}


text:
using System.Xml.Serialization;

namespace MpzMail.Api.Model
{
    public enum DateSegmentFieldType
    {
        [XmlElement("dateOfBirth")]
        DateOfBirth = 0,
        [XmlElement("dateAdded")]
        CreateDate = 1
    }
}


text:
"""
test_dnstester
----------------------------------

Tests for `dnstester` module.
"""

import unittest

from dnstester import dnstester

class TestDnstester(unittest.TestCase):

    def setUp(self):
        pass

    def test_something(self):
        pass

    def tearDown(self):
        pass

if __name__ == '__main__':
    unittest.main()


text:
package org.Webgatherer.Utility;

import java.util.ArrayList;
import java.util.List;

/**
 * This is just an ad-hoc class at this point
 *
 * @author Rick Dane
 */
public class TextReformatter {

    private static String inputFilePath = "/home/user/Desktop/rawids";
    private static String outputFilePath = "/home/user/Desktop/formattedforsql";
    private static String surroundingCharacter = "";    //"\""

    public static void main(String[] args) {

        ReadFiles readFiles = new ReadFiles();
        List<String> linesList = readFiles.readLinesToList(inputFilePath);

        List<String> duplicateCheck = new ArrayList<String>();

        StringBuilder strBld = new StringBuilder();
        for (String curLine : linesList) {

            strBld.append(curLine);

        }

        StringBuilder outputStringBld = new StringBuilder();

        String document = strBld.toString();

        String[] split = document.split("\\|");

        for (String curEntry : split) {
            String[] splitComma = curEntry.split(",");
            outputStringBld.append(splitComma[0] + ",\n");
        }

        System.out.println(outputStringBld.toString());

    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mjiayou.testmoduleb">

    <application>
        <activity android:name=".TestModuleBActivity" />
    </application>
</manifest>


text:
#import "TMLAPIRequest.h"

@implementation TMLAPIRequest

#pragma mark - Init

- (instancetype)initWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters {
    if (self = [super init]) {
        self.method = method;
        self.path = path;
        self.parameters = parameters;
    }
    return self;
}

+ (instancetype)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters {
    return [[TMLAPIRequest alloc] initWithMethod:method path:path parameters:parameters];
}

@end


text:
<?php
// autogenerated file 30.09.2013 15:20
// $Id: $
// $Log: $
//
//
require_once 'EbatNs_ComplexType.php';

/**
 * Indicates whether the category supports using the telephone as a contact
 * method.Added for EbayMotors Pro users.
 *
 * @link http://developer.ebay.com/DevZone/XML/docs/Reference/eBay/types/eBayMotorsProContactByPhoneEnabledDefinitionType.html
 *
 */
class eBayMotorsProContactByPhoneEnabledDefinitionType extends EbatNs_ComplexType
{

	/**
	 * @return
	 */
	function __construct()
	{
		parent::__construct('eBayMotorsProContactByPhoneEnabledDefinitionType', 'urn:ebay:apis:eBLBaseComponents');
		if (!isset(self::$_elements[__CLASS__])) {
			self::$_elements[__CLASS__] = array_merge(self::$_elements[get_parent_class()], array());
		}
	}
}
?>


text:
<?php
//require_once 'PHPUnit/Framework/TestSuite.php';

class AllTests {

	public static function suite() {

		$suite = new PHPUnit_Framework_TestSuite();

		foreach (self::$tests as $value)
		{
			require_once $value.'.php';
			$suite->addTestSuite($value);
		}

		return $suite;
	}

	protected static $tests = array(
		  'Base64SerializerTest'
		, 'DeflateSerializerTest'
		, 'MsgpackSerializerTest'
		, 'ZlibSerializerTest'
	);
}


text:
package org.elasticsearch.plugin.river.couchdb;

import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.plugins.AbstractPlugin;
import org.elasticsearch.river.RiversModule;
import org.elasticsearch.river.couchdb.CouchdbRiverModule;

/**
 *
 */
public class CouchdbRiverPlugin extends AbstractPlugin {

    @Inject
    public CouchdbRiverPlugin() {
    }

    @Override
    public String name() {
        return "river-couchdb";
    }

    @Override
    public String description() {
        return "River CouchDB Plugin";
    }

    public void onModule(RiversModule module) {
        module.registerRiver("couchdb", CouchdbRiverModule.class);
    }
}


text:
using System;

namespace VkNet.Exception;

/// <summary>
/// История событий устарела или была частично утеряна, приложение может получать события далее, используя новое значение ts из ответа.
/// </summary>
[Serializable]
public class LongPollOutdateException : LongPollException
{
	/// <summary>
	/// Значение для кода ошибки - 1
	/// </summary>
	public string Ts { get; set; }

	/// <inheritdoc />
	public LongPollOutdateException(string ts) : base(OutdateException,
		"История событий устарела или была частично утеряна, приложение может получать события далее, используя новое значение ts из ответа.") =>
		Ts = ts;
}


text:
require 'fog/core/model'

module Fog
  module Compute
    class Google

      class Zone < Fog::Model

        identity :name
        attribute :description
        attribute :status
        attribute :maintenance_windows, :aliases => 'maintenanceWindows'
        attribute :begin_time, :aliases => 'beginTime'
        attribute :end_time, :aliases => 'endTime'
        attribute :quotas
        attribute :region
        attribute :self_link, :aliases => 'selfLink'

        def up?
          self.status == "UP"
        end

      end
    end
  end
end


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.github.inder123</groupId>
	<artifactId>json2java</artifactId>
	<version>1.0.4</version>
	<dependencies>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.8.2</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.7.0</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
import {
	Component,
	OnInit,
	NgZone
} from '@angular/core';
import {
	Router
} from '@angular/router';
import {
	Mongo
} from 'meteor/mongo';
import {
	Meteor
} from 'meteor/meteor';

import {
	FormGroup,
	FormBuilder,
	Validators
} from '@angular/forms';
import template from './login.html';

@Component({
	selector: 'login',
	template
})

export class LoginComponent implements OnInit {
	addForm: FormGroup;
	resetEmailForm: FormGroup;
	resetEmail: string;
	email: string;
	password: string;
	message: string;
	showmessage: boolean = false;
	loginprocess: boolean;
	logintime: any;

	current_date: any;
	current_month: any;
	current_year: any;
	years: number[];
	constructor(private ngZone: NgZone, private formBuilder: FormBuilder, private _router: Router) {

	}

	ngOnInit() {
		// list of things we do when our login component loads
		this.current_date = new Date(); // storing current date in current date variable
		this.current_month = this.current_date.getMonth() + 1; // extracting current month value
		this.current_year = this.current_date.getFullYear();
		//  *** checking if user is already login ***
		if (Meteor.user()) { // if user already login then redirect him to csvtimeline component.
			this._router.navigate(['csvtemplate/csvtimeline', this.current_month, this.current_year]);
		}
		this.getYears(-10, 10); // get Year function will give us list of 10 years date from current date.
		this.addForm = this.formBuilder.group({ // this is the form used to take input at login
			email: ['', Validators.required],
			password: ['', Validators.required],
			FYYear: ['Select Financial Year', Validators.required] // option to select financial year
		});
		this.resetEmailForm = this.formBuilder.group({ // this is the form used to take email to reset password
			email: ['', Validators.required]
		});

		this.loginprocess = false;
	}
	// code to get list of years in years variable
	getYears(offset: number, range: number) {
		this.years = [];
		for (var i = 0; i < range + 1; i++) {
			this.years.push(this.current_year + offset + i);
		}
	}

	// function called when we enter our login detail and click login
	login() {
		var self = this;
		self.loginprocess = true;
		if (this.addForm.valid) { // run code only if form is valid
			self.logintime = new Date();
			this.email = this.addForm.controls['email'].value; // taking out email value
			this.password = this.addForm.controls['password'].value; // taking out password value
			if (isNaN(this.addForm.controls['FYYear'].value)) { // checking financial year value
				this.ngZone.run(() => { // if financial year is not selected show error message.
					this.loginprocess = false;
					this.showmessage = true;
					this.message = "Please Select Financial Year";
				});
			} else {
				// meteor method to login a user by passing email and password into loginwithpassword function
				Meteor.loginWithPassword(this.email, this.password, function (error) {
					if (Meteor.user()) { // if login is successfull we will store logintime in localstorage and current financial year.
						localStorage.setItem("login_time", self.logintime);
						localStorage.setItem("Selected_financial_year", new Date('04-04-' + self.addForm.controls['FYYear'].value).toString());
						console.log('04-04-' + self.addForm.controls['FYYear'].value);
						// After successfull login redirect to csvtimeline component.
						self._router.navigate(['csvtemplate/csvtimeline', self.current_month, self.current_year]);
					} else {
						self.ngZone.run(() => { // if there is error at login time show error message
							self.loginprocess = false;
							self.showmessage = true;
							self.message = error.reason;
						});
					}
				});
			}
		}
	}

	//function called when click to forgot password
	forgotUserPassword() {
		var self = this;
		this.resetEmail = this.resetEmailForm.controls['email'].value; // taking out email value
		Accounts.forgotPassword({
			email: this.resetEmail
		}, function (res) {
			if (res) {
				if (res.message === 'User not found [403]') {
					alert('This email does not exist.');
				} else {
					alert('We are sorry but something went wrong.');
					console.log(res)
				}
			} else {
				alert('Email Sent. Check your mailbox.');
				this.location.reload();
			}
		});
	}
}


text:
namespace metro_driver {
namespace {

ImePopupObserver* g_observer_ = NULL;
HWINEVENTHOOK g_hook_handle_ = NULL;

void CALLBACK ImeEventCallback(HWINEVENTHOOK win_event_hook_handle,
                               DWORD event,
                               HWND window_handle,
                               LONG object_id,
                               LONG child_id,
                               DWORD event_thread,
                               DWORD event_time) {
  // This function is registered to SetWinEventHook to be called back on the UI
  // thread.
  DCHECK(base::MessageLoop::current()->IsType(base::MessageLoop::TYPE_UI));

  if (!g_observer_)
    return;
  switch (event) {
    case EVENT_OBJECT_IME_SHOW:
      g_observer_->OnImePopupChanged(ImePopupObserver::kPopupShown);
      return;
    case EVENT_OBJECT_IME_HIDE:
      g_observer_->OnImePopupChanged(ImePopupObserver::kPopupHidden);
      return;
    case EVENT_OBJECT_IME_CHANGE:
      g_observer_->OnImePopupChanged(ImePopupObserver::kPopupUpdated);
      return;
  }
}

}  // namespace

void AddImePopupObserver(ImePopupObserver* observer) {
  CHECK(g_observer_ == NULL)
      << "Currently only one observer is supported at the same time.";
  g_observer_ = observer;

  // IMEs running under immersive mode are supposed to generate WinEvent
  // whenever their popup UI such as candidate window is shown, updated, and
  // hidden to support accessibility applications.
  // http://msdn.microsoft.com/en-us/library/windows/apps/hh967425.aspx#accessibility
  // Note that there is another mechanism in TSF, called ITfUIElementSink, to
  // subscribe when the visibility of an IME's UI element is changed. However,
  // MS-IME running under immersive mode does not fully support this API.
  // Thus, WinEvent is more reliable for this purpose.
  g_hook_handle_ = SetWinEventHook(
      EVENT_OBJECT_IME_SHOW,
      EVENT_OBJECT_IME_CHANGE,
      NULL,
      ImeEventCallback,
      GetCurrentProcessId(),  // monitor the metro_driver process only
      0,   // hook all threads because MS-IME emits WinEvent in a worker thread
      WINEVENT_OUTOFCONTEXT);  // allows us to receive message in the UI thread
  LOG_IF(ERROR, !g_hook_handle_) << "SetWinEventHook failed.";
}

void RemoveImePopupObserver(ImePopupObserver* observer) {
  if (g_observer_ != observer)
    return;
  g_observer_ = NULL;
  if (!g_hook_handle_)
    return;
  const bool unhook_succeeded = !!UnhookWinEvent(g_hook_handle_);
  LOG_IF(ERROR, !unhook_succeeded) << "UnhookWinEvent failed.";
  g_hook_handle_ = NULL;
}

}  // namespace metro_driver


text:
import {isDevMode} from '@angular/core';
import {identifierName} from '../compile_metadata';

import {EmitterVisitorContext} from './abstract_emitter';
import {AbstractJsEmitterVisitor} from './abstract_js_emitter';
import * as o from './output_ast';

function evalExpression(
    sourceUrl: string, ctx: EmitterVisitorContext, vars: {[key: string]: any}): any {
  let fnBody = `${ctx.toSource()}\n//# sourceURL=${sourceUrl}`;
  const fnArgNames: string[] = [];
  const fnArgValues: any[] = [];
  for (const argName in vars) {
    fnArgNames.push(argName);
    fnArgValues.push(vars[argName]);
  }
  if (isDevMode()) {
    // using `new Function(...)` generates a header, 1 line of no arguments, 2 lines otherwise
    // E.g. ```
    // function anonymous(a,b,c
    // /**/) { ... }```
    // We don't want to hard code this fact, so we auto detect it via an empty function first.
    const emptyFn = new Function(...fnArgNames.concat('return null;')).toString();
    const headerLines = emptyFn.slice(0, emptyFn.indexOf('return null;')).split('\n').length - 1;
    fnBody += `\n${ctx.toSourceMapGenerator(sourceUrl, sourceUrl, headerLines).toJsComment()}`;
  }
  return new Function(...fnArgNames.concat(fnBody))(...fnArgValues);
}

export function jitStatements(sourceUrl: string, statements: o.Statement[]): {[key: string]: any} {
  const converter = new JitEmitterVisitor();
  const ctx = EmitterVisitorContext.createRoot();
  converter.visitAllStatements(statements, ctx);
  converter.createReturnStmt(ctx);
  return evalExpression(sourceUrl, ctx, converter.getArgs());
}

class JitEmitterVisitor extends AbstractJsEmitterVisitor {
  private _evalArgNames: string[] = [];
  private _evalArgValues: any[] = [];
  private _evalExportedVars: string[] = [];

  createReturnStmt(ctx: EmitterVisitorContext) {
    const stmt = new o.ReturnStatement(new o.LiteralMapExpr(this._evalExportedVars.map(
        resultVar => new o.LiteralMapEntry(resultVar, o.variable(resultVar), false))));
    stmt.visitStatement(this, ctx);
  }

  getArgs(): {[key: string]: any} {
    const result: {[key: string]: any} = {};
    for (let i = 0; i < this._evalArgNames.length; i++) {
      result[this._evalArgNames[i]] = this._evalArgValues[i];
    }
    return result;
  }

  visitExternalExpr(ast: o.ExternalExpr, ctx: EmitterVisitorContext): any {
    const value = ast.value.runtime;
    let id = this._evalArgValues.indexOf(value);
    if (id === -1) {
      id = this._evalArgValues.length;
      this._evalArgValues.push(value);
      const name = identifierName({reference: ast.value.runtime}) || 'val';
      this._evalArgNames.push(`jit_${name}${id}`);
    }
    ctx.print(ast, this._evalArgNames[id]);
    return null;
  }

  visitDeclareVarStmt(stmt: o.DeclareVarStmt, ctx: EmitterVisitorContext): any {
    if (stmt.hasModifier(o.StmtModifier.Exported)) {
      this._evalExportedVars.push(stmt.name);
    }
    return super.visitDeclareVarStmt(stmt, ctx);
  }

  visitDeclareFunctionStmt(stmt: o.DeclareFunctionStmt, ctx: EmitterVisitorContext): any {
    if (stmt.hasModifier(o.StmtModifier.Exported)) {
      this._evalExportedVars.push(stmt.name);
    }
    return super.visitDeclareFunctionStmt(stmt, ctx);
  }

  visitDeclareClassStmt(stmt: o.ClassStmt, ctx: EmitterVisitorContext): any {
    if (stmt.hasModifier(o.StmtModifier.Exported)) {
      this._evalExportedVars.push(stmt.name);
    }
    return super.visitDeclareClassStmt(stmt, ctx);
  }
}


text:
<?php

namespace Sculpin\Contrib\ProxySourceCollection;

use Sculpin\Core\Source\SourceInterface;

class SimpleProxySourceItemFactory implements ProxySourceItemFactoryInterface
{
    private $reflectionClass;

    public function __construct($class = null)
    {
        $this->reflectionClass = new \ReflectionClass(
            $class ?: 'Sculpin\Contrib\ProxySourceCollection\ProxySourceItem'
        );
    }

    public function createProxySourceItem(SourceInterface $source)
    {
        return $this->reflectionClass->newInstance($source);
    }
}


text:
/**
 * @fileoverview Generating Python for math blocks.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

Blockly.Python = Blockly.Generator.get('Python');

if (!Blockly.Python.RESERVED_WORDS_) {
  Blockly.Python.RESERVED_WORDS_ = '';
}
Blockly.Python.RESERVED_WORDS_ += 'math,random,';

Blockly.Python.math_number = function() {
  // Numeric value.
  var code = window.parseFloat(this.getTitleValue('NUM'));
  return [code, Blockly.Python.ORDER_UNARY_SIGN];
};

Blockly.Python.math_arithmetic = function() {
  // Basic arithmetic operators, and power.
  var mode = this.getTitleValue('OP');
  var tuple = Blockly.Python.math_arithmetic.OPERATORS[mode];
  var operator = tuple[0];
  var order = tuple[1];
  var argument0 = Blockly.Python.valueToCode(this, 'A', order) || '0';
  var argument1 = Blockly.Python.valueToCode(this, 'B', order) || '0';
  var code = argument0 + operator + argument1;
  return [code, order];
  // In case of 'DIVIDE', division between integers returns different results
  // in Python 2 and 3. However, is not an issue since Blockly does not
  // guarantee identical results in all languages.  To do otherwise would
  // require every operator to be wrapped in a function call.  This would kill
  // legibility of the generated code.  See:
  // http://code.google.com/p/blockly/wiki/Language
};

Blockly.Python.math_arithmetic.OPERATORS = {
  ADD: [' + ', Blockly.Python.ORDER_ADDITIVE],
  MINUS: [' - ', Blockly.Python.ORDER_ADDITIVE],
  MULTIPLY: [' * ', Blockly.Python.ORDER_MULTIPLICATIVE],
  DIVIDE: [' / ', Blockly.Python.ORDER_MULTIPLICATIVE],
  POWER: [' ** ', Blockly.Python.ORDER_EXPONENTIATION]
};

Blockly.Python.math_change = function() {
  // Add to a variable in place.
  var argument0 = Blockly.Python.valueToCode(this, 'DELTA',
      Blockly.Python.ORDER_ADDITIVE) || '0';
  var varName = Blockly.Python.variableDB_.getName(this.getTitleValue('VAR'),
      Blockly.Variables.NAME_TYPE);
  return varName + ' = (' + varName + ' if type(' + varName +
      ') in (int, float) else 0) + ' + argument0 + '\n';
};

Blockly.Python.math_single = function() {
  // Math operators with single operand.
  var operator = this.getTitleValue('OP');
  var code;
  var arg;
  if (operator == 'NEG') {
    // Negation is a special case given its different operator precedence.
    var code = Blockly.Python.valueToCode(this, 'NUM',
        Blockly.Python.ORDER_UNARY_SIGN) || '0';
    return ['-' + code, Blockly.Python.ORDER_UNARY_SIGN];
  }
  Blockly.Python.definitions_['import_math'] = 'import math';
  if (operator == 'SIN' || operator == 'COS' || operator == 'TAN') {
    arg = Blockly.Python.valueToCode(this, 'NUM',
        Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
  } else {
    arg = Blockly.Python.valueToCode(this, 'NUM',
        Blockly.Python.ORDER_NONE) || '0';
  }
  // First, handle cases which generate values that don't need parentheses
  // wrapping the code.
  switch (operator) {
    case 'ABS':
      code = 'math.fabs(' + arg + ')';
      break;
    case 'ROOT':
      code = 'math.sqrt(' + arg + ')';
      break;
    case 'LN':
      code = 'math.log(' + arg + ')';
      break;
    case 'LOG10':
      code = 'math.log10(' + arg + ')';
      break;
    case 'EXP':
      code = 'math.exp(' + arg + ')';
      break;
    case 'POW10':
      code = 'math.pow(10,' + arg + ')';
      break;
    case 'ROUND':
      code = 'round(' + arg + ')';
      break;
    case 'ROUNDUP':
      code = 'math.ceil(' + arg + ')';
      break;
    case 'ROUNDDOWN':
      code = 'math.floor(' + arg + ')';
      break;
    case 'SIN':
      code = 'math.sin(' + arg + ' / 180.0 * math.pi)';
      break;
    case 'COS':
      code = 'math.cos(' + arg + ' / 180.0 * math.pi)';
      break;
    case 'TAN':
      code = 'math.tan(' + arg + ' / 180.0 * math.pi)';
      break;
  }
  if (code) {
    return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  }
  // Second, handle cases which generate values that may need parentheses
  // wrapping the code.
  switch (operator) {
    case 'ASIN':
      code = 'math.asin(' + arg + ') / math.pi * 180';
      break;
    case 'ACOS':
      code = 'math.acos(' + arg + ') / math.pi * 180';
      break;
    case 'ATAN':
      code = 'math.atan(' + arg + ') / math.pi * 180';
      break;
    default:
      throw 'Unknown math operator: ' + operator;
  }
  return [code, Blockly.Python.ORDER_MULTIPLICATIVE];
};

// Rounding functions have a single operand.
Blockly.Python.math_round = Blockly.Python.math_single;
// Trigonometry functions have a single operand.
Blockly.Python.math_trig = Blockly.Python.math_single;

Blockly.Python.math_on_list = function() {
  // Math functions for lists.
  var func = this.getTitleValue('OP');
  var list = Blockly.Python.valueToCode(this, 'LIST',
      Blockly.Python.ORDER_NONE) || '[]';
  var code;
  switch (func) {
    case 'SUM':
      code = 'sum(' + list + ')';
      break;
    case 'MIN':
      code = 'min(' + list + ')';
      break;
    case 'MAX':
      code = 'max(' + list + ')';
      break;
    case 'AVERAGE':
      if (!Blockly.Python.definitions_['math_mean']) {
        // This operation exclude null and values that are not int or float:
        //   math_mean([null,null,"aString",1,9]) == 5.0.
        var functionName = Blockly.Python.variableDB_.getDistinctName(
            'math_mean', Blockly.Generator.NAME_TYPE);
        Blockly.Python.math_on_list.math_mean = functionName;
        var func = [];
        func.push('def ' + functionName + '(myList):');
        func.push('  localList = [e for e in myList ' +
            'if type(e) in [int, float]]');
        func.push('  if not localList: return');
        func.push('  return float(sum(localList)) / len(localList)');
        Blockly.Python.definitions_['math_mean'] = func.join('\n');
      }
      code = Blockly.Python.math_on_list.math_mean + '(' + list + ')';
      break;
    case 'MEDIAN':
      if (!Blockly.Python.definitions_['math_median']) {
        // This operation exclude null values:
        //   math_median([null,null,1,3]) == 2.0.
        var functionName = Blockly.Python.variableDB_.getDistinctName(
            'math_median', Blockly.Generator.NAME_TYPE);
        Blockly.Python.math_on_list.math_median = functionName;
        var func = [];
        func.push('def ' + functionName + '(myList):');
        func.push('  localList = sorted([e for e in myList ' +
            'if type(e) in [int, float]])');
        func.push('  if not localList: return');
        func.push('  if len(localList) % 2 == 0:');
        func.push('    return (localList[len(localList) / 2 - 1] + ' +
            'localList[len(localList) / 2]) / 2.0');
        func.push('  else:');
        func.push('    return localList[(len(localList) - 1) / 2]');
        Blockly.Python.definitions_['math_median'] = func.join('\n');
      }
      code = Blockly.Python.math_on_list.math_median + '(' + list + ')';
      break;
    case 'MODE':
      if (!Blockly.Python.definitions_['math_modes']) {
        // As a list of numbers can contain more than one mode,
        // the returned result is provided as an array.
        // Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1].
        var functionName = Blockly.Python.variableDB_.getDistinctName(
            'math_modes', Blockly.Generator.NAME_TYPE);
        Blockly.Python.math_on_list.math_modes = functionName;
        var func = [];
        func.push('def ' + functionName + '(some_list):');
        func.push('  modes = []');
        func.push('  # Using a lists of [item, count] to keep count rather ' +
                  'than dict');
        func.push('  # to avoid "unhashable" errors when the counted item is ' +
                  'itself a list or dict.');
        func.push('  counts = []');
        func.push('  maxCount = 1');
        func.push('  for item in some_list:');
        func.push('    found = False');
        func.push('    for count in counts:');
        func.push('      if count[0] == item:');
        func.push('        count[1] += 1');
        func.push('        maxCount = max(maxCount, count[1])');
        func.push('        found = True');
        func.push('    if not found:');
        func.push('      counts.append([item, 1])');
        func.push('  for counted_item, item_count in counts:');
        func.push('    if item_count == maxCount:');
        func.push('      modes.append(counted_item)');
        func.push('  return modes');
        Blockly.Python.definitions_['math_modes'] = func.join('\n');
      }
      code = Blockly.Python.math_on_list.math_modes + '(' + list + ')';
      break;
    case 'STD_DEV':
      if (!Blockly.Python.definitions_['math_standard_deviation']) {
        Blockly.Python.definitions_['import_math'] = 'import math';
        var functionName = Blockly.Python.variableDB_.getDistinctName(
            'math_standard_deviation', Blockly.Generator.NAME_TYPE);
        Blockly.Python.math_on_list.math_standard_deviation = functionName;
        var func = [];
        func.push('def ' + functionName + '(numbers):');
        func.push('  n = len(numbers)');
        func.push('  if n == 0: return');
        func.push('  mean = float(sum(numbers)) / n');
        func.push('  variance = sum((x - mean) ** 2 for x in numbers) / n');
        func.push('  return math.sqrt(variance)');
        Blockly.Python.definitions_['math_standard_deviation'] =
            func.join('\n');
      }
      code = Blockly.Python.math_on_list.math_standard_deviation +
          '(' + list + ')';
      break;
    case 'RANDOM':
      Blockly.Python.definitions_['import_random'] = 'import random';
      code = 'random.choice(' + list + ')';
      break;
    default:
      throw 'Unknown operator: ' + func;
  }
  return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};

Blockly.Python.math_constrain = function() {
  // Constrain a number between two limits.
  var argument0 = Blockly.Python.valueToCode(this, 'VALUE',
      Blockly.Python.ORDER_NONE) || '0';
  var argument1 = Blockly.Python.valueToCode(this, 'LOW',
      Blockly.Python.ORDER_NONE) || '0';
  var argument2 = Blockly.Python.valueToCode(this, 'HIGH',
      Blockly.Python.ORDER_NONE) || '0';
  var code = 'min(max(' + argument0 + ', ' + argument1 + '), ' +
      argument2 + ')';
  return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};

Blockly.Python.math_modulo = function() {
  // Remainder computation.
  var argument0 = Blockly.Python.valueToCode(this, 'DIVIDEND',
      Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
  var argument1 = Blockly.Python.valueToCode(this, 'DIVISOR',
      Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
  var code = argument0 + ' % ' + argument1;
  return [code, Blockly.Python.ORDER_MULTIPLICATIVE];
};

Blockly.Python.math_random_int = function() {
  // Random integer between [X] and [Y].
  Blockly.Python.definitions_['import_random'] = 'import random';
  var argument0 = Blockly.Python.valueToCode(this, 'FROM',
      Blockly.Python.ORDER_NONE) || '0';
  var argument1 = Blockly.Python.valueToCode(this, 'TO',
      Blockly.Python.ORDER_NONE) || '0';
  var code = 'random.randint(' + argument0 + ', ' + argument1 + ')';
  return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};

Blockly.Python.math_random_float = function() {
  // Random fraction between 0 and 1.
  Blockly.Python.definitions_['import_random'] = 'import random';
  return ['random.random()', Blockly.Python.ORDER_FUNCTION_CALL];
};


text:
<?php

namespace asset\assets;
use asset\filters\FilterInterface;

interface AssetInterface
{
    public function addFilter(FilterInterface $filter);
    public function getFilters();
    public function clearFilters();

    public function getLastModified();

    public function getContent();
    public function getToken();
}


text:
<?php
  // For the testing of this database, the username and password are the same
  // They are the names of our staff members.

if(!isset($_POST['val']) OR !isset($_POST['signID']) OR !isset($_POST['patientID'])){
  include('index.php');
  exit();
 }

session_start();
$val = $_POST['val'];
$signID= (int)$_POST['signID'];
$patientID = (int)$_POST['patientID'];
$note = $_POST['note'];
include('pdo.inc.php');

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
    /*** echo a message saying we have connected ***/
    // echo 'Connected to database<br />';

    /*** set the error reporting attribute ***/
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    /*** prepare the SQL statement ***/
    $stmt = $dbh->prepare("INSERT INTO vital_sign (`vital_signID`, `patientID`, `signID`, `value`, `time`, `note`) VALUES (NULL, :patientID, :signID, :value, CURRENT_TIMESTAMP, :note);");

    /*** bind the paramaters ***/
    $stmt->bindParam(':patientID', $patientID, PDO::PARAM_INT);
    $stmt->bindParam(':signID', $signID, PDO::PARAM_INT);
    $stmt->bindParam(':value', $val, PDO::PARAM_STR,5);
    $stmt->bindParam(':note', $note, PDO::PARAM_STR, 5);

    /*** execute the prepared statement ***/
    $stmt->execute();

    // redirect to the page home.php
    header('location: ../view/patient.html?id='.$patientID);

    /*** close the database connection ***/
    $dbh = null;

    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }

?>


text:
package org.robbins.flashcards.presentation;

import org.apache.struts2.StrutsTestCase;
import org.robbins.flashcards.presentation.action.TagAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionProxy;

public class TagActionTxst extends StrutsTestCase {

    private static final Logger LOGGER = LoggerFactory.getLogger(TagActionTxst.class);

    public void testCreateTagFail() throws Exception {
        try {
            request.setParameter("name", "");

            ActionProxy proxy = getActionProxy("/tag/saveOrUpdate.action");

            TagAction tagAction = (TagAction) proxy.getAction();

            proxy.execute();

            assertTrue(
                    "Problem There were no errors present in fieldErrors but there should have been one error present",
                    tagAction.getFieldErrors().size() == 1);
            assertTrue(
                    "Problem field 'name' not present in fieldErrors but it should have been",
                    tagAction.getFieldErrors().containsKey("name"));
        } catch (Exception e) {
            LOGGER.debug("Error running testCreateTagFail()");
            LOGGER.error(e.getMessage(), e);

            assertTrue("Error running testCreateTagFail()", false);
        }
    }

    public void testCreateTag() throws Exception {
        request.setParameter("name", "my tag name");

        ActionProxy proxy = getActionProxy("/tag/saveOrUpdate.action");

        TagAction tagAction = (TagAction) proxy.getAction();

        String result = proxy.execute();

        assertTrue(
                "Problem There were errors present in fieldErrors but there should not have been any errors present",
                tagAction.getFieldErrors().size() == 0);
        assertEquals(
                "Result returned form executing the action was not success but it should have been.",
                "success", result);
    }

    public void testListTags() throws Exception {
        ActionProxy proxy = getActionProxy("/tag/list.action");

        String result = proxy.execute();

        assertEquals(
                "Result returned form executing the action was not success but it should have been.",
                "success", result);
    }

    public void testDisplayTag() throws Exception {
        String result = "";

        try {
            request.setParameter("name", "my tag name");

            ActionProxy proxy = getActionProxy("/tag/display.action");

            result = proxy.execute();

        } catch (Exception e) {
            LOGGER.debug("Error running testDisplayTag()");
            LOGGER.error(e.getMessage(), e);
        }

        assertEquals(
                "Result returned form executing the action was not success but it should have been.",
                "success", result);
    }

}


text:
package org.elasticsearch.index.mapper.core;

import org.elasticsearch.index.mapper.FieldTypeTestCase;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.junit.Before;

public class BooleanFieldTypeTests extends FieldTypeTestCase {
    @Override
    protected MappedFieldType createDefaultFieldType() {
        return new BooleanFieldMapper.BooleanFieldType();
    }

    @Before
    public void setupProperties() {
        setDummyNullValue(true);
    }

    public void testValueFormat() {
        MappedFieldType ft = createDefaultFieldType();
        assertEquals("false", ft.docValueFormat(null, null).format(0));
        assertEquals("true", ft.docValueFormat(null, null).format(1));
    }
}


text:
namespace peloton {
namespace concurrency {

//  volatile cid_t EpochManager::curr_epoch_ = 1;

}
}


text:
class Admin::PeopleController < Admin::BaseController
  before_action :load_person, only: %i[show edit update destroy]
  before_action :enforce_permissions!, only: %i[edit update destroy]

  def index
    @people = Person.order(:surname, :forename).includes(:translations)
  end

  def new
    @person = Person.new
  end

  def create
    @person = Person.new(person_params)
    if @person.save
      redirect_to [:admin, @person], notice: %("#{@person.name}" created.)
    else
      render action: "new"
    end
  end

  def show; end

  def edit; end

  def update
    if @person.update(person_params)
      redirect_to [:admin, @person], notice: %("#{@person.name}" saved.)
    else
      render action: "edit"
    end
  end

  def destroy
    if @person.destroy
      redirect_to admin_people_path, notice: %("#{@person.name}" destroyed.)
    else
      redirect_to admin_people_path, alert: "Cannot destroy a person with appointments"
    end
  end

private

  def load_person
    @person = Person.friendly.find(params[:id])
  end

  def person_params
    params.require(:person).permit(
      :title,
      :forename,
      :surname,
      :letters,
      :image,
      :biography,
      :privy_counsellor,
    )
  end

  def enforce_permissions!
    enforce_permission!(:edit, @person)
  end
end


text:
package org.noob.thinking.chapter11.foreach;

import java.util.Arrays;

public class ArrayIsNotIterable {

	static <T> void test(Iterable<T> ib) {
		for (T t : ib) {
			System.out.print(t+" ");
		}
	}

	public static void main(String[] args) {

		test(Arrays.asList(1,2,3));
		String[] array={"A","B","C"};
		test(Arrays.asList(array));

	}

}


text:
package org.solr.contrib.plugin.response;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.solr.SolrJettyTestBase;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.JettySolrRunner;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;

@SolrTestCaseJ4.SuppressObjectReleaseTracker(bugUrl = "Unclear SolrTestCase behavior.")
@SolrTestCaseJ4.SuppressSSL
public class SimpleExplainJsonResponseWriterTest extends SolrJettyTestBase {
  private static JettySolrRunner jettySolrRunner;
  private SolrClient solrClient;

  @BeforeClass
  public static void beforeTest() throws Exception {
    URL url = SimpleExplainJsonResponseWriterTest.class.getResource("/solr");
    String path = Paths.get(url.toURI()).normalize().toString();
    jettySolrRunner = createJetty(
        path, "solrconfig.xml",
        "conf/schema.xml",
        null, true, null);
  }

  @Before
  public void initTest() {
    solrClient = createNewSolrClient();
  }

  @Test
  public void testResponseWriter()
      throws IOException, SolrServerException {
    setupTestBase();
    retrieveHttpResult("fox");
  }

  private void setupTestBase() throws IOException, SolrServerException {
    writeSolrInputDocumentToIndex("1", "Quick Fox", "The quick brown fox jumped the fence.");
    writeSolrInputDocumentToIndex("2", "Slow Bear", "The slow bear went to grab some fish.");
    writeSolrInputDocumentToIndex("3", "Early bird", "A early bird catches everything before the late one.");
    writeSolrInputDocumentToIndex("4", "Early quick eagle", "The Old English The Battle of Maldon refers to the Earn or Sea Eagle as a carrion eater in 10th century Essex.");
    writeSolrInputDocumentToIndex("5", "Hungry rabbit", "They came across a bunny rabbit who looked hungry.");
  }

  private void writeSolrInputDocumentToIndex(final String id, final String title, final String description) throws IOException, SolrServerException {
    SolrInputDocument inputDocument = new SolrInputDocument();
    inputDocument.addField("id", id);
    inputDocument.addField("title", title);
    inputDocument.addField("description", description);
    solrClient.add(inputDocument);
  }

  private String retrieveHttpResult(String query)
      throws IOException {
    StringBuilder responseContent = new StringBuilder();

    List<NameValuePair> params = new LinkedList<>();
    params.add(new BasicNameValuePair("q", query));
    params.add(new BasicNameValuePair("debugQuery", "true"));
    params.add(new BasicNameValuePair("wt", "simpleExplainJson"));
    String paramString = URLEncodedUtils.format(params, "utf-8");

    HttpClient client = HttpClientBuilder.create().build();

    HttpGet request = new HttpGet(jettySolrRunner.getBaseUrl() + "/collection1/select?" + paramString);
    HttpResponse response = client.execute(request);

    BufferedReader rd = new BufferedReader
        (new InputStreamReader(response.getEntity().getContent()));

    String line;
    while ((line = rd.readLine()) != null) {
      responseContent.append(line);
    }
    return responseContent.toString();
  }
}


text:
#ifndef _PVM_COMMID_H_
#define _PVM_COMMID_H_

void _InitCommID(void);
int _GetDynamicCommID(void);
int _SetDynamicCommID(int);

#endif


text:
title: Getting started with the Engine API
---

To try out the Docker Engine API in development, [you first need to install Docker](https://docs.docker.com/engine/installation/).

Next, you need to install an SDK for the language you are using. There are official ones available for Python and Go, and a number of community maintained libraries for other languages. [Head to the SDKs page to find and install them.](sdks.md)

## Running a container

The most basic thing you can do with Docker is running a container. On the command line, you would use the `docker run` command, but this is just as easy to do from your own apps too.

This is the equivalent of doing `docker run alpine echo hello world`:

Python

Go

curl

{% highlight python %}
import docker
client = docker.from_env()
print client.containers.run("alpine", ["echo", "hello", "world"])
{% endhighlight %}

{% highlight go %}
package main

import (
	"io"
	"os"

	"github.com/docker/engine-api/client"
	"github.com/docker/engine-api/types"
	"github.com/docker/engine-api/types/container"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	cli, err := client.NewEnvClient()
	if err != nil {
		panic(err)
	}

	_, err = cli.ImagePull(ctx, "alpine", types.ImagePullOptions{})
	if err != nil {
		panic(err)
	}

	resp, err := cli.ContainerCreate(ctx, &container.Config{
		Image: "alpine",
		Cmd:   []string{"echo", "hello world"},
	}, nil, nil, "")
	if err != nil {
		panic(err)
	}

	if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
		panic(err)
	}

	if _, err = cli.ContainerWait(ctx, resp.ID); err != nil {
		panic(err)
	}

	out, err := cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true})
	if err != nil {
		panic(err)
	}

	io.Copy(os.Stdout, out)
}
{% endhighlight %}

{% highlight bash %}
$ curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" \
  -d '{"Image": "alpine", "Cmd": ["echo", "hello world"]}' \
  -X POST http:/v1.24/containers/create
{"Id":"1c6594faf5","Warnings":null}

$ curl --unix-socket /var/run/docker.sock -X POST http:/v1.24/containers/1c6594faf5/start

$ curl --unix-socket /var/run/docker.sock -X POST http:/v1.24/containers/1c6594faf5/wait
{"StatusCode":0}

$ curl --unix-socket /var/run/docker.sock "http:/v1.24/containers/1c6594faf5/logs?stdout=1"
hello world
{% endhighlight %}

You can also run containers in the background, the equivalent of `docker run -d bfirsh/reticulate-splines`:

Python

Go

curl

{% highlight python %}
import docker
client = docker.from_env()
container = client.containers.run("bfirsh/reticulate-splines", detach=True)
print container.id
{% endhighlight %}

{% highlight go %}
package main

import (
	"fmt"
	"io"
	"os"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/client"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	cli, err := client.NewEnvClient()
	if err != nil {
		panic(err)
	}

	imageName := "bfirsh/reticulate-splines"

	out, err := cli.ImagePull(ctx, imageName, types.ImagePullOptions{})
	if err != nil {
		panic(err)
	}
	io.Copy(os.Stdout, out)

	resp, err := cli.ContainerCreate(ctx, &container.Config{
		Image: imageName,
	}, nil, nil, "")
	if err != nil {
		panic(err)
	}

	if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
		panic(err)
	}

	fmt.Println(resp.ID)
}
{% endhighlight %}

{% highlight bash %}
$ curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" \
  -d '{"Image": "bfirsh/reticulate-splines"}' \
  -X POST http:/v1.24/containers/create
{"Id":"1c6594faf5","Warnings":null}

$ curl --unix-socket /var/run/docker.sock -X POST http:/v1.24/containers/1c6594faf5/start
{% endhighlight %}

## Listing and managing containers

Like `docker ps`, we can use the API to list containers that are running:

Python

Go

curl

{% highlight python %}
import docker
client = docker.from_env()
for container in client.containers.list():
  print container.id
{% endhighlight %}

{% highlight go %}
package main

import (
	"context"
	"fmt"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
)

func main() {
	cli, err := client.NewEnvClient()
	if err != nil {
		panic(err)
	}

	containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
	if err != nil {
		panic(err)
	}

	for _, container := range containers {
		fmt.Println(container.ID)
	}
}
{% endhighlight %}

{% highlight bash %}
$ curl --unix-socket /var/run/docker.sock http:/v1.24/containers/json
[{
  "Id":"ae63e8b89a26f01f6b4b2c9a7817c31a1b6196acf560f66586fbc8809ffcd772",
  "Names":["/tender_wing"],
  "Image":"bfirsh/reticulate-splines",
  ...
}]

{% endhighlight %}

Now we know what containers exist, we can perform operations on them. For example, we can stop all running containers:

Python

Go

curl

{% highlight python %}
import docker
client = docker.from_env()
for container in client.containers.list():
  container.stop()
{% endhighlight %}

{% highlight go %}
package main

import (
	"context"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
)

func main() {
	ctx := context.Background()
	cli, err := client.NewEnvClient()
	if err != nil {
		panic(err)
	}

	containers, err := cli.ContainerList(ctx, types.ContainerListOptions{})
	if err != nil {
		panic(err)
	}

	for _, container := range containers {
		if err := cli.ContainerStop(ctx, container.ID, nil); err != nil {
			panic(err)
		}
	}
}
{% endhighlight %}

{% highlight bash %}
$ curl --unix-socket /var/run/docker.sock http:/v1.24/containers/json
[{
  "Id":"ae63e8b89a26f01f6b4b2c9a7817c31a1b6196acf560f66586fbc8809ffcd772",
  "Names":["/tender_wing"],
  "Image":"bfirsh/reticulate-splines",
  ...
}]

$ curl --unix-socket /var/run/docker.sock \
  -X POST http:/v1.24/containers/ae63e8b89a26/stop

{% endhighlight %}

We can also perform actions on individual containers. For example, to print the logs of a container given its ID:

Python

Go

curl

{% highlight python %}
import docker
client = docker.from_env()
container = client.containers.get('f1064a8a4c82')
print container.logs()
{% endhighlight %}

{% highlight go %}
package main

import (
	"context"
	"io"
	"os"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
)

func main() {
	ctx := context.Background()
	cli, err := client.NewEnvClient()
	if err != nil {
		panic(err)
	}

	options := types.ContainerLogsOptions{ShowStdout: true}
	out, err := cli.ContainerLogs(ctx, "f1064a8a4c82", options)
	if err != nil {
		panic(err)
	}

	io.Copy(os.Stdout, out)
}
{% endhighlight %}

{% highlight bash %}
$ curl --unix-socket /var/run/docker.sock "http:/v1.24/containers/ca5f55cdb/logs?stdout=1"
Reticulating spline 1...
Reticulating spline 2...
Reticulating spline 3...
Reticulating spline 4...
Reticulating spline 5...
{% endhighlight %}

## Managing images

Images are the basis of containers, and can be managed in a similar way. You can list the images on your Engine, similar to `docker images`:

Python

Go

curl

{% highlight python %}
import docker
client = docker.from_env()
for image in client.images.list():
  print image.id
{% endhighlight %}

{% highlight go %}
package main

import (
	"context"
	"fmt"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
)

func main() {
	cli, err := client.NewEnvClient()
	if err != nil {
		panic(err)
	}

	images, err := cli.ImageList(context.Background(), types.ImageListOptions{})
	if err != nil {
		panic(err)
	}

	for _, image := range images {
		fmt.Println(image.ID)
	}
}
{% endhighlight %}

{% highlight bash %}
$ curl --unix-socket /var/run/docker.sock http:/v1.24/images/json
[{
  "Id":"sha256:31d9a31e1dd803470c5a151b8919ef1988ac3efd44281ac59d43ad623f275dcd",
  "ParentId":"sha256:ee4603260daafe1a8c2f3b78fd760922918ab2441cbb2853ed5c439e59c52f96",
  ...
}]
{% endhighlight %}

You can pull images, like `docker pull`:

Python

Go

curl

{% highlight python %}
import docker
client = docker.from_env()
image = client.images.pull("alpine")
print image.id
{% endhighlight %}

{% highlight go %}
package main

import (
	"io"
	"os"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	cli, err := client.NewEnvClient()
	if err != nil {
		panic(err)
	}

	out, err := cli.ImagePull(ctx, "alpine", types.ImagePullOptions{})
	if err != nil {
		panic(err)
	}

	io.Copy(os.Stdout, out)
}
{% endhighlight %}

{% highlight bash %}
$ curl --unix-socket /var/run/docker.sock \
  -X POST "http:/v1.24/images/create?fromImage=alpine"
{"status":"Pulling from library/alpine","id":"3.1"}
{"status":"Pulling fs layer","progressDetail":{},"id":"8f13703509f7"}
{"status":"Downloading","progressDetail":{"current":32768,"total":2244027},"progress":"[\u003e                                                  ] 32.77 kB/2.244 MB","id":"8f13703509f7"}
...
{% endhighlight %}

And commit containers to create images from their contents:

Python

Go

curl

{% highlight python %}
import docker
client = docker.from_env()
container = client.run("alpine", ["touch", "/helloworld"], detached=True)
container.wait()
image = container.commit("helloworld")
print image.id
{% endhighlight %}

{% highlight go %}
package main

import (
	"fmt"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/client"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	cli, err := client.NewEnvClient()
	if err != nil {
		panic(err)
	}

	createResp, err := cli.ContainerCreate(ctx, &container.Config{
		Image: "alpine",
		Cmd:   []string{"touch", "/helloworld"},
	}, nil, nil, "")
	if err != nil {
		panic(err)
	}

	if err := cli.ContainerStart(ctx, createResp.ID, types.ContainerStartOptions{}); err != nil {
		panic(err)
	}

	if _, err = cli.ContainerWait(ctx, createResp.ID); err != nil {
		panic(err)
	}

	commitResp, err := cli.ContainerCommit(ctx, createResp.ID, types.ContainerCommitOptions{Reference: "helloworld"})
	if err != nil {
		panic(err)
	}

	fmt.Println(commitResp.ID)
}
{% endhighlight %}

{% highlight bash %}
$ docker run -d alpine touch /helloworld
0888269a9d584f0fa8fc96b3c0d8d57969ceea3a64acf47cd34eebb4744dbc52
$ curl --unix-socket /var/run/docker.sock\
  -X POST "http:/v1.24/commit?container=0888269a9d&repo=helloworld"
{"Id":"sha256:6c86a5cd4b87f2771648ce619e319f3e508394b5bfc2cdbd2d60f59d52acda6c"}
{% endhighlight %}

## What next?

 - [Full documentation for the Python SDK.](https://docker-py.readthedocs.io)
 - [Full documentation for the Go SDK.](https://godoc.org/github.com/docker/docker/client)
 - [Full documentation for the HTTP API.](/engine/api/v1.25/)


text:
set(CMAKE_C_COMPILER "/usr/bin/cc")
set(CMAKE_C_COMPILER_ARG1 "")
set(CMAKE_C_COMPILER_ID "AppleClang")
set(CMAKE_C_COMPILER_VERSION "6.0.0.6000056")
set(CMAKE_C_PLATFORM_ID "Darwin")
set(CMAKE_C_SIMULATE_ID "")
set(CMAKE_C_SIMULATE_VERSION "")

set(CMAKE_AR "/usr/bin/ar")
set(CMAKE_RANLIB "/usr/bin/ranlib")
set(CMAKE_LINKER "/usr/bin/ld")
set(CMAKE_COMPILER_IS_GNUCC )
set(CMAKE_C_COMPILER_LOADED 1)
set(CMAKE_C_COMPILER_WORKS TRUE)
set(CMAKE_C_ABI_COMPILED TRUE)
set(CMAKE_COMPILER_IS_MINGW )
set(CMAKE_COMPILER_IS_CYGWIN )
if(CMAKE_COMPILER_IS_CYGWIN)
  set(CYGWIN 1)
  set(UNIX 1)
endif()

set(CMAKE_C_COMPILER_ENV_VAR "CC")

if(CMAKE_COMPILER_IS_MINGW)
  set(MINGW 1)
endif()
set(CMAKE_C_COMPILER_ID_RUN 1)
set(CMAKE_C_SOURCE_FILE_EXTENSIONS c)
set(CMAKE_C_IGNORE_EXTENSIONS h;H;o;O;obj;OBJ;def;DEF;rc;RC)
set(CMAKE_C_LINKER_PREFERENCE 10)

# Save compiler ABI information.
set(CMAKE_C_SIZEOF_DATA_PTR "8")
set(CMAKE_C_COMPILER_ABI "")
set(CMAKE_C_LIBRARY_ARCHITECTURE "")

if(CMAKE_C_SIZEOF_DATA_PTR)
  set(CMAKE_SIZEOF_VOID_P "${CMAKE_C_SIZEOF_DATA_PTR}")
endif()

if(CMAKE_C_COMPILER_ABI)
  set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_C_COMPILER_ABI}")
endif()

if(CMAKE_C_LIBRARY_ARCHITECTURE)
  set(CMAKE_LIBRARY_ARCHITECTURE "")
endif()

set(CMAKE_C_IMPLICIT_LINK_LIBRARIES "/Library/Developer/CommandLineTools/usr/lib/clang/6.0/lib/darwin/libclang_rt.osx.a")
set(CMAKE_C_IMPLICIT_LINK_DIRECTORIES "/usr/lib;/usr/local/lib")
set(CMAKE_C_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "/Library/Frameworks;/System/Library/Frameworks")


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

	<mvc:annotation-driven enableMatrixVariables="false">
		<mvc:argument-resolvers>
			<bean class="org.springframework.data.web.PageableArgumentResolver">
			</bean>
		</mvc:argument-resolvers>
	</mvc:annotation-driven>

	<context:component-scan base-package="com.izerui.*" />

	<mvc:resources mapping="/resources/**"
		location="/resources/,classpath:META-INF/resources/" cache-period="#{60 * 60}" />

	<mvc:default-servlet-handler />

	<!-- 注册多国语言拦截器,只要url参数中出现 locale=en_US ... 就会设置为参数值表示的语言环境 -->
	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/**" />
			<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
				<property name="paramName" value="language"></property>
			</bean>
		</mvc:interceptor>
	</mvc:interceptors>

	<bean id="localeResolver"
		class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
		<property name="defaultLocale" value="en_US" />
	</bean>

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
		<property name="order" value="2" />
	</bean>

	<bean
		class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<property name="order" value="1" />
		<property name="exceptionMappings">
			<util:map>
				<entry key="ResourceNotFoundException" value="notFoundError" />
			</util:map>
		</property>
		<property name="statusCodes">
			<util:map>
				<entry key="notFoundError" value="404" />
			</util:map>
		</property>
		<property name="defaultStatusCode" value="500" />
		<property name="defaultErrorView" value="systemError" />
		<property name="warnLogCategory"
			value="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" />
	</bean>

	<import resource="classpath:META-INF/spring/spring-tiles.xml"/>
</beans>


text:
/**
 * @param {Object} opt
 * @param {BoltAnimate[]} opt.animEls
 * @param {string} [opt.stage='IN']
 * @param {boolean} [opt.debug=false]
 *
 * @return {Promise<{ success: boolean, animEl: BoltAnimate }[]>}
 */
async function triggerAnimOnEls({ animEls, stage, debug = false }) {
  let eventName = '';
  switch (stage) {
    case 'IN':
      eventName = 'bolt-animate:end:in';
      break;
    case 'OUT':
      eventName = 'bolt-animate:end:out';
      break;
  }
  if (!stage) {
    throw new Error(`Incorrect stage name passed in ${stage}`);
  }

  return Promise.all(
    animEls.map(
      animEl =>
        new Promise((resolve, reject) => {
          let timeoutId;
          let triggered = false;
          let duration = 0;

          animEl.addEventListener(
            eventName,
            () => {
              if (timeoutId) clearTimeout(timeoutId);
              resolve({
                success: true,
                animEl,
              });
            },
            {
              once: true,
            },
          );

          switch (stage) {
            case 'IN':
              triggered = animEl.triggerAnimIn();
              duration = animEl.inDuration;
              break;
            case 'OUT':
              triggered = animEl.triggerAnimOut();
              duration = animEl.outDuration;
              break;
          }

          if (debug) {
            console.debug(`${eventName}`, animEl);
          }

          if (typeof duration === 'number') {
            timeoutId = setTimeout(() => {
              console.warn(
                `animation taking too long for stage "${stage}", cancelling and moving on to next one.`,
                animEl,
              );
              resolve({
                success: false,
                animEl,
              });
            }, duration + 100);
          } else {
            console.warn(
              `Uh oh, animation duration retrieved was not a number: ${duration}`,
              animEl,
            );
          }

          if (!triggered) {
            reject(
              new Error(
                `Attempted to trigger animation when there was no animation`,
              ),
            );
          }
        }),
    ),
  )
    .then(results => {
      return results;
    })
    .catch(console.log.bind(console));
}

/**
 * @param {Object} opt
 * @param {BoltAnimate[] | NodeListOf<BoltAnimate>} opt.animEls
 * @param {string} [opt.stage='IN']
 * @param {boolean=} [opt.debug=false]
 */
export async function triggerAnims({ animEls, stage = 'IN', debug = false }) {
  let orderProp;
  let hasAnimProp;
  let eventName;
  switch (stage) {
    case 'IN':
      eventName = 'bolt-animate:end:in';
      orderProp = 'inOrder';
      hasAnimProp = 'hasAnimIn';
      break;
    case 'OUT':
      eventName = 'bolt-animate:end:out';
      orderProp = 'outOrder';
      hasAnimProp = 'hasAnimOut';
      break;
  }
  if (!orderProp) throw new Error(`Incorrect stage name passed: ${stage}`);

  // convert NodeList over to array in case `querySelectorAll` was used
  animEls = Array.isArray(animEls)
    ? animEls
    : Array.prototype.slice.call(animEls);

  const orders = new Set();
  animEls.forEach(animEl => {
    const order = animEl[orderProp] || 1;
    orders.add(order);
  });

  const animOrders = [...orders].sort((a, b) => a - b);

  for (const order of animOrders) {
    const animElsToTrigger = animEls
      .filter(a => a[hasAnimProp])
      .filter(a => a[orderProp] === order);
    if (debug) {
      console.debug(`${eventName}: order:${order}`, animElsToTrigger);
    }
    // eslint-disable-next-line no-await-in-loop
    await triggerAnimOnEls({
      animEls: animElsToTrigger,
      stage,
      debug,
    });
  }

  return true;
}

/**
 * Trigger `<bolt-animate>` animations found within Element
 * @param {Element} el
 * @param {string} [stage='IN'] must be either 'IN' or 'OUT'
 * @return {Promise<boolean>}
 */
export async function triggerAnimsInEl(el, stage = 'IN') {
  if (!el.querySelectorAll) {
    console.error(el);
    throw new Error(
      `When running "triggerAnimsInEl", the passed element does not have "querySelectorAll" method.`,
    );
  }
  const animEls = Array.prototype.slice.call(
    el.querySelectorAll('bolt-animate'),
  );
  if (animEls.length === 0) {
    return false;
  }
  return triggerAnims({ animEls, stage });
}


text:
'use strict';

/* https://github.com/angular/protractor/blob/master/docs/toc.md */

describe('my app', function() {

  it('should automatically redirect to the application when location hash/fragment is empty', function() {
    browser.get('index.html');
    expect(browser.getLocationAbsUrl()).toMatch("");
  });

  describe('Premiership outright winner odds', function() {

    beforeEach(function() {
      browser.get('index.html');
    });

    it('should have; ID, team, Betfair', function() {
        expect(by.model('team.id')).toMatch(/id/);
        expect(by.model('team.team')).toMatch(/team/);
        expect(by.model('team.betfair')).toMatch(/betfair/);
    });

    it('should count all the teams', function(){
      var list = expect(element.all(by.repeater('team in teams')).count()).toEqual(20);
    });

    it ('should have all the odds from Betfair', function(){
      var odds = element.all(by.repeater('team.betfair'));
    });

    it('should search by team name', function(){
      element(by.model('searchTeam')).sendKeys('test');
      expect(element.all(by.repeater('team in teams')).count()).toEqual(0);
    });

    it('should sort by team name by alphabetical order' ,function(){
    var sort = element.all(by.css('.teamHeading')).first().click();
      setTimeout(function(){
        expect(true).toBe(true);
      },500);
    var row = element.all(by.repeater('team in teams')).first();
    var cells = row.all(by.tagName('td'));

    var cellTexts = cells.map(function (elm) {
        return elm.getText();
    });
    expect(cellTexts).toEqual(["008", "WestHam", "120", "101", "251"]);
    });
  });

});