text:
// SampSharp
// Copyright 2017 Tim Potze
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using SampSharp.GameMode.Tools;
using SampSharp.GameMode.World;

namespace SampSharp.GameMode.Controllers
{
    /// <summary>
    ///     A controller processing all player actions.
    /// </summary>
    [Controller]
    public class BasePlayerController : Disposable, IEventListener, ITypeProvider
    {
        /// <summary>
        ///     Registers the events this PlayerController wants to listen to.
        /// </summary>
        /// <param name="gameMode">The running GameMode.</param>
        public virtual void RegisterEvents(BaseMode gameMode)
        {
            //Register all player events
            gameMode.PlayerConnected += (sender, args) => (sender as BasePlayer)?.OnConnected(args);
            gameMode.PlayerDisconnected += (sender, args) => (sender as BasePlayer)?.OnDisconnected(args);
            gameMode.PlayerCleanup += (sender, args) => (sender as BasePlayer)?.OnCleanup(args);
            gameMode.PlayerSpawned += (sender, args) => (sender as BasePlayer)?.OnSpawned(args);
            gameMode.PlayerDied += (sender, args) => (sender as BasePlayer)?.OnDeath(args);
            gameMode.PlayerText += (sender, args) => (sender as BasePlayer)?.OnText(args);
            gameMode.PlayerCommandText += (sender, args) => (sender as BasePlayer)?.OnCommandText(args);
            gameMode.PlayerRequestClass += (sender, args) => (sender as BasePlayer)?.OnRequestClass(args);
            gameMode.PlayerEnterVehicle += (sender, args) => (sender as BasePlayer)?.OnEnterVehicle(args);
            gameMode.PlayerExitVehicle += (sender, args) => (sender as BasePlayer)?.OnExitVehicle(args);
            gameMode.PlayerStateChanged += (sender, args) => (sender as BasePlayer)?.OnStateChanged(args);
            gameMode.PlayerEnterCheckpoint += (sender, args) => (sender as BasePlayer)?.OnEnterCheckpoint(args);
            gameMode.PlayerLeaveCheckpoint += (sender, args) => (sender as BasePlayer)?.OnLeaveCheckpoint(args);
            gameMode.PlayerEnterRaceCheckpoint +=
                (sender, args) => (sender as BasePlayer)?.OnEnterRaceCheckpoint(args);
            gameMode.PlayerLeaveRaceCheckpoint +=
                (sender, args) => (sender as BasePlayer)?.OnLeaveRaceCheckpoint(args);
            gameMode.PlayerRequestSpawn += (sender, args) => (sender as BasePlayer)?.OnRequestSpawn(args);
            gameMode.PlayerEnterExitModShop += (sender, args) => (sender as BasePlayer)?.OnEnterExitModShop(args);
            gameMode.PlayerSelectedMenuRow += (sender, args) => (sender as BasePlayer)?.OnSelectedMenuRow(args);
            gameMode.PlayerExitedMenu += (sender, args) => (sender as BasePlayer)?.OnExitedMenu(args);
            gameMode.PlayerInteriorChanged += (sender, args) => (sender as BasePlayer)?.OnInteriorChanged(args);
            gameMode.PlayerKeyStateChanged += (sender, args) => (sender as BasePlayer)?.OnKeyStateChanged(args);
            gameMode.PlayerUpdate += (sender, args) => (sender as BasePlayer)?.OnUpdate(args);
            gameMode.PlayerStreamIn += (sender, args) => (sender as BasePlayer)?.OnStreamIn(args);
            gameMode.PlayerStreamOut += (sender, args) => (sender as BasePlayer)?.OnStreamOut(args);
            gameMode.DialogResponse += (sender, args) => (sender as BasePlayer)?.OnDialogResponse(args);
            gameMode.PlayerTakeDamage += (sender, args) => (sender as BasePlayer)?.OnTakeDamage(args);
            gameMode.PlayerGiveDamage += (sender, args) => (sender as BasePlayer)?.OnGiveDamage(args);
            gameMode.PlayerClickMap += (sender, args) => (sender as BasePlayer)?.OnClickMap(args);
            gameMode.PlayerClickTextDraw += (sender, args) =>
            {
                if (args.TextDraw == null)
                    (sender as BasePlayer)?.OnCancelClickTextDraw(args);
                else
                    (sender as BasePlayer)?.OnClickTextDraw(args);
            };
            gameMode.PlayerClickPlayerTextDraw +=
                (sender, args) => (sender as BasePlayer)?.OnClickPlayerTextDraw(args);
            gameMode.PlayerClickPlayer += (sender, args) => (sender as BasePlayer)?.OnClickPlayer(args);
            gameMode.PlayerEditGlobalObject += (sender, args) => (sender as BasePlayer)?.OnEditGlobalObject(args);
            gameMode.PlayerEditPlayerObject += (sender, args) => (sender as BasePlayer)?.OnEditPlayerObject(args);
            gameMode.PlayerEditAttachedObject +=
                (sender, args) => (sender as BasePlayer)?.OnEditAttachedObject(args);
            gameMode.PlayerSelectGlobalObject +=
                (sender, args) => (sender as BasePlayer)?.OnSelectGlobalObject(args);
            gameMode.PlayerSelectPlayerObject +=
                (sender, args) => (sender as BasePlayer)?.OnSelectPlayerObject(args);
            gameMode.PlayerWeaponShot += (sender, args) => (sender as BasePlayer)?.OnWeaponShot(args);
        }

        /// <summary>
        ///     Registers types this PlayerController requires the system to use.
        /// </summary>
        public virtual void RegisterTypes()
        {
            BasePlayer.Register<BasePlayer>();
        }

        /// <summary>
        ///     Performs tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <param name="disposing">Whether managed resources should be disposed.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                foreach (var player in BasePlayer.All)
                {
                    player.Dispose();
                }
            }
        }
    }
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

/*

    Programmation d'une séquence simple de processus.
    Un père crée un fils, et visualisation du résultat
*/

int main(int argc, char **argv)
{
    // création d'un procéssus fils
    pid_t pid = fork();
    if(!pid) // si le pid != alors le fils entre dans ce bloque
    {
        sleep(1);
        printf("Je suis le fils mon pid est %i, mon père est %i.\n", getpid(), getppid());
    }else{
        //sleep(1);
        printf("Je suis le père mon pid est %i, mon fils est %i.\n", getpid(), pid);
    }

    return EXIT_SUCCESS;
}

redpajama_set_name: RedPajamaGithub


text:
//  *************************************************************
// <copyright file="DoubleRingTest.cs" company="None">
//     Copyright (c) 2014 andy. All rights reserved.
// </copyright>
// <license>MIT Licence</license>
// <author>andy</author>
// <email>andy.augustin@t-online.de</email>
// *************************************************************
using GenericMath.Base.Contracts;

namespace GenericMath.Base.Tests
{
	using System;

	using NUnit.Framework;

	/// <summary>
	/// Double ring test.
	/// </summary>
	[TestFixture]
	public class DoubleRingTest : TemplateRingTest<Double>
	{
		#region fields

		private IRing<Double> _ring;

		#endregion

		#region properties

		#region implemented abstract members of TemplateRingTest

		/// <summary>
		/// Gets the ring.
		/// </summary>
		/// <value>The ring.</value>
		protected override IRing<Double> Ring
		{
			get
			{
				return this._ring ?? (this._ring = new DoubleRing ());
			}
		}

		#endregion

		#endregion

		#region implemented abstract members of TemplateRingTest

		/// <summary>
		/// Tests the multiplication.
		/// </summary>
		/// <param name="leftInput">Left input.</param>
		/// <param name="rightInput">Right input.</param>
		/// <param name="expected">Expected solution.</param>
		[Test]
		[Category ("RingTest")]
		[TestCase (3.5, 5.5, 19.25)]
		[TestCase (4.0, -10.0, -40.0)]
		public override void TestMultiplication (
			Double leftInput,
			Double rightInput,
			Double expected)
		{
			this.TemplateTestMultiplication (leftInput, rightInput, expected);
		}

		#endregion
	}
}


text:
Build Better APIs, Faster than Ever

[![NPM](https://nodei.co/npm/feathers.png?downloads=true&stars=true)](https://nodei.co/npm/feathers/)

[![Build Status](https://travis-ci.org/feathersjs/feathers.png?branch=master)](https://travis-ci.org/feathersjs/feathers)
[![Code Climate](https://codeclimate.com/github/feathersjs/feathers.png)](https://codeclimate.com/github/feathersjs/feathers)
[![Join the chat at https://gitter.im/feathersjs/feathers](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/feathersjs/feathers?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Feathers is a real-time, micro-service web framework for NodeJS that gives you control over your data via RESTful resources, sockets and flexible plug-ins.

## Getting started

Visit the website at [feathersjs.com](http://feathersjs.com) to read the [Getting started guide](http://feathersjs.com/quick-start/) or learn how to build real-time applications with jQuery, Angular, React, CanJS, iOS, Android - you name it - and Feathers as the backend [in our guides](http://feathersjs.com/learn/).

## A MongoDB REST and real-time API

Want to see it in action? Here is a full REST and real-time todo API that uses MongoDB:

```js
// app.js
var feathers = require('feathers');
var mongodb = require('feathers-mongodb');
var bodyParser = require('body-parser');

var app = feathers();
var todoService = mongodb({
  db: 'feathers-demo',
  collection: 'todos'
});

app.configure(feathers.rest())
  .configure(feathers.socketio())
  .use(bodyParser.json())
  .use('/todos', todoService)
  .use('/', feathers.static(__dirname))
  .listen(3000);
```

Then run

```
npm install feathers feathers-mongodb body-parser
node app
```

and go to [http://localhost:3000/todos](http://localhost:3000/todos). That's all the code you need to have a full real-time CRUD API.

Don't want to use MongoDB? Feathers has plugins for [many other databases](http://feathersjs.com/learn/) and you can easily [write your own adapters](http://feathersjs.com/quick-start/).

## License

[MIT](LICENSE)

## Authors

- [David Luecke](https://github.com/daffl)
- [Eric Kryski](http://erickryski.com)


text:
package com.b12kab.tmdblibrary.services;

import com.b12kab.tmdblibrary.entities.AppendToResponse;
import com.b12kab.tmdblibrary.entities.Company;
import com.b12kab.tmdblibrary.entities.MovieResultsPage;

import java.util.Map;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;

public interface CompaniesService {
    /**
     * Get the basic company information for a specific A Company TMDb id.
     *
     * @param companyId A Company TMDb id.
     */
    @GET("company/{company_id}")
    Call<Company> summary(
            @Path("company_id") int companyId
    );

    /**
     * Get the basic company information for a specific A Company TMDb id.
     *
     * @param companyId        A Company TMDb id.
     * @param appendToResponse Optional. extra requests to append to the result. Accepted Value(s): movies
     */
    @GET("company/{company_id}")
    Call<Company> summary(
            @Path("company_id") int companyId,
            @Query("append_to_response") AppendToResponse appendToResponse
    );

    /**
     * Get the basic company information for a specific A Company TMDb id.
     *
     * @param companyId        A Company TMDb id.
     * @param appendToResponse Optional. extra requests to append to the result. Accepted Value(s): movies
     * @param options          Optional. parameters for the appended extra results.
     */
    @GET("company/{company_id}")
    Call<Company> summary(
            @Path("company_id") int companyId,
            @Query("append_to_response") AppendToResponse appendToResponse,
            @QueryMap Map<String, String> options
    );

    /**
     * Get the movies for a specific A Company TMDb id.
     *

     * Is highly recommend using {@link DiscoverService#discoverMovie discoverMovie}
     * instead of this method as it is much more flexible.
     *
     * @param companyId A Company TMDb id.
     */
    @GET("company/{company_id}/movies")
    Call<MovieResultsPage> movies(
            @Path("company_id") int companyId
    );
}


text:
package org.helianto.seed;

import java.util.List;

import org.helianto.core.config.HeliantoServiceConfig;
import org.helianto.core.domain.Entity;
import org.helianto.core.domain.Signup;
import org.helianto.core.sender.UserConfirmationSender;
import org.helianto.install.service.EntityInstallStrategy;
import org.helianto.security.controller.VerifyController;
import org.helianto.sendgrid.config.SendGridConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.test.context.ContextConfiguration;

@Configuration
@ContextConfiguration(classes={HeliantoServiceConfig.class
		, SendGridConfig.class
		, OAuth2ClientConfig.class
		, MultiHttpSecurityConfig.class})
	@EnableJpaRepositories(
	    basePackages={"org.helianto.*.repository"})
@PropertySource("classpath:/META-INF/app.properties")
public class TestConfig extends AbstractRootContextConfig {

	@Bean
	public VerifyControllerStub verifyControllerStub() {
		return new VerifyControllerStub();
	}

	/**
	 * Test stub.
	 *
	 * @author mauriciofernandesdecastro
	 */
	public class VerifyControllerStub extends VerifyController {

		@Override
		protected List<Entity> generateEntityPrototypes(Signup signup) {
			// TODO Auto-generated method stub
			return null;
		}

	}

    @Bean
	public TextEncryptor textEncryptor() {
		return Encryptors.queryableText(env.getProperty("security.encryptPassword", "password"), env.getProperty("security.encryptSalt", "00"));
	}

    @Bean
	public UserConfirmationSender userConfirmationSender(Environment env) {
		return new UserConfirmationSender(env);
	}

}


text:
package net.ontopia.topicmaps.webed.impl.actions;

import java.io.IOException;
import java.util.Collections;
import net.ontopia.infoset.core.LocatorIF;
import net.ontopia.topicmaps.core.TopicIF;
import net.ontopia.topicmaps.webed.core.ActionIF;
import net.ontopia.topicmaps.webed.core.ActionParametersIF;
import net.ontopia.topicmaps.webed.core.ActionResponseIF;
import net.ontopia.topicmaps.webed.core.ActionRuntimeException;
import net.ontopia.topicmaps.webed.impl.actions.tmobject.SetSourceLocator;

public class TestSetSourceLocator extends AbstractWebedTestCase {

  public TestSetSourceLocator(String name) {
    super(name);
  }

  /*
    1. Good, Normal use
    2. Good , No previous SL
    3. Bad parameters
    4. Bad url
  */

  public void testNormalOperation() throws IOException {
    ActionIF action = new SetSourceLocator();
    TopicIF topic = getTopicById(tm, "super");
    LocatorIF SL = topic.getItemIdentifiers().iterator().next();

    //build parms
    ActionParametersIF params = makeParameters(makeList(topic, SL), "http://mama.no");
    ActionResponseIF response = makeResponse();
    try{
      action.perform(params, response);
      int newSLNum = topic.getItemIdentifiers().size();
      LocatorIF SLnew = topic.getItemIdentifiers().iterator().next();

      assertFalse("new address not set correctly",
		  !(SLnew.getAddress().equals("http://mama.no/")));
    } catch (ActionRuntimeException e) {
    }
  }

  public void testSetNewSL() throws IOException {
    // setting sourcelocator on topic without predefined SL
    ActionIF action = new SetSourceLocator();
    TopicIF topic = getTopicById(tm, "gamst");

    TopicIF topicDummy = getTopicById(tm, "super");
    LocatorIF SL = topic.getItemIdentifiers().iterator().next();

    //build parms
    ActionParametersIF params = makeParameters(makeList(topic, SL), "http://mama.no");
    ActionResponseIF response = makeResponse();
    try {
      action.perform(params, response);
      int newSLNum = topic.getItemIdentifiers().size();

      LocatorIF SLnew = topic.getItemIdentifiers().iterator().next();
      assertFalse("new address not set correctly",
		  !(SLnew.getAddress().equals("http://mama.no/")));
    } catch (ActionRuntimeException e) {
    }
  }

  public void testNoParams() throws IOException{
    //setting sourcelocator on topic without predefined SL
    ActionIF action = new SetSourceLocator();

    //build parms
    ActionParametersIF params = makeParameters(Collections.EMPTY_LIST, "http://mama.no");
    ActionResponseIF response = makeResponse();
    try{
      action.perform(params, response);
      fail("Empty parameters..");

    }catch (ActionRuntimeException e){
    }
  }

  public void testBadURL() throws IOException{

    ActionIF action = new SetSourceLocator();
    TopicIF topic = getTopicById(tm, "super");
    LocatorIF SL = topic.getItemIdentifiers().iterator().next();

    //build parms
    ActionParametersIF params = makeParameters(makeList(topic, SL), "foobar");
    ActionResponseIF response = makeResponse();
    try{
      action.perform(params, response);
      fail("Bad url given");
    }catch (ActionRuntimeException e){

    }
  }

}


text:
require 'testup/testcase'

module TestUp
module Tests
  # Set of tests triggering different result types.
  class TC_TestPasses < TestUp::TestCase

    def setup
      # ...
    end

    def teardown
      # ...
    end

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

    # Ensure that passing tests doesn't expand the test case.
    def test_pass_only_test_case
      assert(true)
    end # test

  end # class
end
end


text:
Remote Associates Task
======================

The remote associates test is a test of problem solving. You need to think of a word that connects 3 cue words. The test will be administered in 2 parts.

In the first part you will read two sets of three words. You will decide which word from the second set connects the words from the first set.
When you have decided press 1), 2), or 3) to select your answer. You will receive as many problems as you can complete in 1 minute. Try to answer as quickly as possible.

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

** Examples for Part 1 **

Example 1.

** Time / Weigh / Last **

- OUT
- BACK
- BAY

(**Solution**: Time*out* / *Out*weigh / *Out*last)

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

Example 2.

** Mower / Gnome / Fertilizer **

- GREEN
- CROP
- LAWN ?

(**Solution**: *Lawn* mower / *Lawn* gnome / *Lawn* fertilizer)


text:
try:
    import base64
    import hashlib
    import hmac
    import itertools
    import json
    import requests
    import ssl
    import sys
    import time
    import urllib
    import urllib2

    from datetime import datetime, timedelta
    from requests_toolbelt import SSLAdapter
    from urllib2 import HTTPError, URLError
except ImportError, e:
    print "Import error in %s : %s" % (__name__, e)
    import sys
    sys.exit()

# Disable HTTPS verification warnings.
from requests.packages import urllib3
urllib3.disable_warnings()

def logger_debug(logger, message):
    if logger is not None:
        logger.debug(message)

def writeError(msg):
    sys.stderr.write(msg)
    sys.stderr.write("\n")
    sys.stderr.flush()

def login(url, username, password, domain="/", verifysslcert=False):
    """
    Login and obtain a session to be used for subsequent API calls
    Wrong username/password leads to HTTP error code 531
    """
    args = {}

    args["command"] = 'login'
    args["username"] = username
    args["password"] = password
    args["domain"] = domain
    args["response"] = "json"

    sessionkey = ''
    session = requests.Session()
    session.mount('https://', SSLAdapter(ssl.PROTOCOL_TLSv1))

    try:
        resp = session.post(url, params=args, verify=verifysslcert)
    except requests.exceptions.ConnectionError, e:
        writeError("Connection refused by server: %s" % e)
        return None, None

    if resp.status_code == 200:
        sessionkey = resp.json()['loginresponse']['sessionkey']
    elif resp.status_code == 405:
        writeError("Method not allowed, unauthorized access on URL: %s" % url)
        session = None
        sessionkey = None
    elif resp.status_code == 531:
        writeError("Error authenticating at %s using username: %s"
                   ", password: %s, domain: %s" % (url, username, password,
                                                   domain))
        session = None
        sessionkey = None
    else:
        resp.raise_for_status()

    return session, sessionkey

def logout(url, session):
    if not session:
        return
    session.get(url, params={'command': 'logout'})

def make_request_with_password(command, args, logger, url, credentials,
                               verifysslcert=False):
    error = None
    args = args.copy()
    username = credentials['username']
    password = credentials['password']
    domain = credentials['domain']

    if not (username and password):
        error = "Username and password cannot be empty"
        result = None
        return result, error

    tries = 0
    retry = True

    while tries < 2 and retry:
        sessionkey = credentials.get('sessionkey')
        session = credentials.get('session')
        tries += 1

        # obtain a valid session if not supplied
        if not (session and sessionkey):
            session, sessionkey = login(url, username, password, domain,
                                        verifysslcert)
            if not (session and sessionkey):
                return None, 'Authentication failed'
            credentials['session'] = session
            credentials['sessionkey'] = sessionkey

        args['sessionkey'] = sessionkey

        # make the api call
        resp = session.get(url, params=args, verify=verifysslcert)
        result = resp.text
        logger_debug(logger, "Response received: %s" % resp.text)

        if resp.status_code == 200:  # success
            retry = False
            break
        if resp.status_code == 401:  # sessionkey is wrong
            credentials['session'] = None
            credentials['sessionkey'] = None
            continue

        if resp.status_code != 200 and resp.status_code != 401:
            error_message = resp.headers.get('X-Description')
            if not error_message:
                error_message = resp.text
            error = "{0}: {1}".format(resp.status_code, error_message)
            result = None
            retry = False

    return result, error

def make_request(command, args, logger, url, credentials, expires,
                 verifysslcert=False, signatureversion=3):
    result = None
    error = None

    if not url.startswith('http'):
        error = "Server URL should start with 'http' or 'https', " + \
                "please check and fix the url"
        return None, error

    if not args:
        args = {}

    args = args.copy()
    args["command"] = command
    args["response"] = "json"
    signatureversion = int(signatureversion)
    if signatureversion >= 3:
        args["signatureversion"] = signatureversion
        if not expires:
            expires = 600
        expirationtime = datetime.utcnow() + timedelta(seconds=int(expires))
        args["expires"] = expirationtime.strftime('%Y-%m-%dT%H:%M:%S+0000')

    for key in args.keys():
        value = args[key]
        if isinstance(value, unicode):
            value = value.encode("utf-8")
        args[key] = value
        if not key:
            args.pop(key)
        else:
            if key in ['publickey', 'privatekey', 'certificate']:
                args[key] = urllib.quote_plus(str(value))

    # try to use the apikey/secretkey method by default
    # followed by trying to check if we're using integration port
    # finally use the username/password method
    if not credentials['apikey'] and not ("8096" in url):
        try:
            return make_request_with_password(command, args, logger, url,
                                              credentials, verifysslcert)
        except (requests.exceptions.ConnectionError, Exception), e:
            return None, e

    def sign_request(params, secret_key):
        request = zip(params.keys(), params.values())
        request.sort(key=lambda x: x[0].lower())
        hash_str = "&".join(
            ["=".join(
                [r[0].lower(),
                 urllib.quote_plus(str(r[1])).lower()
                 .replace("+", "%20").replace("%3A", ":")]
            ) for r in request]
        )
        return base64.encodestring(hmac.new(secret_key, hash_str,
                                   hashlib.sha1).digest()).strip()

    args['apiKey'] = credentials['apikey']
    args["signature"] = sign_request(args, credentials['secretkey'])

    session = requests.Session()
    session.mount('https://', SSLAdapter(ssl.PROTOCOL_TLSv1))

    try:
        response = session.get(url, params=args, verify=verifysslcert)
        logger_debug(logger, "Request sent: %s" % response.url)
        result = response.text

        if response.status_code == 200:  # success
            error = None
        elif response.status_code == 401:      # auth issue
            error = "401 Authentication error"
        elif response.status_code != 200 and response.status_code != 401:
            error = "{0}: {1}".format(response.status_code,
                                      response.headers.get('X-Description'))
    except requests.exceptions.ConnectionError, e:
        return None, "Connection refused by server: %s" % e
    except Exception, pokemon:
        error = pokemon.message

    logger_debug(logger, "Response received: %s" % result)
    if error is not None:
        logger_debug(logger, "Error: %s" % (error))
        return result, error

    return result, error

def monkeyrequest(command, args, isasync, asyncblock, logger, url,
                  credentials, timeout, expires, verifysslcert=False,
                  signatureversion=3):
    response = None
    error = None
    logger_debug(logger, "======== START Request ========")
    logger_debug(logger, "Requesting command=%s, args=%s" % (command, args))
    response, error = make_request(command, args, logger, url,
                                   credentials, expires, verifysslcert,
                                   signatureversion)

    logger_debug(logger, "======== END Request ========\n")

    if error is not None and not response:
        return response, error

    def process_json(response):
        try:
            response = json.loads(response, "utf-8")
        except ValueError, e:
            logger_debug(logger, "Error processing json: %s" % e)
            writeError("Error processing json: %s" % e)
            response = None
            error = e
        return response

    response = process_json(response)
    if not response or not isinstance(response, dict):
        return response, error

    isasync = isasync and (asyncblock == "true" or asyncblock == "True")
    responsekey = filter(lambda x: 'response' in x, response.keys())[0]

    if isasync and 'jobid' in response[responsekey]:
        jobid = response[responsekey]['jobid']
        command = "queryAsyncJobResult"
        request = {'jobid': jobid}
        if not timeout:
            timeout = 3600
        timeout = int(timeout)
        cursor = itertools.cycle([u'|', u'/', u'-', u'\\'])
        while timeout > 0:
            interval = 2
            while interval > 0:
                sys.stdout.write(u"%s\r" % cursor.next())
                sys.stdout.flush()
                time.sleep(0.1)
                interval -= 0.1
            timeout = timeout - 2
            logger_debug(logger, "Job %s to timeout in %ds" % (jobid, timeout))

            response, error = make_request(command, request, logger, url,
                                           credentials, expires, verifysslcert)
            if error and not response:
                return response, error

            response = process_json(response)
            responsekeys = filter(lambda x: 'response' in x, response.keys())

            if len(responsekeys) < 1:
                continue

            result = response[responsekeys[0]]
            if "errorcode" in result or "errortext" in result:
                return response, error

            jobstatus = result['jobstatus']
            if jobstatus == 2:
                jobresult = result["jobresult"]
                error = "\rAsync job %s failed\nError %s, %s" % (
                        jobid, jobresult["errorcode"], jobresult["errortext"])
                return response, error
            elif jobstatus == 1:
                sys.stdout.write(u"\r \n")
                sys.stdout.flush()
                return response, error
            elif jobstatus == 0:
                pass  # Job in progress
            else:
                logger_debug(logger, "We should not arrive here!")
                sys.stdout.flush()

        error = "Error: Async query timeout occurred for jobid %s" % jobid

    return response, error


text:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ReMi.DataEntities.BusinessRules
{
    [Table("BusinessRuleParameter", Schema = Constants.BusinessRulesSchemaName)]
    public class BusinessRuleParameter
    {
        [Key]
        public int BusinessRuleParameterId { get; set; }

        [Index(IsUnique = true)]
        public Guid ExternalId { get; set; }

        [Required, Index("IX_BusinessRuleAndName", 1)]
        public int BusinessRuleId { get; set; }

        [Required, Index("IX_BusinessRuleAndName", 2), StringLength(50)]
        public string Name { get; set; }

        [Required, StringLength(256)]
        public string Type { get; set; }

        public virtual BusinessRuleTestData TestData { get; set; }

        public virtual BusinessRuleDescription BusinessRule { get; set; }
    }
}


text:
function electricityConsumption = getElectricityConsumption(vehID)
%getElectricityConsumption Get the electricity consumption of the vehicle.
%   electricityConsumption = getElectricityConsumption(VEHID) Returns the
%   electricity consumption in mw for the last time step.

%   Copyright 2019 Universidad Nacional de Colombia,
%   Politecnico Jaime Isaza Cadavid.
%   Authors: Andres Acosta, Jairo Espinosa, Jorge Espinosa.
%   $Id: getElectricityConsumption.m 48 2018-12-26 15:35:20Z afacostag $

import traci.constants
electricityConsumption = traci.vehicle.getUniversal(constants.VAR_ELECTRICITYCONSUMPTION, vehID);


text:
<!--
//
// Boost.Pointer Container
//
//  Copyright Thorsten Ottosen 2003-2005. Use, modification and
//  distribution is subject to the Boost Software License, Version
//  1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see http://www.boost.org/libs/ptr_container/
//
-->
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE library PUBLIC "-//Boost//DTD BoostBook XML V1.0//EN"
"http://www.boost.org/tools/boostbook/dtd/boostbook.dtd">
<boostbook xmlns:xi="http://www.w3.org/2001/XInclude"
           last-revision="$Date: 2008-02-07 03:44:10 -0500 (Thu, 07 Feb 2008) $">
<library name="Pointer Container" dirname="ptr_container" xmlns:xi="http://www.w3.org/2001/XInclude"
	id="ptr_container" last-revision="$Date: 2008-02-07 03:44:10 -0500 (Thu, 07 Feb 2008) $">
	<libraryinfo>
		<author>
			<firstname>Thorsten</firstname>
			<surname>Ottosen</surname>
		</author>

		<copyright>
			<year>2003</year>
			<holder>Thorsten Ottosen</holder>
		</copyright>

		<legalnotice>
			<para>Permission to copy, use, sell and distribute this software
				is granted provided this copyright notice appears in all copies.
				Permission to modify the code and to distribute modified code is
				granted provided this copyright notice appears in all copies, and
				a notice that the code was modified is included with the copyright
				notice. </para>

			<para> This software is provided "as is" without express or
				implied warranty, and with no claim as to its suitability for any
				purpose. </para>
		</legalnotice>

		<librarypurpose>
			This library provides standard-like containers that are suitable
            for storing pointers to both polymorphic and non-polymorphic objects.
		</librarypurpose>
		<librarycategory name="category:containers"/>
	</libraryinfo>

	<title>Boost Pointer Container Library</title>
	<xi:include href="intro.xml"/>
</library>
</boostbook>


text:
package org.nick.nfcsmime;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;

import org.spongycastle.asn1.ASN1Encoding;
import org.spongycastle.asn1.x509.AlgorithmIdentifier;
import org.spongycastle.asn1.x509.DigestInfo;
import org.spongycastle.util.Arrays;

import android.nfc.tech.IsoDep;
import android.util.Log;

public class MuscleCard {

    private static final String TAG = MuscleCard.class.getSimpleName();

    private static final boolean DEBUG = true;

    private static final short SW_SUCCESS = (short) 0x9000;

    private static final String MUSCLE_AID = "A0 00 00 00 01 01";
    private static final String INPUT_OBJ_ID = "FF FF FF FF";
    private static final String OUTPUT_OBJ_ID = "FF FF FF FE";

    private static final String CERT_OBJECT_ID = "50 15 31 00";
    private static final int CERT_SIZE = 727;

    private static final int MAX_READ = 255;
    private static final int MAX_SEND = 255;

    private IsoDep tag;

    public MuscleCard(IsoDep tag) {
        this.tag = tag;
    }

    public void select() throws IOException {
        connect();

        String cmd = String.format("00 A4 04 00 %02x %s",
                byteLength(MUSCLE_AID), MUSCLE_AID);
        ResponseApdu rapdu = transceive(cmd);
        Log.d(TAG, "SELECT: " + rapdu.toString());
        checkSw(rapdu);
    }

    public boolean verifyPin(String pin) throws IOException {
        connect();

        String cmd = String.format("B0 42 01 00 %02x %s", pin.length(),
                Hex.toHex(pin.getBytes("ASCII")));
        ResponseApdu rapdu = transceive(cmd);
        if (DEBUG) {
            Log.d(TAG, "VERIFY PIN: " + rapdu.toString());
        }
        if (rapdu.getSW() != SW_SUCCESS) {
            Log.e(TAG, "Error reponse: " + Integer.toString(rapdu.getSW(), 16));
            // throw new MuscleException(rapdu.getSW());
            return false;
        }

        return true;
    }

    private void computeCryptInit() throws IOException {
        connect();

        // key 0x1, RSA_NOPAD
        String cmd = "B0 36 00 01 05 00 04 01 00 00 02";
        ResponseApdu rapdu = transceive(cmd);
        if (DEBUG) {
            Log.d(TAG, "COMPUTE CRYPT INIT: " + rapdu.toString());
        }
        checkSw(rapdu);
    }

    private void computeCryptFinal() throws IOException {
        connect();

        // data location: object (0x2)
        String cmd = "B0 36 00 03 01 02";
        ResponseApdu rapdu = transceive(cmd);
        if (DEBUG) {
            Log.d(TAG, "COMPUTE CRYPT FINAL: " + rapdu.toString());
        }
        checkSw(rapdu);
    }

    public void createObject(String id, int size, short readAcl,
            short writeAcl, short delAcl) throws IOException {
        connect();

        String cmd = String.format("B0 5A 00 00 0E %s %s %s %s %s", id,
                Hex.toHex(size), Hex.toHex(readAcl), Hex.toHex(writeAcl),
                Hex.toHex(delAcl));
        ResponseApdu rapdu = transceive(cmd);
        if (DEBUG) {
            Log.d(TAG, "CREATE OBJECT: " + rapdu.toString());
        }
        checkSw(rapdu);
    }

    public void updateObject(String objectId, int offset, byte[] data)
            throws IOException {
        connect();

        // len | data
        byte[] buff = new byte[data.length + 2];
        short dataLen = (short) data.length;
        buff[0] = (byte) ((dataLen >> 8) & 0xff);
        buff[1] = (byte) (dataLen & 0xff);
        System.arraycopy(data, 0, buff, 2, data.length);

        int chunkLen = MAX_SEND - 9;
        for (int i = 0; i < buff.length; i += chunkLen) {
            updateObjectChunk(objectId, offset + i, buff, i,
                    Math.min(buff.length - i, chunkLen));
        }
    }

    private void updateObjectChunk(String objectId, int offset, byte[] data,
            int dataOffset, int dataLen) throws IOException {
        connect();

        int lc = dataLen + 9;
        String cmd = String.format(
                "B0 54 00 00 %02x %s %s %02x %s",
                lc,
                objectId,
                Hex.toHex(offset),
                dataLen,
                Hex.toHex(Arrays.copyOfRange(data, dataOffset, dataOffset
                        + dataLen)));
        ResponseApdu rapdu = transceive(cmd);
        if (DEBUG) {
            Log.d(TAG, "UPDATE OBJECT: " + rapdu.toString());
        }
        checkSw(rapdu);
    }

    public byte[] readObject(String objectId, int offset, int dataLen)
            throws IOException {
        connect();

        int chunkLen = MAX_READ;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        for (int i = 0; i < dataLen; i += chunkLen) {
            byte[] chunk = readObjectChunk(objectId, offset + i,
                    Math.min(dataLen - i, chunkLen));
            baos.write(chunk);
        }

        return baos.toByteArray();
    }

    private byte[] readObjectChunk(String objectId, int offset, int dataLen)
            throws IOException {
        connect();

        // objectId | offset | dataLen | le
        String cmd = String.format("B0 56 00 00 09 %s %s %02x %02x", objectId,
                Hex.toHex(offset), dataLen, dataLen);
        ResponseApdu rapdu = transceive(cmd);
        if (DEBUG) {
            Log.d(TAG, "READ OBJECT: " + rapdu.toString());
        }
        checkSw(rapdu);

        return rapdu.getData();
    }

    private static byte[] createSha512EncryptionBlock(byte[] data, int keySize) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA512");
            byte[] digest = md.digest(data);
            // SHA512
            AlgorithmIdentifier sha512Aid = AlgorithmIdentifier
                    .getInstance("2.16.840.1.101.3.4.2.3");
            DigestInfo di = new DigestInfo(sha512Aid, digest);
            byte[] diDer = di.getEncoded(ASN1Encoding.DER);

            return padPkcs1(diDer, keySize);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // PKCS#1 padding
    private static byte[] padPkcs1(byte[] in, int keySize) {
        if (in.length > keySize) {
            throw new IllegalArgumentException("Data too long");
        }
        byte[] result = new byte[keySize / 8];

        result[0] = 0x0;
        result[1] = 0x01; // BT 1

        // PS
        for (int i = 2; i != result.length - in.length - 1; i++) {
            result[i] = (byte) 0xff;
        }

        // end of padding
        result[result.length - in.length - 1] = 0x00;
        // D
        System.arraycopy(in, 0, result, result.length - in.length, in.length);

        return result;
    }

    public byte[] sign(byte[] data) throws IOException {
        if (data.length == 0) {
            throw new IllegalArgumentException("Data must not be empty");
        }

        connect();

        computeCryptInit();

        // len | data => data length + 2
        int signatureLen = 2048 / 8;
        createObject(INPUT_OBJ_ID, signatureLen + 2, (short) 0x2, (short) 0x2,
                (short) 0x2);
        createObject(OUTPUT_OBJ_ID, signatureLen + 2, (short) 0x2, (short) 0x2,
                (short) 0x2);

        byte[] eb = createSha512EncryptionBlock(data, 2048);
        updateObject(OUTPUT_OBJ_ID, 0, eb);

        computeCryptFinal();

        // len | data => offset = 0x2
        String cmd = "B0 56 00 00 09 FF FF FF FF 00 00 00 02 FF FF";
        ResponseApdu rapdu = transceive(cmd);
        if (DEBUG) {
            Log.d(TAG, "READ OBJECT: " + rapdu.toString());
        }
        checkSw(rapdu);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write(rapdu.getData());

        cmd = "B0 56 00 00 09 FF FF FF FF 00 00 01 01 01 01";
        rapdu = transceive(cmd);
        if (DEBUG) {
            Log.d(TAG, "READ OBJECT: " + rapdu.toString());
        }
        checkSw(rapdu);
        baos.write(rapdu.getData());

        deleteObject(OUTPUT_OBJ_ID);

        return baos.toByteArray();
    }

    private void connect() throws IOException {
        if (!tag.isConnected()) {
            tag.connect();
        }
    }

    private void checkSw(ResponseApdu rapdu) {
        if (rapdu.getSW() != SW_SUCCESS) {
            Log.e(TAG, "Error reponse: " + Integer.toString(rapdu.getSW(), 16));
            throw new MuscleException(rapdu.getSW());
        }
    }

    private ResponseApdu transceive(String cmd) throws IOException {
        if (DEBUG) {
            Log.d(TAG, "--> " + cmd);
        }
        byte[] response = tag.transceive(Hex.fromHex(cmd));
        if (DEBUG) {
            Log.d(TAG, "<-- " + Hex.toHex(response));
        }

        return new ResponseApdu(response);
    }

    public void deleteObject(String id) throws IOException {
        connect();

        int len = byteLength(id);
        String cmd = String.format("B0 52 00 00 %02x %s", len, id);
        ResponseApdu rapdu = transceive(cmd);
        if (DEBUG) {
            Log.d(TAG, "DELETE OBJECT: " + rapdu.toString());
        }
        checkSw(rapdu);
    }

    public byte[] readSignerCertificate() throws IOException {
        return readObject(CERT_OBJECT_ID, 0, CERT_SIZE);
    }

    private static int byteLength(String id) {
        return id.replace(" ", "").length() / 2;
    }
}


text:
//==============================================================================
// Include files
#include <windows.h>
#include <utility.h>
#include <stdio.h>
#include "MCTBox_API_DIO.h"
#include "../user_utility.h"
#include "SUT Sequenzer Kernel API.h"

//==============================================================================
// Constants

//==============================================================================
// Types

//==============================================================================
// Static global variables
static void MCTBOxAPI_TF_DIOModule_SetDoutPortHighLowHelp(void);
static void MCTBoxAPI_TF_DIOModule_GetDinPortStateHelp(void);
static void MCTBoxAPI_TF_DIOModule_ParallelGetDin24PortsStatesHelp(void);
static void MCTBoxAPI_TF_DIOModule_SetDoutPortHighLowByTokensHelp(void);
static void MCTBoxAPI_TF_DIOModule_GetDinPortStateByTokenHelp(void);

//==============================================================================
// Static functions

//==============================================================================
// Global variables
extern int __stdcall (*pfTESTER_TestFunctionSetInfoStr)(char sKey[], char sLabel[], char sValue[]);

//==============================================================================
// Test Functions implementation :
static void MCTBOxAPI_TF_DIOModule_SetDoutPortHighLowHelp(void)
{
	int iCnt = 0;
	char sKey[32] = {0}, sLabel[32] = {0}, sValue[32] = {0};

	TESTER_TestFunctionRegisterHelp(1, "Digital-OUT Board ID",
		"Edit the ID number of Digital-OUT board.\nRange: [0x00, 0xFF]");
	TESTER_TestFunctionRegisterHelp(2, "Digital-OUT port number",
		"Choose the port number of Digital-OUT board from the list box.\nRange: [1, 24]");
	TESTER_TestFunctionRegisterHelp(3, "The output state of Digital-OUT port",
		"Choose the output state of Digital-OUT port from the list box.\nRange: [LOW, HIGH]");

	pfTESTER_TestFunctionSetInfoStr("Param2.Type", "", "3");
	pfTESTER_TestFunctionSetInfoStr("Param2.NumValue", "", "24");
	for (iCnt=1; iCnt<=24; iCnt++)
	{
		sprintf(sKey, "Param2.Value%d", iCnt);
		sprintf(sLabel, "%d", iCnt);
		sprintf(sValue, "%d", iCnt);
		pfTESTER_TestFunctionSetInfoStr(sKey, sLabel, sValue);
	}

	pfTESTER_TestFunctionSetInfoStr("Param3.Type", "", "3");
	pfTESTER_TestFunctionSetInfoStr("Param3.NumValue", "", "2");
	pfTESTER_TestFunctionSetInfoStr("Param3.Value1", "LOW", "LOW");
	pfTESTER_TestFunctionSetInfoStr("Param3.Value2", "HIGH", "HIGH");
}

void API MCTBOxAPI_TF_DIOModule_SetDoutPortHighLow(int hThisStep)
{
	int iError = 0;
	char sError[256] = {0};
	EState eDoutPortState = 0;

	TEST_PARAM_INT(1, iDoutBoardID);
	TEST_PARAM_INT(2, iDoutPortNr);
	TEST_PARAM_STR(3, sDoutPortState);

	TEST_CHECK_CBREAK;
	TEST_STEP_DELAY;

	if (!strcmp(sDoutPortState, "HIGH"))
		eDoutPortState = HIGH;
	else if (!strcmp(sDoutPortState, "LOW"))
		eDoutPortState = LOW;

	iError = MCTBoxAPI_DIOModule_SetDoutPortHighLow(iDoutBoardID, iDoutPortNr, eDoutPortState, sError);
	if (iError)
	{
		TEST_RETURN_TESTERERROR(iError, sError);
		return;
	}
	TEST_RESULT_STR("OK", "");
	return;
}

/******************************************************************************/
static void MCTBoxAPI_TF_DIOModule_GetDinPortStateHelp(void)
{
	char sKey[32] = {0}, sLabel[32] = {0}, sValue[32] = {0};

	TESTER_TestFunctionRegisterHelp(1, "Digital-IN Board ID",
		"Edit the ID number of Digital-IN Board.\nRange: [0x00, 0xFF]");
	TESTER_TestFunctionRegisterHelp(2, "Digital-IN port number",
		"Choose the port number of Digital-IN board from the list box.\nRange: [1, 24]");

	pfTESTER_TestFunctionSetInfoStr("Param2.Type", "", "3");
	pfTESTER_TestFunctionSetInfoStr("Param2.NumValue", "", "24");
	for (int iCnt=1; iCnt<=24; iCnt++)
	{
		sprintf(sKey, "Param2.Value%d", iCnt);
		sprintf(sLabel, "%d", iCnt);
		sprintf(sValue, "%d", iCnt);
		pfTESTER_TestFunctionSetInfoStr(sKey, sLabel, sValue);
	}
}

void API MCTBoxAPI_TF_DIOModule_GetDinPortState(int hThisStep)
{
	int iError = 0;
	char sError[256] = {0};
	EState eDinPortState = 0;

	TEST_PARAM_INT(1, iDinBoardID);
	TEST_PARAM_INT(2, iDinPortNr);

	TEST_CHECK_CBREAK;
	TEST_STEP_DELAY;

	iError = MCTBoxAPI_DIOModule_QueryDinPortState(iDinPortNr, &eDinPortState, sError);
	if (iError)
	{
		TEST_RETURN_TESTERERROR(iError, sError);
		return;
	}
	if (eDinPortState == HIGH)
	{
		TEST_RESULT_STR("HIGH", "");
	}
	else if (eDinPortState == LOW)
	{
		TEST_RESULT_STR("LOW", "");
	}
	return;
}

/******************************************************************************/
static void MCTBoxAPI_TF_DIOModule_ParallelGetDin24PortsStatesHelp(void)
{
	TESTER_TestFunctionRegisterHelp(1, "Digital-IN Board ID",
		"Edit the ID number of Digital-IN Board.\nRange: [0x00, 0xFF]");
}

void API MCTBoxAPI_TF_DIOModule_ParallelGetDin24PortsStates(int hThisStep)
{
	int iError = 0;
	char sError[256] = "";
	EState eDin24PortsStateArray[24] = {OFF};
	char sDin24PortsStateArray[32] = {0}, sTemp[4] = {0};

	TEST_PARAM_INT(1, ucDinBoardID);

	TEST_CHECK_CBREAK;
	TEST_STEP_DELAY;

	iError = MCTBoxAPI_DIOModule_ParallelQueryDin24PortsState(eDin24PortsStateArray, sError);
	if (iError)
	{
		TEST_RETURN_TESTERERROR(iError, sError);
		return;
	}
	for (int i=23; i>=0; i--)
	{
		if (eDin24PortsStateArray[i] == OFF)
			sprintf(sTemp, "%s", "0");
		else if (eDin24PortsStateArray[i] == ON)
			sprintf(sTemp, "%s", "1");

		strcat(sDin24PortsStateArray, sTemp);
	}

	TEST_RESULT_STR(sDin24PortsStateArray, "");
	return;
}

/******************************************************************************/
static void MCTBoxAPI_TF_DIOModule_SetDoutPortHighLowByTokensHelp(void)
{
	TESTER_TestFunctionRegisterHelp(1, "Digital-OUT port tokens list which you want to set HIGH",
		"Please separate these DIO port tokens by comma ','.\nOther signs or space are not supported now.");

	TESTER_TestFunctionRegisterHelp(2, "Digital-OUT port tokens list which you want to set LOW",
		"Please separate these DIO port tokens by comma ','.\nOther signs or space are not supported now.");
}

void API MCTBoxAPI_TF_DIOModule_SetDoutPortHighLowByTokens(int hThisStep)
{
	int iError = 0;
	char sError[256] = {0};
	char *sDioPortTokensArray2SetHigh[64] = {0}, *sDioPortTokensArray2SetLow[64] = {0};
	int iNumOfTokens2SetHigh = 0, iNumOfTokens2SetLow = 0, i = 0;

	TEST_PARAM_STR(1, sDioPortTokensList2SetHigh);
	TEST_PARAM_STR(2, sDioPortTokensList2SetLow);

	TEST_CHECK_CBREAK;
	TEST_STEP_DELAY;

	if ( (strlen(sDioPortTokensList2SetHigh) == 0) &&
		 (strlen(sDioPortTokensList2SetLow)  == 0) )
	{
		TEST_RETURN_TESTERERROR(-1, "Error : Parameter list is empty.");
		return;
	}
	if (0 != strlen(sDioPortTokensList2SetHigh))
	{
		ParseTokenList(sDioPortTokensList2SetHigh, sDioPortTokensArray2SetHigh, &iNumOfTokens2SetHigh);
		for (i=0; i<iNumOfTokens2SetHigh; i++)
		{
			iError = MCTBoxAPI_DIOModule_SetDoutPortHighLowByToken(sDioPortTokensArray2SetHigh[i], HIGH, sError);
			if (iError)
			{
				TEST_RETURN_TESTERERROR(iError, sError);
				return;
			}
		}
	}
	if (0 != strlen(sDioPortTokensList2SetLow))
	{
		ParseTokenList(sDioPortTokensList2SetLow, sDioPortTokensArray2SetLow, &iNumOfTokens2SetLow);
		for (i=0; i<iNumOfTokens2SetLow; i++)
		{
			iError = MCTBoxAPI_DIOModule_SetDoutPortHighLowByToken(sDioPortTokensArray2SetLow[i], LOW, sError);
			if (iError)
			{
				TEST_RETURN_TESTERERROR(iError, sError);
				return;
			}
		}
	}
	TEST_RESULT_STR("OK", "");
	return;
}

/******************************************************************************/
static void MCTBoxAPI_TF_DIOModule_GetDinPortStateByTokenHelp(void)
{
	TESTER_TestFunctionRegisterHelp(1, "Digital-IN port token which you want to query",
		"Note : only 1 token can be accepted and supported currently.\nNeither need the comma ',' separator nor other signs.");
}

void API MCTBoxAPI_TF_DIOModule_GetDinPortStateByToken(int hThisStep)
{
	int iError = 0;
	char sError[256] = {0};
	EState eDinPortState = 0;

	TEST_PARAM_STR(1, sOnly1DinPortToken);

	TEST_CHECK_CBREAK;
	TEST_STEP_DELAY;

	iError = MCTBoxAPI_DIOModule_QueryDinPortStateByToken(sOnly1DinPortToken, &eDinPortState, sError);
	if (iError)
	{
		TEST_RETURN_TESTERERROR(iError, sError);
		return;
	}
	if (eDinPortState == HIGH)
	{
		TEST_RESULT_STR("HIGH", "");
	}
	else if (eDinPortState == LOW)
	{
		TEST_RESULT_STR("LOW", "");
	}
	return;
}

/******************************************************************************/
void API MCTBoxAPI_RegisterDIOModuleTFSteps(void)
{
	TEST_REGISTER(MCTBOxAPI_TF_DIOModule_SetDoutPortHighLow);
	MCTBOxAPI_TF_DIOModule_SetDoutPortHighLowHelp();

	TEST_REGISTER(MCTBoxAPI_TF_DIOModule_GetDinPortState);
	MCTBoxAPI_TF_DIOModule_GetDinPortStateHelp();

	TEST_REGISTER(MCTBoxAPI_TF_DIOModule_ParallelGetDin24PortsStates);
	MCTBoxAPI_TF_DIOModule_ParallelGetDin24PortsStatesHelp();

	TEST_REGISTER(MCTBoxAPI_TF_DIOModule_SetDoutPortHighLowByTokens);
	MCTBoxAPI_TF_DIOModule_SetDoutPortHighLowByTokensHelp();

	TEST_REGISTER(MCTBoxAPI_TF_DIOModule_GetDinPortStateByToken);
	MCTBoxAPI_TF_DIOModule_GetDinPortStateByTokenHelp();
}


text:
import datetime
from django.conf import settings
from django.core.management.base import LabelCommand
from corehq.apps.registration.models import OldRegistrationRequest, RegistrationRequest

class Command(LabelCommand):
    help = "Migrates old django RegistrationRequest model to new couch model. March 2012."
    args = ""
    label = ""

    def handle(self, *args, **options):
        django_requests = OldRegistrationRequest.objects.all()

        print "Migrating RegistrationRequest Model from django to couch"

        for request in django_requests:
            existing_request = None
            try:
                existing_request = RegistrationRequest.get_by_guid(request.activation_guid)
            except Exception:
                pass
            try:
                if not existing_request:
                    new_req = RegistrationRequest(tos_confirmed=request.tos_confirmed,
                        request_time=request.request_time,
                        request_ip=request.request_ip,
                        activation_guid=request.activation_guid,
                        confirm_time=request.confirm_time,
                        confirm_ip=request.confirm_ip,
                        domain=request.domain.name,
                        new_user_username=request.new_user.username,
                        requesting_user_username=request.requesting_user.username)
                    new_req.save()
            except Exception as e:
                print "There was an error migrating a registration request with guid %s." % request.activation_guid
                print "Error: %s" % e


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

<title>Uses of Class com.mxgraph.canvas.mxGraphicsCanvas2D.CanvasState (JGraph X 3.3.1.1 API Specification)</title>
<meta name="date" content="2015-06-23">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

JGraph X 3.3.1.1

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.mxgraph.canvas.mxGraphicsCanvas2D.CanvasState

Packages that use mxGraphicsCanvas2D.CanvasState

Package
Description

com.mxgraph.canvas

This package contains various implementations for painting a graph using
  different technologies, such as Graphics2D, HTML, SVG or VML.

Uses of mxGraphicsCanvas2D.CanvasState in com.mxgraph.canvas

Fields in com.mxgraph.canvas declared as mxGraphicsCanvas2D.CanvasState

Modifier and Type
Field and Description

protected mxGraphicsCanvas2D.CanvasState
mxGraphicsCanvas2D.state

Represents the current state of the canvas.

Fields in com.mxgraph.canvas with type parameters of type mxGraphicsCanvas2D.CanvasState

Modifier and Type
Field and Description

protected Stack<mxGraphicsCanvas2D.CanvasState>
mxGraphicsCanvas2D.stack

Stack of states for save/restore.

Methods in com.mxgraph.canvas that return mxGraphicsCanvas2D.CanvasState

Modifier and Type
Method and Description

protected mxGraphicsCanvas2D.CanvasState
mxGraphicsCanvas2D.cloneState(mxGraphicsCanvas2D.CanvasState state)

Returns a clone of thec given state.

Methods in com.mxgraph.canvas with parameters of type mxGraphicsCanvas2D.CanvasState

Modifier and Type
Method and Description

protected mxGraphicsCanvas2D.CanvasState
mxGraphicsCanvas2D.cloneState(mxGraphicsCanvas2D.CanvasState state)

Returns a clone of thec given state.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

JGraph X 3.3.1.1

Prev

Next

Frames

No Frames

All Classes

Copyright (c) 2010 Gaudenz Alder. All rights reserved.


text:
WolframLaunch
=============

Desktop launcher for Wolfram | Alpha

Features a convenient "add matrix" button to very quickly create matrices.
The AutoHotKey script will run the app when WIN+W is pressed.


text:
package dzufferey.arg

object MyBool extends Enumeration {
  val top, bot = Value
}


text:
package org.sagebionetworks.annotations.worker;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sagebionetworks.asynchronous.workers.changes.ChangeMessageDrivenRunner;
import org.sagebionetworks.cloudwatch.WorkerLogger;
import org.sagebionetworks.common.util.progress.ProgressCallback;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.SubmissionStatusAnnotationsAsyncManager;
import org.sagebionetworks.repo.model.message.ChangeMessage;
import org.sagebionetworks.repo.model.message.ChangeType;
import org.sagebionetworks.workers.util.aws.message.RecoverableMessageException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.TransientDataAccessException;

/**
 * The worker that processes messages for SubmissionStatus Annotations jobs.
 *
 */
public class EvaluationSubmissionAnnotationsWorker implements ChangeMessageDrivenRunner {

	static private Log log = LogFactory.getLog(EvaluationSubmissionAnnotationsWorker.class);

	@Autowired
	private SubmissionStatusAnnotationsAsyncManager ssAsyncMgr;
	@Autowired
	private WorkerLogger workerLogger;

	@Override
	public void run(ProgressCallback progressCallback, ChangeMessage change)
			throws RecoverableMessageException, Exception {
		// We only care about Submission messages here
		if (ObjectType.EVALUATION_SUBMISSIONS == change.getObjectType()) {
			try {
				// Is this a create, update, or delete?
				if (ChangeType.CREATE == change.getChangeType()) {
					ssAsyncMgr.createEvaluationSubmissionStatuses(change.getObjectId());
				} else if (ChangeType.UPDATE == change.getChangeType()) {
					// update
					ssAsyncMgr.updateEvaluationSubmissionStatuses(change.getObjectId());
				} else if(ChangeType.DELETE == change.getChangeType()) {
					// delete
					ssAsyncMgr.deleteEvaluationSubmissionStatuses(change.getObjectId());
				} else {
					throw new IllegalArgumentException("Unknown change type: "+change.getChangeType());
				}
			} catch (TransientDataAccessException e) {
				log.info("Intermittent error in AnnotationsWorker: "+e.getMessage()+". Will retry");
				workerLogger.logWorkerFailure(this.getClass(), change, e, true);
				throw new RecoverableMessageException();
			} catch (Throwable e) {
				// Something went wrong and we did not process the message.  By default we remove the message from the queue.
				log.error("Failed to process message", e);
				workerLogger.logWorkerFailure(this.getClass(), change, e, false);
			}
		}
	}

}


text:
package org.mybatis.spring.config;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

import com.mockrunner.mock.jdbc.MockDataSource;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.mapper.AnnotatedMapper;
import org.mybatis.spring.mapper.MapperInterface;
import org.mybatis.spring.mapper.MapperSubinterface;
import org.mybatis.spring.mapper.ScopedProxyMapper;
import org.mybatis.spring.mapper.child.MapperChildInterface;
import org.mybatis.spring.type.DummyMapperFactoryBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.GenericApplicationContext;

/**
 * Test for the MapperScannerRegistrar.
 * <p>
 * This test works fine with Spring 3.1 and 3.2 but with 3.1 the registrar is called twice.
 */
class NamespaceTest {
  private ClassPathXmlApplicationContext applicationContext;

  private void startContext() {
    applicationContext.refresh();
    applicationContext.start();

    // this will throw an exception if the beans cannot be found
    applicationContext.getBean("sqlSessionFactory");
  }

  @AfterEach
  void assertNoMapperClass() {
    try {
      // concrete classes should always be ignored by MapperScannerPostProcessor
      assertBeanNotLoaded("mapperClass");

      // no method interfaces should be ignored too
      assertBeanNotLoaded("package-info");
      // assertBeanNotLoaded("annotatedMapperZeroMethods"); // as of 1.1.0 mappers
      // with no methods are loaded
    } finally {
      applicationContext.close();
    }
  }

  @Test
  void testInterfaceScan() {

    applicationContext = new ClassPathXmlApplicationContext(
        new String[] { "org/mybatis/spring/config/base-package.xml" }, setupSqlSessionFactory());

    startContext();

    SqlSessionFactory sqlSessionFactory = applicationContext.getBean(SqlSessionFactory.class);
    assertEquals(5, sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers().size());

    // all interfaces with methods should be loaded
    applicationContext.getBean("mapperInterface");
    applicationContext.getBean("mapperSubinterface");
    applicationContext.getBean("mapperChildInterface");
    applicationContext.getBean("annotatedMapper");
  }

  @Test
  void testNameGenerator() {

    applicationContext = new ClassPathXmlApplicationContext(
        new String[] { "org/mybatis/spring/config/name-generator.xml" }, setupSqlSessionFactory());

    startContext();

    // only child inferfaces should be loaded and named with its class name
    applicationContext.getBean(MapperInterface.class.getName());
    applicationContext.getBean(MapperSubinterface.class.getName());
    applicationContext.getBean(MapperChildInterface.class.getName());
    applicationContext.getBean(AnnotatedMapper.class.getName());
  }

  @Test
  void testMarkerInterfaceScan() {

    applicationContext = new ClassPathXmlApplicationContext(
        new String[] { "org/mybatis/spring/config/marker-interface.xml" }, setupSqlSessionFactory());

    startContext();

    // only child inferfaces should be loaded
    applicationContext.getBean("mapperSubinterface");
    applicationContext.getBean("mapperChildInterface");

    assertBeanNotLoaded("mapperInterface");
    assertBeanNotLoaded("annotatedMapper");
  }

  @Test
  void testAnnotationScan() {

    applicationContext = new ClassPathXmlApplicationContext(new String[] { "org/mybatis/spring/config/annotation.xml" },
        setupSqlSessionFactory());

    startContext();

    // only annotated mappers should be loaded
    applicationContext.getBean("annotatedMapper");
    applicationContext.getBean("mapperChildInterface");

    assertBeanNotLoaded("mapperInterface");
    assertBeanNotLoaded("mapperSubinterface");
  }

  @Test
  void testMarkerInterfaceAndAnnotationScan() {

    applicationContext = new ClassPathXmlApplicationContext(
        new String[] { "org/mybatis/spring/config/marker-and-annotation.xml" }, setupSqlSessionFactory());

    startContext();

    // everything should be loaded but the marker interface
    applicationContext.getBean("annotatedMapper");
    applicationContext.getBean("mapperSubinterface");
    applicationContext.getBean("mapperChildInterface");

    assertBeanNotLoaded("mapperInterface");
  }

  @Test
  void testScanWithExplicitSqlSessionFactory() {

    applicationContext = new ClassPathXmlApplicationContext(
        new String[] { "org/mybatis/spring/config/factory-ref.xml" }, setupSqlSessionFactory());

    startContext();

    // all interfaces with methods should be loaded
    applicationContext.getBean("mapperInterface");
    applicationContext.getBean("mapperSubinterface");
    applicationContext.getBean("mapperChildInterface");
    applicationContext.getBean("annotatedMapper");
  }

  @Test
  void testScanWithExplicitSqlSessionTemplate() {

    applicationContext = new ClassPathXmlApplicationContext(
        new String[] { "org/mybatis/spring/config/factory-ref.xml" }, setupSqlSessionTemplate());

    startContext();

    // all interfaces with methods should be loaded
    applicationContext.getBean("mapperInterface");
    applicationContext.getBean("mapperSubinterface");
    applicationContext.getBean("mapperChildInterface");
    applicationContext.getBean("annotatedMapper");
  }

  @Test
  void testScanWithMapperFactoryBeanClass() {
    DummyMapperFactoryBean.clear();
    applicationContext = new ClassPathXmlApplicationContext(
        new String[] { "org/mybatis/spring/config/mapper-factory-bean-class.xml" }, setupSqlSessionTemplate());

    startContext();

    // all interfaces with methods should be loaded
    applicationContext.getBean("mapperInterface");
    applicationContext.getBean("mapperSubinterface");
    applicationContext.getBean("mapperChildInterface");
    applicationContext.getBean("annotatedMapper");

    assertTrue(DummyMapperFactoryBean.getMapperCount() > 0);
  }

  @Test
  void testLazy() {

    applicationContext = new ClassPathXmlApplicationContext(new String[] { "org/mybatis/spring/config/lazy.xml" },
        setupSqlSessionTemplate());

    startContext();

    SqlSessionFactory sqlSessionFactory = applicationContext.getBean(SqlSessionFactory.class);
    assertEquals(0, sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers().size());

    // all interfaces with methods should be loaded
    applicationContext.getBean("mapperInterface");
    applicationContext.getBean("mapperSubinterface");
    applicationContext.getBean("mapperChildInterface");
    applicationContext.getBean("annotatedMapper");

    assertEquals(4, sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers().size());
  }

  @Test
  void testDefaultScope() {
    applicationContext = new ClassPathXmlApplicationContext(
        new String[] { "org/mybatis/spring/config/default-scope.xml" }, false, setupSqlSessionTemplate());

    startContext();

    List<String> scopedProxyTargetBeans = Stream.of(applicationContext.getBeanDefinitionNames())
        .filter(x -> x.startsWith("scopedTarget")).collect(Collectors.toList());
    assertThat(scopedProxyTargetBeans).hasSize(6).contains("scopedTarget.scopedProxyMapper",
        "scopedTarget.annotatedMapper", "scopedTarget.annotatedMapperZeroMethods", "scopedTarget.mapperInterface",
        "scopedTarget.mapperSubinterface", "scopedTarget.mapperChildInterface");

    for (String scopedProxyTargetBean : scopedProxyTargetBeans) {
      {
        BeanDefinition definition = applicationContext.getBeanFactory().getBeanDefinition(scopedProxyTargetBean);
        assertThat(definition.getBeanClassName()).isEqualTo("org.mybatis.spring.mapper.MapperFactoryBean");
        assertThat(definition.getScope()).isEqualTo("thread");
      }
      {
        BeanDefinition definition = applicationContext.getBeanFactory()
            .getBeanDefinition(scopedProxyTargetBean.substring(13));
        assertThat(definition.getBeanClassName()).isEqualTo("org.springframework.aop.scope.ScopedProxyFactoryBean");
        assertThat(definition.getScope()).isEqualTo("");
      }
    }
    {
      ScopedProxyMapper mapper = applicationContext.getBean(ScopedProxyMapper.class);
      assertThat(mapper.test()).isEqualTo("test");
    }
    {
      AnnotatedMapper mapper = applicationContext.getBean(AnnotatedMapper.class);
      assertThat(mapper.test()).isEqualTo("main");
    }

    SqlSessionFactory sqlSessionFactory = applicationContext.getBean(SqlSessionFactory.class);
    assertEquals(2, sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers().size());
  }

  private GenericApplicationContext setupSqlSessionTemplate() {

    GenericApplicationContext genericApplicationContext = setupSqlSessionFactory();
    GenericBeanDefinition definition = new GenericBeanDefinition();
    definition.setBeanClass(SqlSessionTemplate.class);
    ConstructorArgumentValues constructorArgs = new ConstructorArgumentValues();
    constructorArgs.addGenericArgumentValue(new RuntimeBeanReference("sqlSessionFactory"));
    definition.setConstructorArgumentValues(constructorArgs);
    genericApplicationContext.registerBeanDefinition("sqlSessionTemplate", definition);
    return genericApplicationContext;
  }

  private GenericApplicationContext setupSqlSessionFactory() {

    GenericApplicationContext genericApplicationContext = new GenericApplicationContext();

    GenericBeanDefinition definition = new GenericBeanDefinition();
    definition.setBeanClass(SqlSessionFactoryBean.class);
    definition.getPropertyValues().add("dataSource", new MockDataSource());

    DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
    factory.registerBeanDefinition("sqlSessionFactory", definition);

    genericApplicationContext.registerBeanDefinition("sqlSessionFactory", definition);

    genericApplicationContext.refresh();

    return genericApplicationContext;
  }

  private void assertBeanNotLoaded(String name) {
    try {
      applicationContext.getBean(name);
      fail("Spring bean should not be defined for class " + name);
    } catch (NoSuchBeanDefinitionException nsbde) {
      // success
    }
  }

  public static class BeanNameGenerator implements org.springframework.beans.factory.support.BeanNameGenerator {

    @Override
    public String generateBeanName(BeanDefinition beanDefinition, BeanDefinitionRegistry definitionRegistry) {
      return beanDefinition.getBeanClassName();
    }

  }

}


text:
package fr.qp1c.ebdj.liseuse.commun.exchange.question;

import java.util.Map;

public class Theme4ALSBdjDistante extends QRGeneriqueBdjDistante {

	private String theme;

	private String categorie4ALS;

	private Long categorie4ALSRef;

	private Long groupeCategorie4ALS;

	private Map<Integer, Question4ALSBdjDistante> questions;

	public String getTheme() {
		return theme;
	}

	public void setTheme(String theme) {
		this.theme = theme;
	}

	public String getCategorie4ALS() {
		return categorie4ALS;
	}

	public void setCategorie4ALS(String categorie4als) {
		categorie4ALS = categorie4als;
	}

	public Long getCategorie4ALSRef() {
		return categorie4ALSRef;
	}

	public void setCategorie4ALSRef(Long categorie4alsRef) {
		categorie4ALSRef = categorie4alsRef;
	}

	public Long getGroupeCategorie4ALS() {
		return groupeCategorie4ALS;
	}

	public void setGroupeCategorie4ALS(Long groupeCategorie4ALS) {
		this.groupeCategorie4ALS = groupeCategorie4ALS;
	}

	public Map<Integer, Question4ALSBdjDistante> getQuestions() {
		return questions;
	}

	public void setQuestions(Map<Integer, Question4ALSBdjDistante> questions) {
		this.questions = questions;
	}

}


text:
package net.ocheyedan.ply.mvn;

import org.junit.Test;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNull;

/**
 * User: blangel
 * Date: 11/11/11
 * Time: 9:25 AM
 */
public class MavenMetadataParserTest {

    @Test
    public void parseMetadata() {
        MavenMetadataParser parser = new MavenMetadataParser();
        assertNull(parser.parseMetadata(null, null));

        MavenMetadataParser.Metadata metadata = parser.parseMetadata("classpath:mock-mvn-repo/log4j/log4j", null);
        assertEquals("1.2.16", metadata.latest);
        assertEquals(1, metadata.versions.size());
        assertEquals("1.2.16", metadata.versions.get(0));
        metadata = parser.parseMetadata("classpath:mock-mvn-repo/log4j/log4j/", null); // test with ending slash
        assertEquals("1.2.16", metadata.latest);
        assertEquals(1, metadata.versions.size());
        assertEquals("1.2.16", metadata.versions.get(0));

        metadata = parser.parseMetadata("classpath:mock-mvn-repo/javax/mail/mail", null);
        assertEquals("1.4.4", metadata.latest);
        assertEquals(5, metadata.versions.size());
        assertEquals("1.4.2", metadata.versions.get(0));
        assertEquals("1.4.3-rc1", metadata.versions.get(1));
        assertEquals("1.4.3", metadata.versions.get(2));
        assertEquals("1.4.4-rc1", metadata.versions.get(3));
        assertEquals("1.4.4", metadata.versions.get(4));
    }

}


text:
namespace Microsoft.Azure.Management.Logic.Models
{
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    using System.Runtime;
    using System.Runtime.Serialization;

    /// <summary>
    /// Defines values for AgreementType.
    /// </summary>
    [JsonConverter(typeof(StringEnumConverter))]
    public enum AgreementType
    {
        [EnumMember(Value = "NotSpecified")]
        NotSpecified,
        [EnumMember(Value = "AS2")]
        AS2,
        [EnumMember(Value = "X12")]
        X12,
        [EnumMember(Value = "Edifact")]
        Edifact
    }
    internal static class AgreementTypeEnumExtension
    {
        internal static string ToSerializedValue(this AgreementType? value)
        {
            return value == null ? null : ((AgreementType)value).ToSerializedValue();
        }

        internal static string ToSerializedValue(this AgreementType value)
        {
            switch( value )
            {
                case AgreementType.NotSpecified:
                    return "NotSpecified";
                case AgreementType.AS2:
                    return "AS2";
                case AgreementType.X12:
                    return "X12";
                case AgreementType.Edifact:
                    return "Edifact";
            }
            return null;
        }

        internal static AgreementType? ParseAgreementType(this string value)
        {
            switch( value )
            {
                case "NotSpecified":
                    return AgreementType.NotSpecified;
                case "AS2":
                    return AgreementType.AS2;
                case "X12":
                    return AgreementType.X12;
                case "Edifact":
                    return AgreementType.Edifact;
            }
            return null;
        }
    }
}


text:
<!DOCTYPE html>

  <title>smoax - mocha tests</title>
  <link href="../node_modules/mocha/mocha.css" rel="stylesheet" />


text:
{% extends "cradmin_legacy/viewhelpers/listbuilderview/filterlist-right.django.html" %}

{% load devilry_account_tags %}
{% load crispy_forms_tags %}
{% load i18n %}
{% load cradmin_legacy_tags %}

{% block title %}
    {{ request.cradmin_role.get_path }}
{% endblock title %}

{% block pageheader-inner %}

{{ headline }}

{% endblock pageheader-inner %}

{% block listbuilderview_buttons %}

            {% trans "Create new status" %}

{% endblock listbuilderview_buttons %}

{% block content %}
    {{ block.super }}

{% endblock content %}


text:
namespace media {
namespace cast {

// RawEventSubscriber implementation that records all incoming raw events
// in std::vector's.
// The user of this class can call the GetXXXEventsAndReset functions to get
// list of events that have acccumulated since last inovcation.
class SimpleEventSubscriber : public RawEventSubscriber {
 public:
  SimpleEventSubscriber();

  ~SimpleEventSubscriber() final;

  // RawEventSubscriber implementations.
  void OnReceiveFrameEvent(const FrameEvent& frame_event) final;
  void OnReceivePacketEvent(const PacketEvent& packet_event) final;

  // Assigns frame events received so far to |frame_events| and clears them
  // from this object.
  void GetFrameEventsAndReset(std::vector<FrameEvent>* frame_events);

  // Assigns packet events received so far to |packet_events| and clears them
  // from this object.
  void GetPacketEventsAndReset(std::vector<PacketEvent>* packet_events);

 private:
  std::vector<FrameEvent> frame_events_;
  std::vector<PacketEvent> packet_events_;

  // All functions must be called on the main thread.
  base::ThreadChecker thread_checker_;

  DISALLOW_COPY_AND_ASSIGN(SimpleEventSubscriber);
};

}  // namespace cast
}  // namespace media

#endif  // MEDIA_CAST_LOGGING_SIMPLE_EVENT_SUBSCRIBER_H_


text:
<!--
1. Please check the Contributing Guidelines: https://github.com/frqnck/apix-cache/blob/master/.github/CONTRIBUTING.md
2. Fill out the whole template so we have a good overview on the issue
3. Do not remove any section of the template. If something is not applicable leave it empty but leave it in the PR
-->

## What did you implement:

**Implementing Issue:** #1234

<!-- Briefly describe the feature if no issue exists for this PR. -->

## How did you implement it:

<!-- Please briefly describe your implementation. -->

## How can we verify it:

<!-- Please provide any applicable commands or other resources to make it easy for us to verify this works. -->

## Done and todos:

<!-- Please tick with [x] as appropriate. -->

- [ ] Write unit tests,
- [ ] Write documentation,
- [ ] Fix linting errors,
- [ ] Make sure code coverage hasn't dropped,
- [ ] Leave a comment that this is ready for review once you've finished the implementation.


text:
from urllib.parse import quote_plus

import sublime
import sublime_plugin

from .base import BaseBlame
from .templates import blame_phantom_css, blame_phantom_html_template

class Blame(BaseBlame, sublime_plugin.TextCommand):

    # Overrides (TextCommand) ----------------------------------------------------------

    def __init__(self, view):
        super().__init__(view)
        self.phantom_set = sublime.PhantomSet(view, self.phantom_set_key())

    def run(self, edit, prevving=False, fixed_row_num=None, sha_skip_list=[]):
        if not self.has_suitable_view():
            self.tell_user_to_save()
            return

        phantoms = []

        if prevving:
            # We'll be getting blame information for the line whose existing phantom's
            # [Prev] button was clicked, regardless of where the text cursor(s)
            # currently are.
            relevant_regions = [sublime.Region(self.view.text_point(fixed_row_num, 0))]
        else:
            # We'll be getting blame information for the lines where text cursor(s)
            # currently are.
            relevant_regions = self.view.sel()

        for region in relevant_regions:
            line_region = self.view.line(region)

            # When this Command is ran for a line with a phantom already visible, we
            # erase the phantom (i.e. toggle it). But if the reason this Command is
            # being ran is because the user is clicking the [Prev] button, just erasing
            # the existing phantom is not sufficient, because we need to then display
            # another phantom with updated content.
            if self.phantom_exists_for_region(line_region) and not prevving:
                continue

            row_num, _ = self.view.rowcol(region.begin())
            line_num = row_num + 1

            full_path = self.view.file_name()

            try:
                blame_output = self.get_blame_text(
                    full_path, line_num=line_num, sha_skip_list=sha_skip_list
                )
            except Exception as e:
                self.communicate_error(e)
                return

            blame = self.parse_line(blame_output)
            if not blame:
                self.communicate_error(
                    "Failed to parse anything for {0}. Has git's output format changed?".format(
                        self.__class__.__name__
                    )
                )
                return
            sha = blame["sha"]
            sha_normalised = blame["sha_normalised"]
            author = blame["author"]
            date = blame["date"]
            time = blame["time"]

            if sha_skip_list:
                recently_skipped_sha = sha_skip_list[-1]
                if sha_normalised == recently_skipped_sha:
                    sublime.message_dialog(
                        "No earlier commits affected line {0}".format(line_num)
                    )
                    return

            phantoms.append(
                sublime.Phantom(
                    line_region,
                    blame_phantom_html_template.format(
                        css=blame_phantom_css,
                        sha=sha,
                        sha_not_latest_indicator=" *" if sha_skip_list else "",
                        author=author,
                        date=date,
                        time=time,
                        qs_row_num_val=quote_plus(str(row_num)),
                        qs_sha_val=quote_plus(sha_normalised),
                        # Querystrings can contain the same key multiple times. We use that
                        # functionality to accumulate a list of SHAs to skip over when
                        # a [Prev] button has been clicked multiple times.
                        qs_skip_keyvals="&".join(
                            [
                                "skip={0}".format(quote_plus(skipee))
                                for skipee in sha_skip_list
                            ]
                        ),
                    ),
                    sublime.LAYOUT_BLOCK,
                    self.handle_phantom_button,
                )
            )

        self.phantom_set.update(phantoms)

    # Overrides (BaseBlame) ------------------------------------------------------------

    def _view(self):
        return self.view

    def close_by_user_request(self):
        self.phantom_set.update([])

    def extra_cli_args(self, line_num, sha_skip_list):
        args = ["-L", "{0},{0}".format(line_num)]
        for skipped_sha in sha_skip_list:
            args.extend(["--ignore-rev", skipped_sha])
        return args

    def rerun(self, **kwargs):
        self.run(None, **kwargs)

    # Overrides end --------------------------------------------------------------------

    def phantom_exists_for_region(self, region):
        return any(p.region == region for p in self.phantom_set.phantoms)

class BlameInsertCommitDescription(sublime_plugin.TextCommand):

    # Overrides begin ------------------------------------------------------------------

    def run(self, edit, desc, scratch_view_name):
        view = self.view
        view.set_scratch(True)
        view.assign_syntax("Packages/Diff/Diff.sublime-syntax")
        view.insert(edit, 0, desc)
        view.set_name(scratch_view_name)
        view.set_read_only(True)

    # Overrides end --------------------------------------------------------------------


text:
package com.jeesms.annotation.validator;

import com.jeesms.validator.StatusValidator;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * Created by LiuXunming on 2014-08-27.
 * 状态注解
 */
@Constraint(validatedBy = {StatusValidator.class})
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface IsStatus {
    String value() default "1";

    String message() default "{com.jeesms.validation.status.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}


text:
using System;
using System.Collections.Generic;

namespace Pegasus.Web.Models
{
    public class TripRequestModel
    {
        public string FromCity { get; set; }
        public string ToCity { get; set; }
        public DateTime DepartureTime { get; set; }
        public DateTime ArrivalTime { get; set; }
        public string VehicleNumber { get; set; }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Min filmsamling</title>

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

Min filmsamling

Detta är ett exempel på ett RESTful API för min låtsatsfilmsamling! =) Detta kan man göra:

                     URL
                     HTTP Metod
                     Operation

                    /movies
                    GET
                    Returnerar alla filmer

                    /movies/:id
                    GET
                    Returnerar filmen med id :id

                    /movies
                    POST
                    Lägger till en ny film och returnerar den tillagda filmen

                    /movies/:id
                    PUT
                    Uppdaterar filmen med id :id

                    /movies/:id
                    DELETE
                    Raderar filmen med id :id

Genom att lägga till attributet &format=json så returneras alltid JSON-data, t.ex.

             /movies?format=json

             eller genom att lägga till &format=xml så returneras alltid XML-data., t.ex.

             /movies?format=xml
Annars vid GET-metoder returneras en webbsida med resultaten, t.ex.

             /movies

Exempelanvändning av API:t

          <form method="post" action="/movies" data-adress="/movies">
              <fieldset>
                  <legend>Skapa en ny film</legend>

                    Titel
                    <input type="text" class="form-control" id="title" name="title" placeholder="Titel på film" required>

                    Genre
                    <input type="text" class="form-control" id="genre" name="genre" placeholder="Genre på film" required>

                    Speltid
                    <input type="number" class="form-control" id="length" name="length" placeholder="Speltid på film" required>

                    Bild
                    <input type="url" class="form-control" id="image" name="image" placeholder="Länk till cover för film" required>

                    Länk till IMDB
                    <input type="url" class="form-control" id="imdb" name="imdb" placeholder="Länk till filem på IMDB" required>

                    Format (som returneras)
                    <select class="form-control format">
                        <option value="json">JSON</option>
                        <option value="xml">XML</option>
                    </select>

                  <input type="submit" class="btn btn-success" value="Spara film">
              </fieldset>
          </form>

          <form method="post" action="/movies/<?php echo $movie['id']; ?>" data-adress="/movies/<?php echo $movie['id']; ?>">
              <input type="hidden" name="_METHOD" value="PUT"/>
              <fieldset>
                  <legend>Redigera den senast inlagda filmen</legend>

                    Titel
                    <input type="text" class="form-control" id="title" name="title" placeholder="Titel på film" required value="<?php echo $movie['title']; ?>">

                    Genre
                    <input type="text" class="form-control" id="genre" name="genre" placeholder="Genre på film" required value="<?php echo $movie['genre']; ?>">

                    Speltid
                    <input type="number" class="form-control" id="length" name="length" placeholder="Speltid på film" required value="<?php echo $movie['length']; ?>">

                    Bild
                    <input type="url" class="form-control" id="image" name="image" placeholder="Länk till cover för film" required value="<?php echo $movie['image']; ?>">

                    Länk till IMDB
                    <input type="url" class="form-control" id="imdb" name="imdb" placeholder="Länk till filem på IMDB" required value="<?php echo $movie['imdb']; ?>">

                    Format (som returneras)
                    <select class="form-control format">
                        <option value="json">JSON</option>
                        <option value="xml">XML</option>
                    </select>

                  <input type="submit" class="btn btn-success" value="Spara film">
              </fieldset>
          </form>

Radera en film

				Id
				Title
				Genre
				Length
				IMDB
				Radera film
				JSON/XML

			<?php
			foreach($movies as $movie){
				echo "
";
				echo "".$movie['id']."	";
				echo "".$movie['title']."	";
				echo "".$movie['genre']."	";
				echo "".$movie['length']."	";
				echo "IMDB	";
                echo "
                        <form action='/movies/".$movie['id']."?format=json' method='post'>
                            <input type='hidden' name='_METHOD' value='delete'>
                            <input type='submit' class='btn btn-danger' value='Radera (JSON)'>
                        </form>
                    	";
                echo "
                        <form action='/movies/".$movie['id']."?format=xml' method='post'>
                            <input type='hidden' name='_METHOD' value='delete'>
                            <input type='submit' class='btn btn-danger' value='Radera (XML)'>
                        </form>
                    	";
				echo "
";
			}
			?>


text:
'use strict'

const wrap = require('co').wrap
const reader = require('..')
const fs = require('promise.ify').all(require('fs-extra'))

// fixture
const filename = __dirname + '/fixtures/eason-k-king.mp3'

describe('It works', function() {
  it('simple', wrap(function*() {
    const info = yield reader(filename)
    info.singer.should.match(/陈奕迅/)
    info.title.should.match(/K歌之王/)
    info.album.should.match(/打得火热/)
  }))

  it('fd supported', wrap(function*() {
    const fd = yield fs.openAsync(filename, 'r')
    const info = yield reader(fd)
    info.singer.should.match(/陈奕迅/)
    info.title.should.match(/K歌之王/)
    info.album.should.match(/打得火热/)
  }))
})


text:
package postgresweb.services

import io.circe._
import io.circe.parser._
import org.scalajs.dom.ext.Ajax
import postgresweb.configs.Config

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.scalajs.js

/**
  * Created by andreaminetti on 23/02/16.
  */
object HttpClient {

  def postJson[T](url:String, data:String)(implicit d:Decoder[T]):Future[T] =
    Ajax.post(url, data,headers = Map(Config.auth, "Content-Type" -> "application/json")).map(xhr => decode[T](xhr.responseText).toOption.get)

  def putJson[T](url:String, data:String)(implicit d:Decoder[T]):Future[T] =
    Ajax.put(url, data,headers = Map(Config.auth, "Content-Type" -> "application/json")).map(xhr => decode[T](xhr.responseText).toOption.get)

  def get[T](url:String)(implicit d:Decoder[T]):Future[T] = Ajax.get(url,headers = Map(Config.auth)).map{xhr =>
    decode[T](xhr.responseText).toOption.get
  }

  def getString(url:String):Future[String] = Ajax.get(url,headers = Map(Config.auth)).map{xhr =>
    xhr.responseText
  }

  def getJs(url:String):Future[js.Any] = Ajax.get(url,headers = Map(Config.auth)).map{xhr =>
    js.JSON.parse(xhr.responseText)
  }

}