text:
<?php

namespace Gishiki\tests\Security\Hashing;

use PHPUnit\Framework\TestCase;

use Gishiki\Security\Hashing\HashingException;
use Gishiki\Security\Hashing\Algorithm;

/**
 * Tests for the Algorithm class.
 *
 * @author Benato Denis <benato.denis96@gmail.com>
 */
class AlgorithmTest extends TestCase
{
    public function testInvalidMessageForOpensslHash()
    {
        $this->expectException(\InvalidArgumentException::class);

        //test hash compatibility
        Algorithm::opensslHash('', Algorithm::SHA512);
    }

    public function testInvalidMessageForRot13Hash()
    {
        $this->expectException(\InvalidArgumentException::class);

        //test hash compatibility
        Algorithm::rot13Hash('');
    }

    public function testInvalidMessageForBcryptHash()
    {
        $this->expectException(\InvalidArgumentException::class);

        Algorithm::bcryptHash('');
    }

    public function testInvalidMessageForPbkdf2Hash()
    {
        $this->expectException(\InvalidArgumentException::class);

        Algorithm::pbkdf2Hash('');
    }

    public function testInvalidMessageForOpensslVerify()
    {
        $this->expectException(\InvalidArgumentException::class);

        //test hash compatibility
        Algorithm::opensslVerify('', ':)', Algorithm::SHA512);
    }

    public function testInvalidMessageForRot13Verify()
    {
        $this->expectException(\InvalidArgumentException::class);

        //test hash compatibility
        Algorithm::rot13Verify('', ':)');
    }

    public function testInvalidMessageForBcryptVerify()
    {
        $this->expectException(\InvalidArgumentException::class);

        //test hash compatibility
        Algorithm::bcryptVerify('', ':)');
    }

    public function testInvalidMessageForPbkdf2Verify()
    {
        $this->expectException(\InvalidArgumentException::class);

        //test hash compatibility
        Algorithm::pbkdf2Verify(9, ':((');
    }

    public function testInvalidMessageDigestForOpensslVerify()
    {
        $this->expectException(\InvalidArgumentException::class);

        //test hash compatibility
        Algorithm::opensslVerify('My message', '', Algorithm::SHA512);
    }

    public function testInvalidMessageDigestForRot13Verify()
    {
        $this->expectException(\InvalidArgumentException::class);

        //test hash compatibility
        Algorithm::rot13Verify('My message', '');
    }

    public function testInvalidMessageDigestForBcryptVerify()
    {
        $this->expectException(\InvalidArgumentException::class);

        //test hash compatibility
        Algorithm::bcryptVerify('My message', '');
    }

    public function testInvalidMessageDigestForPbkdf2Verify()
    {
        $this->expectException(\InvalidArgumentException::class);

        //test hash compatibility
        Algorithm::pbkdf2Verify('My message', '');
    }

    public function testOpensslVerify()
    {
        $random = bin2hex(openssl_random_pseudo_bytes(25));

        //test hash compatibility
        $hash = Algorithm::opensslHash($random, Algorithm::SHA512);
        $this->assertTrue(Algorithm::opensslVerify($random, $hash, Algorithm::SHA512));

        $this->assertFalse(Algorithm::opensslVerify($random, 'any other thing', Algorithm::SHA512));
    }

    public function testRot13Verify()
    {
        $random = bin2hex(openssl_random_pseudo_bytes(25));

        //test hash compatibility
        $hash = Algorithm::rot13Hash($random);
        $this->assertTrue(Algorithm::rot13Verify($random, $hash));

        $this->assertFalse(Algorithm::rot13Verify($random, 'any other thing'));
    }

    public function testBCryptVerify()
    {
        $random = bin2hex(openssl_random_pseudo_bytes(25));

        //test hash compatibility
        $hash = Algorithm::bcryptHash($random);
        $this->assertTrue(Algorithm::bcryptVerify($random, $hash));

        $this->assertFalse(Algorithm::bcryptVerify($random, 'any other thing'));
    }

    public function testROT13()
    {
        $message = 'this is a small>example<to/test rot-13';
        $message_rot13 = 'guvf vf n fznyy>rknzcyr<gb/grfg ebg-13';

        //test hash compatibility
        $rot_ed = Algorithm::rot13Hash($message);
        $this->assertEquals($message_rot13, $rot_ed);
        $this->assertEquals($message, Algorithm::rot13Hash($rot_ed, Algorithm::ROT13));

        $this->assertTrue(Algorithm::rot13Verify($message, $rot_ed));
    }

    public function testPbkdf2()
    {
        $message = 'this is a small>example<to/test pbkdf2';

        //test hash compatibility
        $hashed = Algorithm::pbkdf2Hash($message);

        $this->assertTrue(Algorithm::pbkdf2Verify($message, $hashed));
    }

    public function testHashCompatibility()
    {
        $message = openssl_random_pseudo_bytes(128);

        //test hash compatibility
        $this->assertEquals(md5($message), Algorithm::opensslHash($message, Algorithm::MD5));
        $this->assertEquals(sha1($message), Algorithm::opensslHash($message, Algorithm::SHA1));
    }

    public function testBadHashPbkdf2()
    {
        $this->expectException(HashingException::class);

        Algorithm::pbkdf2('password', 'salt', 512, 3, 'bad-algo');
    }

    public function testBadAlgorithmPbkdf2()
    {
        $this->expectException(\InvalidArgumentException::class);

        Algorithm::pbkdf2('message', 'salt', 512, 3, '');
    }

    public function testBadCountHashPbkdf2()
    {
        $this->expectException(\InvalidArgumentException::class);

        Algorithm::pbkdf2('password', 'salt', 512, '3', Algorithm::SHA256);
    }

    public function testBadKeylengthHashPbkdf2()
    {
        $this->expectException(\InvalidArgumentException::class);

        Algorithm::pbkdf2('password', 'salt', '512', 3, Algorithm::SHA256);
    }

    public function testHashPbkdf2()
    {
        //test vectors from https://www.ietf.org/rfc/rfc6070.txt
        $testVector = [
            ['password', 'salt', 20, 1, 'SHA1'],
            ['password', 'salt', 20, 2, 'SHA1'],
            ['password', 'salt', 20, 4096, 'SHA1'],
            ['password', 'salt', 20, 16777216, 'SHA1'],
            ['passwordPASSWORDpassword', 'saltSALTsaltSALTsaltSALTsaltSALTsalt', 25, 4096, 'SHA1'],
            ["pass\0word", "sa\0lt", 16, 4096, 'SHA1'],
            ];
        $resultsVector = [
            '0c60c80f961f0e71f3a9b524af6012062fe037a6',
            'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957',
            '4b007901b765489abead49d926f721d065a429c1',
            'eefe3d61cd4da4e4e9945b3d6ba2158c2634e984',
            '3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038',
            '56fa6aa75548099dcc37d7f03425e0c3',
            ];

        foreach ($testVector as $testIndex => $testValue) {
            //run the vector test allowing openssl hashing
            $this->assertEquals($resultsVector[$testIndex], Algorithm::pbkdf2($testValue[0], $testValue[1], $testValue[2], $testValue[3], $testValue[4], false, false));
        }
    }

    public function testSlowHashPbkdf2()
    {
        //test vectors from https://www.ietf.org/rfc/rfc6070.txt
        $testVector = [
            ['password', 'salt', 20, 1, 'SHA1'],
            ['password', 'salt', 20, 2, 'SHA1'],
            ['password', 'salt', 20, 4096, 'SHA1'],
            ['password', 'salt', 20, 16777216, 'SHA1'],
            ['passwordPASSWORDpassword', 'saltSALTsaltSALTsaltSALTsaltSALTsalt', 25, 4096, 'SHA1'],
            ["pass\0word", "sa\0lt", 16, 4096, 'SHA1'],
            ];
        $resultsVector = [
            '0c60c80f961f0e71f3a9b524af6012062fe037a6',
            'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957',
            '4b007901b765489abead49d926f721d065a429c1',
            'eefe3d61cd4da4e4e9945b3d6ba2158c2634e984',
            '3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038',
            '56fa6aa75548099dcc37d7f03425e0c3',
            ];

        foreach ($testVector as $testIndex => $testValue) {
            //run the vector test forcing the hash library hashing
            $this->assertEquals($resultsVector[$testIndex], Algorithm::pbkdf2($testValue[0], $testValue[1], $testValue[2], $testValue[3], $testValue[4], false, true));
        }
    }
}


text:
package com.java.offer;

public class GetNumberOfKTest {

	public static int getNumberOfK(int[] numbers, int k){

		if(numbers == null || numbers.length <= 0){
			return 0;
		}

		int first = getFirstK(numbers, k, 0, numbers.length - 1);
		int last = getLastK(numbers, k, 0, numbers.length - 1);

		if(first > -1 && last > -1){
			return last - first + 1;
		}
		return 0;

	}
	private static int getFirstK(int[] numbers, int k, int start, int end) {

		int middle = (start + end) / 2;

		if(numbers[middle] == k){
			if((middle > start && numbers[middle - 1] != k ) || middle == start){
				return middle;
			}
			else{
				end = middle - 1;
			}

		}else if(numbers[middle] < k){
			start = middle + 1;
		}else{
			end = middle - 1;
		}
		return getFirstK(numbers, k, start, end);
	}
	private static int getLastK(int[] numbers, int k, int start, int end) {

		int middle = (start + end) / 2;
		if(numbers[middle] == k){
			if((middle < end && numbers[middle] != k) || middle == end){
				return middle;
			}else{
				start = middle + 1;
			}
		}else if(numbers[middle] > k){
			end = middle - 1;
		}else{
			start = middle + 1;
		}

		return getLastK(numbers, k, start, end);
	}
	public static void main(String[] args) {

		int[] numbers = new int[]{1, 2, 3, 3, 3, 3, 4, 5};
		System.out.println(getNumberOfK(numbers, 3));

	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Doctrine\ORM\Query\AST;

class PartialObjectExpression extends Node
{
    public $identificationVariable;
    public $partialFieldSet;

    public function __construct($identificationVariable, array $partialFieldSet)
    {
        $this->identificationVariable = $identificationVariable;
        $this->partialFieldSet = $partialFieldSet;
    }
}


text:
const request = require('request');

exports.regex = /[Cc]ountdown(.*)/;
exports.example = '/micah countdown <serie>: Muestra el tiempo faltante para el próximo capítulo de <serie>.'

exports.onMsg = function(bot, msg, match) {
  const chatId = msg.chat.id;

  const search = escape(match[1].toLowerCase());
  if (search === '%20help' || search === 'undefined' || !search) {
    bot.sendMessage(chatId, 'Tení que darme el nombre de la serie po! 🐣 (ej: /micah countdown mr robot)\n');
    return false;
  }

  // Send request to the tvmaze search API
  request("http://api.tvmaze.com/search/shows?q=" + search, (err, res, body) => {
    if (err || res.statusCode !== 200) {
      bot.sendMessage(chatId, 'Oops! '+err);
      return false;
    }

    const data = JSON.parse(body);

    if (data.length === 0) {
      bot.sendMessage(chatId, '¿Seguro que ese es el nombre? ¡Tienes que elegir una serie que exista! 🐣');
    }
    else {

      const show_name = data[0].show.name;
      const ep_link = data[0].show._links.nextepisode;

      if (!ep_link) {
        bot.sendMessage(chatId, show_name+' no tiene más fechas! 😢');
      }
      else {
        // Send request to the tvmaze episode API
        request(ep_link.href, (err, res, body) => {
          if (err || res.statusCode !== 200) {
            bot.sendMessage(chatId, 'Oops! Status code: '+res.statusCode);
          }

          const data = JSON.parse(body);

          if (!data) {
            bot.sendMessage(chatId, '¿Seguro que ese es el nombre? ¡Tienes que elegir una serie que exista! 🐣');
          }
          else {
            const ep_name = data.name;
            const ep_date = new Date(data.airstamp);
            const ep_tag = +data.season+"x"+data.number;

            const distance = ep_date - new Date();
            const _second = 1000;
            const _minute = _second * 60;
            const _hour = _minute * 60;
            const _day = _hour * 24;

            const days = Math.floor(distance / _day);
            const hours = Math.floor((distance % _day) / _hour);
            const minutes = Math.floor((distance % _hour) / _minute);
            const seconds = Math.floor((distance % _minute) / _second);
            const count = days+"d "+hours+"h "+minutes+"m y "+seconds+"s 🍿";
            const date_options = {
              year: 'numeric', month: 'numeric', day: 'numeric',
              hour: 'numeric', minute: 'numeric',
              hour12: false, timeZone: 'America/Santiago'
            }
            const result = show_name+" ("+ep_tag+": "+ep_name+") sale el "+new Intl.DateTimeFormat('es-CL', date_options).format(ep_date)+" y quedan "+count;

            bot.sendMessage(chatId, result);
          }
        });
      }
    }
  });
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Omphalina dawsonii Murrill

### Remarks
null


text:
require("deal")

if CardDraftGameMode == nil then
   CardDraftGameMode = class({})
end

function Precache(context)
   PrecacheResource("model_folder", "models/courier/", context)
end

function Activate()
   GameRules.CardDraft = CardDraftGameMode()
   GameRules.CardDraft:InitGameMode()
end

function CardDraftGameMode:InitGameMode()
   ListenToGameEvent("game_rules_state_change", self.StateChange, nil)
   ListenToGameEvent('player_connect_full', self.OnConnectFull, nil)
end

function CardDraftGameMode:OnConnectFull()
   -- Force all players to be Abbadon
   GameRules:GetGameModeEntity():SetCustomGameForceHero("npc_dota_hero_abaddon")
end

function CardDraftGameMode:StateChange()
   local state = GameRules:State_Get()

   if state == DOTA_GAMERULES_STATE_HERO_SELECTION then
      deal()

   elseif state == DOTA_GAMERULES_STATE_PRE_GAME then
      draft()
   end
end


text:
var queryString = require('query-string')
var raw = require('choo/html/raw')
var html = require('choo/html')
var xtend = require('xtend')
var path = require('path')

var blueprintSettings = require('../blueprints/page-header.json')
var blueprintDefault = require('../blueprints/default')
var methodsPage = require('../lib/page')
var fields = require('./fields')

module.exports = pageHeader

function pageHeader (state, emit) {
  var search = queryString.parse(location.search)
  var blueprint = getParentBlueprint()
  var draftPage = getDraftPage()
  var views = methodsPage.getViews({
    blueprints: state.site.blueprints,
    blueprint: blueprint
  })

  // views
  if (views) {
    blueprintSettings.fields.view.options = views
  }

  return html`

          ←

          ${state.page.title || state.page.name || raw(' ')}

        ${elMeta()}

      ${search.settings && state.page.url && state.page.url ? PageSettings() : ''}

  `

  function PageSettings () {
    return html`

        ${fields(state, emit, {
          oninput: handleFieldUpdate,
          blueprint: blueprintSettings,
          values: state.page,
        })}

            Delete

          Delete Page

    `
  }

  function elMeta () {
    var settingsUrl = search.settings ? unescape(queryString.stringify({ url: state.page.url })) : unescape(queryString.stringify(xtend(state.query, { settings: 'active' })))
    var settingsClass = search.settings ? 'fc-fg' : 'fc-bg25 fch-fg'
    return html`

          Settings

          Open

    `
  }

  function getDraftPage () {
    return state.enoki && state.page && state.enoki.changes[state.page.url]
  }

  function getParentBlueprint () {
    if (!state.page || !state.site.loaded) return { }
    try {
      var parent = path.join(state.page.url, '../').replace(/\/$/, '')
      var parentState = state.content[parent]

      return (
        state.site.blueprints[parentState.view] ||
        state.site.blueprints.default ||
        blueprintDefault
      )
    } catch (err) {
      return blueprintDefault
    }
  }

  function handleFieldUpdate (key, data) {
    emit(state.events.ENOKI_UPDATE, {
      path: state.page.path,
      url: state.page.url,
      data: { [key]: data }
    })
  }

  function handleRemovePage () {
    emit(state.events.ENOKI_REMOVE, {
      confirm: true,
      title: state.page.title,
      path: state.page.path,
      url: state.page.url
    })
  }
}


text:
/**
  * © 2019 Refinitiv. All Rights Reserved.
  *
  * 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.
  */
package security

/**
  * Created by yaakov on 6/14/15.
  */
sealed trait Operation
case object Admin extends Operation
case object Overwrite extends Operation
case object PriorityWrite extends Operation

object Operation {
  def unapply(op: String): Option[Operation] = {
    op match {
      case "Admin"         => Some(Admin)
      case "Overwrite"     => Some(Overwrite)
      case "PriorityWrite" => Some(PriorityWrite)
      case _               => None
    }
  }
}


text:
require_relative "card.rb" rescue require "card_deck"
class Hand # The player
	attr_accessor :cards # The cards in the hand
	MDHV = 16 # Maximum Dealer Hit Value; If the dealer's hand is valued more than this number, he will stay.
	def self.deck=(deck); @@deck = deck.cards.shuffle; end # Set which deck the game is using. Also shuffles the deck.

	def self.deck; @@deck; end # The deck the game is using
	def bust?; value > 21; end # Returns true if the value is greater than 21.
	def blackjack?; value == 21 && @cards.length == 2; end # Returns true if you have blackjack.
	def initialize(cards=[@@deck.shift, @@deck.shift])
		@cards = cards
	end
	def view; @cards.each {|card| "#{card.abbr}\t"}; end # The view of the cards
	def hit; @cards.push @@deck.shift; end # Add a card to @cards from @@deck
	def value # The value of the cards in @cards
		v, aces = 0, 0
		for card in @cards
			v += card.value
			aces += 1 if card.num == "Ace"
		end
		while v > 21 && aces > 0
			v -= 10
			aces -= 1
		end
		return v
	end
end


text:
/

    /// This function internally calls registerResource API.
    void createResource()
    {
        //URI of the resource
        std::string resourceURI = m_lightUri;
        //resource type name. In this case, it is light
        std::string resourceTypeName = "core.light";
        // resource interface.
        std::string resourceInterface = DEFAULT_INTERFACE;

        // OCResourceProperty is defined ocstack.h
        uint8_t resourceProperty;
        if(isSecure)
        {
            resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE;
        }
        else
        {
            resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
        }
        EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1);

        // This will internally create and register the resource.
        OCStackResult result = OCPlatform::registerResource(
                                    m_resourceHandle, resourceURI, resourceTypeName,
                                    resourceInterface, cb, resourceProperty);

        if (OC_STACK_OK != result)
        {
            cout << "Resource creation was unsuccessful\n";
        }
    }

    OCStackResult createResource1()
    {
        // URI of the resource
        std::string resourceURI = "/a/light1";
        // resource type name. In this case, it is light
        std::string resourceTypeName = "core.light";
        // resource interface.
        std::string resourceInterface = DEFAULT_INTERFACE;

        // OCResourceProperty is defined ocstack.h
        uint8_t resourceProperty;
        if(isSecure)
        {
            resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE;
        }
        else
        {
            resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
        }
        EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1);

        OCResourceHandle resHandle;

        // This will internally create and register the resource.
        OCStackResult result = OCPlatform::registerResource(
                                    resHandle, resourceURI, resourceTypeName,
                                    resourceInterface, cb, resourceProperty);

        if (OC_STACK_OK != result)
        {
            cout << "Resource creation was unsuccessful\n";
        }

        return result;
    }

    OCResourceHandle getHandle()
    {
        return m_resourceHandle;
    }

    // Puts representation.
    // Gets values from the representation and
    // updates the internal state
    void put(OCRepresentation& rep)
    {
        try {
            if (rep.getValue("state", m_state))
            {
                cout << "\t\t\t\t" << "state: " << m_state << endl;
            }
            else
            {
                cout << "\t\t\t\t" << "state not found in the representation" << endl;
            }

            if (rep.getValue("power", m_power))
            {
                cout << "\t\t\t\t" << "power: " << m_power << endl;
            }
            else
            {
                cout << "\t\t\t\t" << "power not found in the representation" << endl;
            }
        }
        catch (exception& e)
        {
            cout << e.what() << endl;
        }

    }

    // Post representation.
    // Post can create new resource or simply act like put.
    // Gets values from the representation and
    // updates the internal state
    OCRepresentation post(OCRepresentation& rep)
    {
        static int first = 1;

        // for the first time it tries to create a resource
        if(first)
        {
            first = 0;

            if(OC_STACK_OK == createResource1())
            {
                OCRepresentation rep1;
                rep1.setValue("createduri", std::string("/a/light1"));

                return rep1;
            }
        }

        // from second time onwards it just puts
        put(rep);
        return get();
    }

    // gets the updated representation.
    // Updates the representation with latest internal state before
    // sending out.
    OCRepresentation get()
    {
        m_lightRep.setValue("state", m_state);
        m_lightRep.setValue("power", m_power);

        return m_lightRep;
    }

    void addType(const std::string& type) const
    {
        OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
        if (OC_STACK_OK != result)
        {
            cout << "Binding TypeName to Resource was unsuccessful\n";
        }
    }

    void addInterface(const std::string& interface) const
    {
        OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
        if (OC_STACK_OK != result)
        {
            cout << "Binding TypeName to Resource was unsuccessful\n";
        }
    }

private:
// This is just a sample implementation of entity handler.
// Entity handler can be implemented in several ways by the manufacturer
OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
{
    cout << "\tIn Server CPP entity handler:\n";
    OCEntityHandlerResult ehResult = OC_EH_ERROR;
    if(request)
    {
        // Get the request type and request flag
        std::string requestType = request->getRequestType();
        int requestFlag = request->getRequestHandlerFlag();

        if(requestFlag & RequestHandlerFlag::RequestFlag)
        {
            cout << "\t\trequestFlag : Request\n";
            auto pResponse = std::make_shared<OC::OCResourceResponse>();
            pResponse->setRequestHandle(request->getRequestHandle());
            pResponse->setResourceHandle(request->getResourceHandle());

            // Check for query params (if any)
            QueryParamsMap queries = request->getQueryParameters();

            if (!queries.empty())
            {
                std::cout << "\nQuery processing upto entityHandler" << std::endl;
            }
            for (auto it : queries)
            {
                std::cout << "Query key: " << it.first << " value : " << it.second
                        << std:: endl;
            }

            // If the request type is GET
            if(requestType == "GET")
            {
                cout << "\t\t\trequestType : GET\n";
                if(isSlowResponse) // Slow response case
                {
                    static int startedThread = 0;
                    if(!startedThread)
                    {
                        std::thread t(handleSlowResponse, (void *)this, request);
                        startedThread = 1;
                        t.detach();
                    }
                    ehResult = OC_EH_SLOW;
                }
                else // normal response case.
                {
                    pResponse->setErrorCode(200);
                    pResponse->setResponseResult(OC_EH_OK);
                    pResponse->setResourceRepresentation(get());
                    if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
                    {
                        ehResult = OC_EH_OK;
                    }
                }
            }
            else if(requestType == "PUT")
            {
                cout << "\t\t\trequestType : PUT\n";
                OCRepresentation rep = request->getResourceRepresentation();

                // Do related operations related to PUT request
                // Update the lightResource
                put(rep);
                pResponse->setErrorCode(200);
                pResponse->setResponseResult(OC_EH_OK);
                pResponse->setResourceRepresentation(get());
                if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
                {
                    ehResult = OC_EH_OK;
                }
            }
            else if(requestType == "POST")
            {
                cout << "\t\t\trequestType : POST\n";

                OCRepresentation rep = request->getResourceRepresentation();

                // Do related operations related to POST request
                OCRepresentation rep_post = post(rep);
                pResponse->setResourceRepresentation(rep_post);
                pResponse->setErrorCode(200);
                if(rep_post.hasAttribute("createduri"))
                {
                    pResponse->setResponseResult(OC_EH_RESOURCE_CREATED);
                    pResponse->setNewResourceUri(rep_post.getValue<std::string>("createduri"));
                }
                else
                {
                    pResponse->setResponseResult(OC_EH_OK);
                }

                if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
                {
                    ehResult = OC_EH_OK;
                }
            }
            else if(requestType == "DELETE")
            {
                cout << "Delete request received" << endl;
            }
        }

        if(requestFlag & RequestHandlerFlag::ObserverFlag)
        {
            ObservationInfo observationInfo = request->getObservationInfo();
            if(ObserveAction::ObserveRegister == observationInfo.action)
            {
                m_interestedObservers.push_back(observationInfo.obsId);
            }
            else if(ObserveAction::ObserveUnregister == observationInfo.action)
            {
                m_interestedObservers.erase(std::remove(
                                                            m_interestedObservers.begin(),
                                                            m_interestedObservers.end(),
                                                            observationInfo.obsId),
                                                            m_interestedObservers.end());
            }

            pthread_t threadId;

            cout << "\t\trequestFlag : Observer\n";
            gObservation = 1;
            static int startedThread = 0;

            // Observation happens on a different thread in ChangeLightRepresentation function.
            // If we have not created the thread already, we will create one here.
            if(!startedThread)
            {
                pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)this);
                startedThread = 1;
            }
            ehResult = OC_EH_OK;
        }
    }
    else
    {
        std::cout << "Request invalid" << std::endl;
    }

    return ehResult;
}

};

// ChangeLightRepresentaion is an observation function,
// which notifies any changes to the resource to stack
// via notifyObservers
void * ChangeLightRepresentation (void *param)
{
    LightResource* lightPtr = (LightResource*) param;

    // This function continuously monitors for the changes
    while (1)
    {
        sleep (3);

        if (gObservation)
        {
            // If under observation if there are any changes to the light resource
            // we call notifyObservors
            //
            // For demostration we are changing the power value and notifying.
            lightPtr->m_power += 10;

            cout << "\nPower updated to : " << lightPtr->m_power << endl;
            cout << "Notifying observers with resource handle: " << lightPtr->getHandle() << endl;

            OCStackResult result = OC_STACK_OK;

            if(isListOfObservers)
            {
                std::shared_ptr<OCResourceResponse> resourceResponse =
                            {std::make_shared<OCResourceResponse>()};

                resourceResponse->setErrorCode(200);
                resourceResponse->setResourceRepresentation(lightPtr->get(), DEFAULT_INTERFACE);

                result = OCPlatform::notifyListOfObservers(  lightPtr->getHandle(),
                                                             lightPtr->m_interestedObservers,
                                                             resourceResponse);
            }
            else
            {
                result = OCPlatform::notifyAllObservers(lightPtr->getHandle());
            }

            if(OC_STACK_NO_OBSERVERS == result)
            {
                cout << "No More observers, stopping notifications" << endl;
                gObservation = 0;
            }
        }
    }

    return NULL;
}

void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest)
{
    // This function handles slow response case
    LightResource* lightPtr = (LightResource*) param;
    // Induce a case for slow response by using sleep
    std::cout << "SLOW response" << std::endl;
    sleep (10);

    auto pResponse = std::make_shared<OC::OCResourceResponse>();
    pResponse->setRequestHandle(pRequest->getRequestHandle());
    pResponse->setResourceHandle(pRequest->getResourceHandle());
    pResponse->setResourceRepresentation(lightPtr->get());
    pResponse->setErrorCode(200);
    pResponse->setResponseResult(OC_EH_OK);

    // Set the slow response flag back to false
    isSlowResponse = false;
    OCPlatform::sendResponse(pResponse);
    return NULL;
}

void PrintUsage()
{
    std::cout << std::endl;
    std::cout << "Usage : simpleserver <value>\n";
    std::cout << "    Default - Non-secure resource and notify all observers\n";
    std::cout << "    1 - Non-secure resource and notify list of observers\n\n";
    std::cout << "    2 - Secure resource and notify all observers\n";
    std::cout << "    3 - Secure resource and notify list of observers\n\n";
    std::cout << "    4 - Non-secure resource, GET slow response, notify all observers\n";
}

static FILE* client_open(const char* /*path*/, const char *mode)
{
    return fopen("./oic_svr_db_server.json", mode);
}

int main(int argc, char* argv[])
{
    PrintUsage();
    OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };

    if (argc == 1)
    {
        isListOfObservers = false;
        isSecure = false;
    }
    else if (argc == 2)
    {
        int value = atoi(argv[1]);
        switch (value)
        {
            case 1:
                isListOfObservers = true;
                isSecure = false;
                break;
            case 2:
                isListOfObservers = false;
                isSecure = true;
                break;
            case 3:
                isListOfObservers = true;
                isSecure = true;
                break;
            case 4:
                isSlowResponse = true;
                break;
            default:
                break;
       }
     }
    else
    {
        return -1;
    }

    // Create PlatformConfig object
    PlatformConfig cfg {
        OC::ServiceType::InProc,
        OC::ModeType::Server,
        "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
        0,         // Uses randomly available port
        OC::QualityOfService::LowQos,
        &ps
    };

    OCPlatform::Configure(cfg);
    try
    {
        // Create the instance of the resource class
        // (in this case instance of class 'LightResource').
        LightResource myLight;

        // Invoke createResource function of class light.
        myLight.createResource();
        std::cout << "Created resource." << std::endl;

        myLight.addType(std::string("core.brightlight"));
        myLight.addInterface(std::string(LINK_INTERFACE));
        std::cout << "Added Interface and Type" << std::endl;

        // A condition variable will free the mutex it is given, then do a non-
        // intensive block until 'notify' is called on it.  In this case, since we
        // don't ever call cv.notify, this should be a non-processor intensive version
        // of while(true);
        std::mutex blocker;
        std::condition_variable cv;
        std::unique_lock<std::mutex> lock(blocker);
        std::cout <<"Waiting" << std::endl;
        cv.wait(lock, []{return false;});
    }
    catch(OCException &e)
    {
        std::cout << "OCException in main : " << e.what() << endl;
    }

    // No explicit call to stop the platform.
    // When OCPlatform::destructor is invoked, internally we do platform cleanup

    return 0;
}


text:
<?php

namespace Cacheable;

class RobotsParts extends Model
{
	public function initialize()
	{
		$this->belongsTo('robots_id', 'Cacheable\Robots', 'id', array(
			'alias' => 'Robots'
		));
		$this->belongsTo('parts_id', 'Cacheable\Parts', 'id', array(
			'alias' => 'Parts'
		));
	}
}


text:
from importlib import import_module

import os
import sys

from setuptools import setup, find_packages
from setuptools.command.test import test

def package_env(file_name, strict=False):
    file_path = os.path.join(os.path.dirname(__file__), file_name)
    if os.path.exists(file_path) or strict:
        return open(file_path).read()
    else:
        return ''

PROJECT = 'flask_ample'

VERSION = package_env('VERSION')
URL = package_env('URL')

AUTHOR_AND_EMAIL = [v.strip('>').strip() for v \
                    in package_env('AUTHOR').split('<mailto:')]

if len(AUTHOR_AND_EMAIL) == 2:
    AUTHOR, AUTHOR_EMAIL = AUTHOR_AND_EMAIL
else:
    AUTHOR = AUTHOR_AND_EMAIL
    AUTHOR_EMAIL = ''

DESC = "basic setup of ample for flask"

class TestRunner(test):
    def run(self, *args, **kwargs):
        if self.distribution.install_requires:
            self.distribution.fetch_build_eggs(self.\
                                                distribution.install_requires)
        if self.distribution.tests_require:
            self.distribution.fetch_build_eggs(self.distribution.tests_require)
        from test import run
        run()

if __name__ == '__main__':
    setup(
        cmdclass={"test": TestRunner},
        name=PROJECT,
        version=VERSION,
        description=DESC,
        long_description=package_env('README.rst'),
        author=AUTHOR,
        author_email=AUTHOR_EMAIL,
        url=URL,
        license=package_env('LICENSE'),
        packages=['flask_ample',] + ['.'.join(('flask_ample', e)) \
                    for e in find_packages('flask_ample')],
        package_dir={
                     'flask_ample': 'flask_ample'},
        include_package_data=True,
        zip_safe=False,
        test_suite='test',
        tests_require=[],
        classifiers=[
            'Development Status :: 2 - Pre-Alpha',
            'Programming Language :: Python',
            'Programming Language :: Python :: 2.7',
        ],
    )


text:
module Genome
  module Importers
    module HingoraniCasas
      def self.source_info
        {
          base_url:           'http://stm.sciencemag.org/content/9/383/eaag1166',
          site_url:           'http://stm.sciencemag.org/content/9/383/eaag1166',
          citation:           'The druggable genome and support for target identification and validation in drug development. Finan C, Gaulton A, Kurger F, Lumbers T, Shah T, Engmann J, Galver L, Kelly R, Karlsson A, Santos R, Overington J, Hingorani A, Casas JP.   Sci. Transl. Med. 2017 Mar 29;9(383):eaag1166 PMID: 28356508.',
          source_db_version:  '31-May-2017',
          source_type_id:     DataModel::SourceType.POTENTIALLY_DRUGGABLE,
          source_trust_level_id: DataModel::SourceTrustLevel.EXPERT_CURATED,
          source_db_name:     'HingoraniCasas',
          full_name:          'The druggable genome and support for target identification and validation in drug development (Hingorani & Casas, 2017)',
          license: 'Supplementary data from Author Copyright publication',
          license_link: 'https://stm.sciencemag.org/content/9/383/eaag1166/tab-pdf',
        }
      end

      def self.run(tsv_path)
        TSVImporter.import tsv_path, HingoraniCasasRow, source_info do
          gene :gene_symbol, nomenclature: 'HingoraniCasas Gene Symbol' do
            name :gene_symbol, nomenclature: 'Gene Symbol', transform: ->(x) { x.upcase }
            name :ensembl_id, nomenclature: 'Ensembl Id', transform: ->(x) { x.upcase }
            category 'DRUGGABLE GENOME'
          end
        end.save!
      end
    end
  end
end


text:
package com.opengamma.analytics.financial.model.option.pricing.analytic;

import static org.testng.AssertJUnit.assertEquals;

import org.testng.annotations.Test;
import org.threeten.bp.ZonedDateTime;

import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldCurve;
import com.opengamma.analytics.financial.model.option.definition.EuropeanVanillaOptionDefinition;
import com.opengamma.analytics.financial.model.option.definition.OptionDefinition;
import com.opengamma.analytics.financial.model.option.definition.SkewKurtosisOptionDataBundle;
import com.opengamma.analytics.financial.model.volatility.surface.VolatilitySurface;
import com.opengamma.analytics.math.curve.ConstantDoublesCurve;
import com.opengamma.analytics.math.statistics.descriptive.LognormalFisherKurtosisFromVolatilityCalculator;
import com.opengamma.analytics.math.statistics.descriptive.LognormalSkewnessFromVolatilityCalculator;
import com.opengamma.analytics.math.surface.ConstantDoublesSurface;
import com.opengamma.util.test.TestGroup;
import com.opengamma.util.time.DateUtils;
import com.opengamma.util.time.Expiry;

/**
 * Test.
 */
@Test(groups = TestGroup.UNIT)
public class JarrowRuddSkewnessKurtosisModelTest {
  private static final YieldAndDiscountCurve R = YieldCurve.from(ConstantDoublesCurve.from(0.05));
  private static final double B = 0.02;
  private static final double SIGMA = 0.4;
  private static final double T = 0.5;
  private static final VolatilitySurface SURFACE = new VolatilitySurface(ConstantDoublesSurface.from(SIGMA));
  private static final double SPOT = 90;
  private static final ZonedDateTime DATE = DateUtils.getUTCDate(2010, 1, 1);
  private static final BlackScholesMertonModel BSM = new BlackScholesMertonModel();
  private static final JarrowRuddSkewnessKurtosisModel MODEL = new JarrowRuddSkewnessKurtosisModel();
  private static final double SKEW;
  private static final double KURTOSIS;
  private static final OptionDefinition CALL = new EuropeanVanillaOptionDefinition(100, new Expiry(DateUtils.getDateOffsetWithYearFraction(DATE, T)), true);
  private static final OptionDefinition PUT = new EuropeanVanillaOptionDefinition(100, new Expiry(DateUtils.getDateOffsetWithYearFraction(DATE, T)), false);
  private static final SkewKurtosisOptionDataBundle NORMAL_DATA;

  static {
    SKEW = new LognormalSkewnessFromVolatilityCalculator().evaluate(SIGMA, T);
    KURTOSIS = new LognormalFisherKurtosisFromVolatilityCalculator().evaluate(SIGMA, T) + 3;
    NORMAL_DATA = new SkewKurtosisOptionDataBundle(R, B, SURFACE, SPOT, DATE, SKEW, KURTOSIS);
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testNullDefinition() {
    MODEL.getPricingFunction(null);
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testNullData() {
    MODEL.getPricingFunction(CALL).evaluate((SkewKurtosisOptionDataBundle) null);
  }

  @Test
  public void testNormal() {
    assertEquals(MODEL.getPricingFunction(CALL).evaluate(NORMAL_DATA), BSM.getPricingFunction(CALL).evaluate(NORMAL_DATA), 1e-9);
    assertEquals(MODEL.getPricingFunction(PUT).evaluate(NORMAL_DATA), BSM.getPricingFunction(PUT).evaluate(NORMAL_DATA), 1e-9);
  }
}


text:
            Transaksi Pendasaran Balik Nama

                    <a href="<?php echo site_url('admin/home'); ?>">Dashboard

                    Transaksi Pendasaran

                    <a href="<?php echo site_url('admin/baliknama'); ?>">Balik Nama

                    <a href="<?php echo site_url('admin/baliknama/pilihpenduduk/'.$this->uri->segment(4)); ?>">Pilih Penduduk

                    Tambah Penduduk

                             Form Tambah Penduduk

                        <form role="form" class="form-horizontal" action="<?php echo site_url('admin/baliknama/savedatapenduduk/'.$this->uri->segment(4)); ?>" method="post" enctype="multipart/form-data">
                        <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
                        <input type="hidden" class="provinsi_id" name="provinsi_id" value="<?php echo set_value('provinsi_id'); ?>">
                        <input type="hidden" class="kab_id" name="kab_id" value="<?php echo set_value('kab_id'); ?>">

                                <?php if ($error == 'true') { ?>

                                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
                                    ERROR !!

                                    <?php echo validation_errors(); ?>

                                <?php } ?>

Data Detail

                                    N I K

                                        <input type="text" class="form-control" placeholder="Enter N I K" name="nik" value="<?php echo set_value('nik'); ?>" pattern="^[0-9]*" title="Harus Angka" autocomplete="off" maxlength="16" required autofocus>

                                    No. KK

                                        <input type="text" class="form-control" placeholder="Enter No. KK" name="no_kk" value="<?php echo set_value('no_kk'); ?>" pattern="^[0-9]*" title="Harus Angka" autocomplete="off" maxlength="16" required>

                                    Nama Penduduk

                                        <input type="text" class="form-control" placeholder="Enter Nama Penduduk" name="nama" value="<?php echo set_value('nama'); ?>" autocomplete="off" required>

                                    Tempat Lahir

                                        <input type="text" class="form-control" placeholder="Enter Tempat Lahir" name="tmpt_lahir" value="<?php echo set_value('tmpt_lahir'); ?>" autocomplete="off" required>

                                    Tanggal Lahir

                                        <input class="form-control form-control-inline input-medium date-picker" size="16" type="text" name="tgl_lahir" value="<?php echo set_value('tgl_lahir'); ?>" placeholder="DD-MM-YYYY" autocomplete="off" required />

                                    Jenis Kelamin

                                            <input type="radio" name="rdJk" class="md-radiobtn" id="Jk1" value="1" <?php echo set_checkbox('rdJk', 1); ?> required>

                                                 Laki-Laki

                                            <input type="radio" name="rdJk" class="md-radiobtn" id="Jk2" value="2" <?php echo set_checkbox('rdJk', 2); ?> required>

                                                 Perempuan

                                    Provinsi

                                        <?php
                                        $style_provinsi = 'class="select2_category form-control" id="provinsi_id"  onChange="tampilKabupaten()"';
                                            echo form_dropdown('lstProvinsi',$provinsi,'',$style_provinsi);
                                        ?>

                                    Kabupaten

                                        <?php
                                        $style_kabupaten = 'class="select2_category form-control" id="kabupaten_id" onChange="tampilKecamatan()"';
                                        echo form_dropdown("lstKabupaten",array('Pilih Kabupaten'=>'- Pilih Kabupaten -'),'',$style_kabupaten);
                                        ?>

                                    Kecamatan

                                        <?php
                                        $style_kecamatan = 'class="select2_category form-control" id="kecamatan_id" onChange="tampilKelurahan()"';
                                        echo form_dropdown("lstKecamatan",array('Pilih Kecamatan'=>'- Pilih Kecamatan -'),'',$style_kecamatan);
                                        ?>

                                    Desa

                                        <?php
                                        $style_kelurahan = 'class="select2_category form-control" id="kelurahan_id"';
                                        echo form_dropdown("lstKelurahan",array('Pilih Desa '=>'- Pilih Desa -'),'',$style_kelurahan);
                                        ?>

                                    Alamat

                                        <input type="text" class="form-control" placeholder="Enter Alamat" name="alamat" value="<?php echo set_value('alamat'); ?>" autocomplete="off" required>

                                        SAMPLE : NAMA ALAMAT RT : 999 RW : 999

Foto

                                    Upload Foto

                                                <img src="<?php echo base_url(); ?>img/no_image.gif" alt="" />

                                                 Browse
                                                 Change
                                                    <input type="file" class="default" name="userfile" />

                                            NOTE !
                                            Resolution : 500 x 750 pixel

                                        <button type="submit" class="btn green"> Simpan</button>
                                        <a href="<?php echo site_url('admin/baliknama/pilihpenduduk/'.$this->uri->segment(4)); ?>" class="btn yellow"> Batal

                        </form>


text:
title: Bitwise-OR operations on random integers
localeTitle: Operaciones bitwise-OR en enteros aleatorios
---
## Problema 323: operaciones de bitwise-OR en enteros aleatorios

Esto es un talón. [Ayuda a nuestra comunidad a expandirla](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-323-bitwise-or-operations-on-random-integers/index.md) .

[Esta guía rápida de estilo ayudará a asegurar que su solicitud de extracción sea aceptada](https://github.com/freecodecamp/guides/blob/master/README.md) .


text:
<?php

namespace Casino\BlackjackBundle\Controller;

use Casino\BlackjackBundle\Controller\DefaultController;
use Casino\BlackjackBundle\Entity\Deck;
use Casino\BlackjackBundle\Entity\Game;
use Casino\BlackjackBundle\Entity\Round;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;

class GameController extends DefaultController
{
    public function startAction()
    {
        $session = new Session();
        if (!$session->get('playerId')) {
            return $this->redirect($this->generateUrl('get_blackjack_login'));
        }

        $player = $this->getCurrentPlayer( $session->get('playerId') );
        $game = new Game();
        $game->setPlayer($player);
        $round = new Round();
        $round->setGame($game);

        $em = $this->getDoctrine()->getManager();
        $em->persist($game);
        $em->persist($round);
        $em->flush();

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

    public function startRoundAction()
    {
        $session = new Session();
        if (!$session->get('playerId')) {
            return $this->redirect($this->generateUrl('get_blackjack_login'));
        }

        $player = $this->getCurrentPlayer( $session->get('playerId') );
        $game = $player->getGames()->last();
        $round = new Round();
        $round->setGame($game);

        $em = $this->getDoctrine()->getManager();
        $em->persist($round);
        $em->flush();

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

    public function playAction()
    {
        $session = new Session();
        if (!$session->get('playerId')) {
            return $this->redirect($this->generateUrl('get_blackjack_login'));
        }

        $player = $this->getCurrentPlayer( $session->get('playerId') );
        $game = $player->getGames()->last();
        $round = $game->getRounds()->last();

        if ($round->getWon() !== "" || ($player->getWallet() < 10 && $round->getBet() > 0)) {
            return $this->redirect($this->generateUrl('get_blackjack_homepage'));
        }

        $error = "";
        foreach ($session->getFlashBag()->get('error', array()) as $message) {
            $error = $message;
        }

        if ($round->getBet() === 0) {
            return $this->render('CasinoBlackjackBundle:Game:roundStart.html.twig', array(
                'player' => $player,
                'game' => $game,
                'round' => $round,
                'error' => $error
            ));
        }

        $em = $this->getDoctrine()->getManager();
        $roundId = $round->getId();
        $playerRevealed = $em->getRepository('CasinoBlackjackBundle:Revealed')->findPlayerCards($roundId);
        $dealerRevealed = $em->getRepository('CasinoBlackjackBundle:Revealed')->findDealerCards($roundId);

        return $this->render('CasinoBlackjackBundle:Game:playing.html.twig', array(
            'player' => $player,
            'game' => $game,
            'round' => $round,
            'error' => $error,
            'playerRevealed' => $playerRevealed,
            'dealerRevealed' => $dealerRevealed
        ));
    }

    public function betAction(Request $request)
    {
        $session = new Session();

        $bet = $request->get('bet');

        $em = $this->getDoctrine()->getManager();
        $player = $this->getCurrentPlayer( $session->get('playerId') );
        $originalWallet = $player->getWallet();
        if ($originalWallet < $bet) {
            $session->getFlashBag()->add('error', 'You can\'t bet more than you have !');
            return $this->redirect($this->generateUrl('blackjack_game'));
        }
        $player->setWallet( $originalWallet - $bet );
        $round = $em->getRepository('CasinoBlackjackBundle:Round')->find( $request->get('roundId') );

        $round->setBet($bet);

        if ($round->getRevealed()->count() > 50) {
            $session->getFlashBag()->add('error', 'The deck is empty, this shouldn\'t happend.');
            return $this->redirect($this->generateUrl('blackjack_game'));
        }

        $deck = new Deck();
        $revealed = array();
        $revealedNames = array();
        for ($i=0; $i < 2; $i++) {
            $revealed[$i] = $deck->draw($round, $revealedNames, 'player');
            array_push($revealedNames, array('name' => $revealed[$i]->getName()));
            $em->persist($revealed[$i]);
        }
        for ($i=2; $i < 4; $i++) {
            $revealed[$i] = $deck->draw($round, $revealedNames, 'dealer');
            array_push($revealedNames, array('name' => $revealed[$i]->getName()));
            $em->persist($revealed[$i]);
        }

        $em->flush();

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

    public function playerDrawAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $roundId = $request->get('roundId');
        $round = $em->getRepository('CasinoBlackjackBundle:Round')->find( $roundId );
        $revealedNames = $em->getRepository('CasinoBlackjackBundle:Revealed')->findNamesByRoundId($roundId);

        if ($round->getRevealed()->count() > 50) {
            $session->getFlashBag()->add('error', 'The deck is empty, this shouldn\'t happend.');
            return $this->redirect($this->generateUrl('blackjack_game'));
        }

        $deck = new Deck();

        $revealed = $deck->draw($round, $revealedNames, 'player');
        $em->persist($revealed);

        $playerRevealed = $em->getRepository('CasinoBlackjackBundle:Revealed')->findPlayerCards($roundId);

        $deck = $deck->cards();
        array_push($playerRevealed, $revealed);
        $playerScore = $this->getScore($deck, $playerRevealed);

        if (!$playerScore) {
            $round->setWon('lost');
            $em->persist($round);
            $em->flush();
            return $this->redirect($this->generateUrl('blackjack_end_round'));
        }

        $em->flush();

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

    public function dealerDrawAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $round = $em->getRepository('CasinoBlackjackBundle:Round')->find( $request->get('roundId') );
        $revealedNames = $em->getRepository('CasinoBlackjackBundle:Revealed')->findNamesByRoundId($round->getId());

        if ($round->getRevealed()->count() > 50) {
            $session->getFlashBag()->add('error', 'The deck is empty, this shouldn\'t happend.');
            return $this->redirect($this->generateUrl('blackjack_game'));
        }

        $deckObject = new Deck();
        $deck = $deckObject->cards();

        $dealerRevealed = $em->getRepository('CasinoBlackjackBundle:Revealed')->findDealerCards( $request->get('roundId') );
        $dealerScore = $this->getScore($deck, $dealerRevealed);

        if ($dealerScore) {
            while ($dealerScore < 17 && $dealerScore !== false) {
                $newRevealed = $deckObject->draw($round, $revealedNames, 'dealer');
                $em->persist($newRevealed);
                array_push($dealerRevealed, $newRevealed);
                $dealerScore = $this->getScore($deck, $dealerRevealed);
            }
        }
        else {
            $round->setWon('won');
            $em->persist($round);
            $em->flush();
            return $this->redirect($this->generateUrl('blackjack_end_round'));
        }

        $playerRevealed = $em->getRepository('CasinoBlackjackBundle:Revealed')->findPlayerCards( $request->get('roundId') );
        $playerScore = $this->getScore($deck, $playerRevealed);

        if (!$dealerScore || $dealerScore < $playerScore) {
            $round->setWon('won');
        }
        elseif ($dealerScore == $playerScore) {
            $round->setWon('tie');
        }
        else {
            $round->setWon('lost');
        }

        $em->persist($round);
        $em->flush();

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

    public function getScore($deck, $allCards)
    {
        $scores = array();
        foreach ($allCards as $card) {
            $cardValues = $deck[ $card->getName() ];
            if (count($scores) === 0) {
                $scores = $cardValues;
            }
            else {
                $newScores = $scores;
                foreach ($scores as $key => &$possibleScore) {
                    if (isset($cardValues[1])) {
                        array_push($newScores, ($possibleScore + $cardValues[1]));
                    }
                    $newScores[$key] += $cardValues[0];
                }
                $scores = $newScores;
            }
        }

        $score = false;
        foreach ($scores as $key => $possibleScore) {
            if ($possibleScore < 22) {
                $score = max($score, $possibleScore);
            }
        }

        return $score;
    }

    public function endAction()
    {
        $session = new Session();
        if (!$session->get('playerId')) {
            return $this->redirect($this->generateUrl('get_blackjack_login'));
        }
        $em = $this->getDoctrine()->getManager();

        $player = $this->getCurrentPlayer( $session->get('playerId') );
        $game = $player->getGames()->last();
        $round = $game->getRounds()->last();
        $score = $game->getScore();
        $bet = $round->getBet();

        if ($round->getWon() === 'won') {
            $message = "Vous avez gagné !";
            $wallet = $player->getWallet();
            $player->setWallet( $wallet + ($bet * 2) );
            $game->setScore( $score + $bet );
            $class = "won";
        }
        elseif ($round->getWon() === 'tie') {
            $message = "Vous êtes à égalité avec le casino !";
            $wallet = $player->getWallet();
            $player->setWallet( $wallet + $bet );
            $class = "tie";
        }
        else {
            $message = "Vous avez perdu !";
            $game->setScore( $score - $bet );
            $class = "lost";
        }

        $em->persist($player);
        $em->persist($game);

        $roundId = $round->getId();
        $playerRevealed = $em->getRepository('CasinoBlackjackBundle:Revealed')->findPlayerCards($roundId);
        $dealerRevealed = $em->getRepository('CasinoBlackjackBundle:Revealed')->findDealerCards($roundId);

        $em->flush();

        return $this->render('CasinoBlackjackBundle:Game:end.html.twig', array(
            'player' => $player,
            'game' => $game,
            'round' => $round,
            'message' => $message,
            'result' => $class,
            'playerRevealed' => $playerRevealed,
            'dealerRevealed' => $dealerRevealed
        ));
    }

}


text:
require "rubygems"
require "json"
require "galaxy"

class Dataset
  attr_accessor :id, :history_number

  def self.all
    Galaxy.agent.get Galaxy::BASE_URL + "/history"
    Galaxy.agent.page.root.css("div.historyItem").map do |e|
      dataset = self.new
      dataset.id = e["id"].split("-")[1]
      dataset.history_number =  e.css("span.historyItemTitle").css("b").text.split(":")[0].to_i
      dataset
    end
  end

  def self.upload(content)
    Galaxy.agent.get Galaxy::BASE_URL + "/tool_runner?tool_id=upload1"
    Galaxy.agent.page.form_with(:name => "tool_form") do |form|
      form.field_with(:name => "files_0|url_paste").value = content
      form.click_button
    end
    title = Galaxy.agent.page.root.css("div.donemessage div b").first.text
    history_number = title.match(/(\d+): Pasted Entry/)[1].to_i
    find_by_history_numbers([history_number]).first
  end

  def self.find_by_history_numbers(history_numbers)
    all.select{|d| history_numbers.include?(d.history_number)}
  end

  def self.generating?(datasets)
    datasets.any? do |dataset|
      dataset.generating?
    end
  end

  def self.wait(datasets)
    while generating?(datasets)
      sleep 1
    end
  end

  def generating?
    Galaxy.agent.post("/root/history_item_updates", "ids" => id, "states" => "queued")
    result = JSON.parse(Galaxy.agent.page.body)
    if result.empty?
      true
    else
      state = result[id.to_s]["state"]
      if state == "running"
        true
      else
        false
      end
    end
  rescue
    true
  end
end


text:
package kubeletutil // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/awscontainerinsightreceiver/internal/stores/kubeletutil"

import (
	"encoding/json"
	"fmt"

	"go.uber.org/zap"
	corev1 "k8s.io/api/core/v1"

	"github.com/open-telemetry/opentelemetry-collector-contrib/internal/k8sconfig"
	"github.com/open-telemetry/opentelemetry-collector-contrib/internal/kubelet"
)

type KubeletClient struct {
	KubeIP     string
	Port       string
	restClient kubelet.Client
}

func NewKubeletClient(kubeIP string, port string, logger *zap.Logger) (*KubeletClient, error) {
	kubeClient := &KubeletClient{
		Port:   port,
		KubeIP: kubeIP,
	}

	endpoint := kubeIP + ":" + port

	// use service account for authentication
	clientConfig := &kubelet.ClientConfig{
		APIConfig: k8sconfig.APIConfig{
			AuthType: k8sconfig.AuthTypeServiceAccount,
		},
	}

	clientProvider, err := kubelet.NewClientProvider(endpoint, clientConfig, logger)
	if err != nil {
		return nil, err
	}
	client, err := clientProvider.BuildClient()
	if err != nil {
		return nil, err
	}
	kubeClient.restClient = client
	return kubeClient, nil
}

func (k *KubeletClient) ListPods() ([]corev1.Pod, error) {
	var result []corev1.Pod
	b, err := k.restClient.Get("/pods")
	if err != nil {
		return result, fmt.Errorf("call to /pods endpoint failed: %w", err)
	}

	pods := corev1.PodList{}
	err = json.Unmarshal(b, &pods)
	if err != nil {
		return result, fmt.Errorf("parsing response failed: %w", err)
	}

	return pods.Items, nil
}


text:
module CsvRails
  module Mongoid
    def self.included(base)
      base.send(:include, CsvRails::ActiveModel::InstanceMethods)
      base.const_get(:ClassMethods).tap{|klass|
        klass.send(:include, CsvRails::ActiveModel::ClassMethods)
        klass.send(:include, ClassMethods)
      }
    end

    module ClassMethods
      def attribute_names
        fields.keys.map(&:to_sym)
      end
    end
  end
end


text:
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
using Sample;
using System.Collections.Generic;
using System.IdentityModel.Tokens;

[assembly: OwinStartup(typeof(MVC_OWIN_Client.Startup))]

namespace MVC_OWIN_Client
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = "mvc.owin.implicit",
                Authority = Constants.BaseAddress,
                RedirectUri = "https://localhost:44301/",
                ResponseType = "id_token",
                Scope = "openid email",

                UseTokenLifetime = false,
                SignInAsAuthenticationType = "Cookies",
            });
        }
    }
}


text:
<?php
$config->todo = new stdclass();
$config->todo->batchCreate  = 8;

$config->todo->create = new stdclass();
$config->todo->edit   = new stdclass();
$config->todo->dates  = new stdclass();
$config->todo->times  = new stdclass();
$config->todo->create->requiredFields = 'name';
$config->todo->edit->requiredFields   = 'name';
$config->todo->dates->end             = 15;
$config->todo->times->begin           = 6;
$config->todo->times->end             = 23;
$config->todo->times->delta           = 10;

$config->todo->editor = new stdclass();
$config->todo->editor->create = array('id' => 'desc', 'tools' => 'simpleTools');
$config->todo->editor->edit   = array('id' => 'desc', 'tools' => 'simpleTools');

$config->todo->list = new stdclass();
$config->todo->list->exportFields = 'id, account, date, begin, end, type, idvalue, pri, name, desc, status, private';


text:
<!DOCTYPE html>

  {% include head.html %}

    {% include header.html %}

        {{ content }}

    {% include rules.html %}
    {% include footer.html %}


text:
package com.google.gwt.xhr2.client;
/**
 * A ready-state callback for an {@link XMLHttpRequest2} object.
 */
public interface XHRLoadEndHandler {
	/**
	 * This is called when the request has completed (either in success or failure).
	 * See {@link XMLHttpRequest2#setOnLoadEnd}.
	 *
	 * @param xhr
	 *            the object whose state has changed.
	 */
	void onLoadEnd(ProgressEvent event);
}


text:
import React, {PropTypes} from 'react'
// import PropTypes from 'prop-types'
import {
    StyleSheet, View, TextInput, Text, TouchableHighlight, InteractionManager
}
    from 'react-native';

export default class PassInput extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            text: '',
            editable: true
        }
    }

    static propTypes = {
        maxLength: PropTypes.number,
        blur: PropTypes.bool,
        passWordType: PropTypes.string,
        onChange: PropTypes.func
    }

    static defaultProps = {
        maxLength: 6,
        blur: false,
        passWordType: 'numeric',
        onChange: () => { }
    }

    componentWillReceiveProps(props) {
        if (props.blur) {
            this.refs.textInput.blur()
            this.setState({ editable: false })
        } else {
            this.setState({ editable: true })
            InteractionManager.runAfterInteractions(() => {
                this._onPress()
            })

        }
    }

    _onPress() {
        if (!this.state.editable) {
            return
        }
        this.refs.textInput.focus()
    }

    _onChange(text) {
        this.setState({ text })
        this.props.onChange(text)
    }

    render() {
        return (
            <TouchableHighlight onPress={this._onPress.bind(this)} activeOpacity={1} underlayColor='transparent'>
                <View style={[styles.container, this.props.style]} >
                    <TextInput ref='textInput'
                        style={styles.inputBehind}
                        maxLength={this.props.maxLength}
                        autoFocus={true}
                        //editable={this.state.editable}
                        keyboardType={this.props.passWordType}//default
                        onChangeText={(text) => { this._onChange(text) }}
                    />
                    {
                        this._getInputItem()
                    }
                </View>
            </TouchableHighlight>
        )

    }
    _getInputItem() {
        let inputItem = [];
        let { text } = this.state;
        for (let i = 0; i < parseInt(this.props.maxLength); i++) {
            if (i == 0) {
                inputItem.push(
                    <View key={i} style={[styles.inputItem, this.props.inputItemStyle]}>
                        {i < text.length ? <View style={[styles.iconStyle, this.props.iconStyle]}></View> : null}
                    </View>)
            }
            else {
                inputItem.push(
                    <View key={i} style={[styles.inputItem, styles.inputItemBorderLeftWidth, this.props.inputItemStyle]}>
                        {i < text.length ?
                            <View style={[styles.iconStyle, this.props.iconStyle]}>
                            </View> : null}
                    </View>)
            }
            ;
        }
        return inputItem;
    }
}

const styles = StyleSheet.create({
    container: {
        alignItems: 'center',
        flexDirection: 'row',
        borderWidth: .5,
        borderColor: '#ccc',
        backgroundColor: '#fff'
    },
    inputBehind: { width: 0, height: 0, overflow: 'hidden', position: 'absolute', left: 0, top: 0 },
    inputItem: {
        height: 45,
        width: 45,
        justifyContent: 'center',
        alignItems: 'center'
    },
    inputItemBorderLeftWidth: {
        borderLeftWidth: .5,
        borderColor: '#ccc',
    },
    iconStyle: {
        width: 16,
        height: 16,
        backgroundColor: '#222',
        borderRadius: 8,
    },
})


text:
@interface SocialInviteRequest ()

// Private interface goes here.

@end

@implementation SocialInviteRequest

+ (SocialInviteRequest *)new:(RKObjectManager *)objectManager {
    SocialInviteRequest *requestObject = [[SocialInviteRequest alloc] initWithEntity:[NSEntityDescription entityForName:NSStringFromClass([SocialInviteRequest class]) inManagedObjectContext:objectManager.managedObjectStore.persistentStoreManagedObjectContext] insertIntoManagedObjectContext:objectManager.managedObjectStore.persistentStoreManagedObjectContext];
    return requestObject;
}

@end


text:
using System.Net;
using System.Threading.Tasks;
using tusdotnet.Adapters;
using tusdotnet.Helpers;

namespace tusdotnet.Validation
{
    internal abstract class Requirement
    {
        public HttpStatusCode StatusCode { get; protected set; }

        public string ErrorMessage { get; protected set; }

        public abstract Task Validate(ContextAdapter context);

        public void Reset()
        {
            StatusCode = 0;
            ErrorMessage = null;
        }

        protected Task Conflict(string errorMessage)
        {
            return Error(HttpStatusCode.Conflict, errorMessage);
        }

        protected Task BadRequest(string errorMessage)
        {
            return Error(HttpStatusCode.BadRequest, errorMessage);
        }

        protected Task RequestEntityTooLarge(string errorMessage)
        {
            return Error(HttpStatusCode.RequestEntityTooLarge, errorMessage);
        }

        protected Task Forbidden(string errorMessage)
        {
            return Error(HttpStatusCode.Forbidden, errorMessage);
        }

        protected Task NotFound()
        {
            return Error(HttpStatusCode.NotFound, null);
        }

        protected Task UnsupportedMediaType(string errorMessage)
        {
            return Error(HttpStatusCode.UnsupportedMediaType, errorMessage);
        }

        protected Task Error(HttpStatusCode status, string errorMessage)
        {
            StatusCode = status;
            ErrorMessage = errorMessage;
            return TaskHelper.Completed;
        }
    }
}


text:
package com.example.taxihelper.mvp.ui.activities;

import android.content.Intent;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.example.taxihelper.R;
import com.example.taxihelper.constant.Constant;
import com.example.taxihelper.mvp.entity.CityChoose;
import com.example.taxihelper.mvp.entity.LocationChoose;
import com.example.taxihelper.mvp.ui.activities.base.RxBusSubscriberBaseActivity;
import com.example.taxihelper.mvp.ui.adapters.LocationChooseAdapter;
import com.example.taxihelper.utils.system.RxBus;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.List;

import butterknife.InjectView;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * Created by Raven on 2017/8/11.
 */

public class LocationChooseActivity extends RxBusSubscriberBaseActivity implements Inputtips.InputtipsListener, RecyclerArrayAdapter.OnItemClickListener {
    @InjectView(R.id.city_choose_tv)
    TextView cityChooseTv;
    @InjectView(R.id.location_input)
    EditText locationInput;
    @InjectView(R.id.search_result_list)
    EasyRecyclerView listView;
    private int currentCityId;
    private boolean hasSearch = false;
    String type;
    Integer serviceId;
    private String currentCity;
    private String currentLocation;
    private LocationChooseAdapter adapter;

    /**
     * 关键字搜索相关
     */
    InputtipsQuery query;
    Inputtips inputTips;

    @Override
    public void initInjector() {

    }

    @Override
    public void initViews() {
        currentCity = getIntent().getStringExtra(Constant.CURRENT_CITY);
        currentLocation = getIntent().getStringExtra(Constant.CURRENT_LOCATION);
        type = getIntent().getStringExtra(Constant.TYPE);
        serviceId = getIntent().getIntExtra(Constant.SERVICE_ID,-1);
        if (currentCity != null) {
            cityChooseTv.setText(currentCity);
        } else {
            cityChooseTv.setText("城市");
        }
        locationInput.addTextChangedListener(tw);

        adapter = new LocationChooseAdapter(this);
        listView.setLayoutManager(new LinearLayoutManager(this));
        listView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        listView.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
        //初始化搜索
        if (type.equals(Constant.TYPE_START)){
            getSupportActionBar().setTitle("选择上车地点");
            query = new InputtipsQuery(currentLocation, currentCity);
            query.setCityLimit(true);//限制在当前城市
        }else {
            getSupportActionBar().setTitle("选择下车地点");
            query = new InputtipsQuery(currentCity,currentCity);
        }

        inputTips = new Inputtips(this, query);
        inputTips.setInputtipsListener(this);
        inputTips.requestInputtipsAsyn();
        locationInput.setSingleLine();
    }

    @Override
    public int getLayout() {
        return R.layout.activity_location_choose;
    }

    @OnClick(R.id.city_choose_tv)
    public void onViewClicked() {
        Intent intent = new Intent(this, CityChooseActivity.class);
        intent.putExtra(Constant.CURRENT_CITY, currentCity);
        intent.putExtra(Constant.TYPE,type);
        intent.putExtra(Constant.SERVICE_ID,serviceId);
        startActivity(intent);
        //用户更改城市,为了重新搜索
        hasSearch = false;
    }

    @Override
    public void initRxBus() {
        mSubscription =  RxBus.getDefault().toObservable(CityChoose.class)
                .subscribe(new Action1<CityChoose>() {
                    @Override
                    public void call(CityChoose cityChoose) {
                        currentCityId = cityChoose.getCityId();
                        currentCity = cityChoose.getCity();
                        cityChooseTv.setText(currentCity);
                        //用户改变了城市选择,这里重新请求
                        if (!hasSearch){
                            query = new InputtipsQuery(currentCity, currentCity);
                            inputTips.setQuery(query);
                            inputTips.requestInputtipsAsyn();
                            hasSearch = true;
                        }
                    }
                });

    }

    private TextWatcher tw = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            query = new InputtipsQuery(charSequence.toString(), currentCity);
            query.setCityLimit(true);
            inputTips.setQuery(query);
            inputTips.requestInputtipsAsyn();

            if (charSequence.toString().equals("")){
                query = new InputtipsQuery(currentLocation,currentCity);
                inputTips.setQuery(query);
                inputTips.requestInputtipsAsyn();
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    };

    @Override
    public void onGetInputtips(List<Tip> list, int i) {
        Log.i(TAG,i+"");
        if (i != 1000 || list == null || list.size() == 0){
            return;
        }
        adapter.clear();
        adapter.addAll(list);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(int position) {
        String location = adapter.getItem(position).getName();
        String formatLocation = adapter.getItem(position).getDistrict()+adapter.getItem(position).getName();
        RxBus.getDefault().post(new LocationChoose(location,type,formatLocation,currentCityId));
        finish();
    }
}


text:
use {Ix, Ixs};
use error::{from_kind, ErrorKind, ShapeError};
use {zipsl, ZipExt};

pub use self::dim::*;
pub use self::axis::Axis;
pub use self::conversion::IntoDimension;
pub use self::dimension_trait::Dimension;
pub use self::ndindex::NdIndex;
pub use self::remove_axis::RemoveAxis;

#[macro_use] mod macros;
mod axis;
mod conversion;
pub mod dim;
mod dimension_trait;
mod ndindex;
mod remove_axis;

/// Private constructor and accessors for Dim
pub trait DimPrivate<I> {
    fn new(index: I) -> Self;
    fn ix(&self) -> &I;
    fn ixm(&mut self) -> &mut I;
}

/// Calculate offset from `Ix` stride converting sign properly
#[inline(always)]
pub fn stride_offset(n: Ix, stride: Ix) -> isize {
    (n as isize) * ((stride as Ixs) as isize)
}

/// Check whether the given `dim` and `stride` lead to overlapping indices
///
/// There is overlap if, when iterating through the dimensions in the order
/// of maximum variation, the current stride is inferior to the sum of all
/// preceding strides multiplied by their corresponding dimensions.
///
/// The current implementation assumes strides to be positive
pub fn dim_stride_overlap<D: Dimension>(dim: &D, strides: &D) -> bool {
    let order = strides._fastest_varying_stride_order();

    let dim = dim.slice();
    let strides = strides.slice();
    let mut prev_offset = 1;
    for &index in order.slice() {
        let d = dim[index];
        let s = strides[index];
        // any stride is ok if dimension is 1
        if d != 1 && (s as isize) < prev_offset {
            return true;
        }
        prev_offset = stride_offset(d, s);
    }
    false
}

/// Check whether the given dimension and strides are memory safe
/// to index the provided slice.
///
/// To be safe, no stride may be negative, and the offset corresponding
/// to the last element of each dimension should be smaller than the length
/// of the slice. Also, the strides should not allow a same element to be
/// referenced by two different index.
pub fn can_index_slice<A, D: Dimension>(data: &[A], dim: &D, strides: &D)
    -> Result<(), ShapeError>
{
    // check lengths of axes.
    let len = match dim.size_checked() {
        Some(l) => l,
        None => return Err(from_kind(ErrorKind::OutOfBounds)),
    };
    // check if strides are strictly positive (zero ok for len 0)
    for &s in strides.slice() {
        let s = s as Ixs;
        if s < 1 && (len != 0 || s < 0) {
            return Err(from_kind(ErrorKind::Unsupported));
        }
    }
    if len == 0 {
        return Ok(());
    }
    // check that the maximum index is in bounds
    let mut last_index = dim.clone();
    for mut index in last_index.slice_mut().iter_mut() {
        *index -= 1;
    }
    if let Some(offset) = stride_offset_checked_arithmetic(dim,
                                                           strides,
                                                           &last_index)
    {
        // offset is guaranteed to be positive so no issue converting
        // to usize here
        if (offset as usize) >= data.len() {
            return Err(from_kind(ErrorKind::OutOfBounds));
        }
        if dim_stride_overlap(dim, strides) {
            return Err(from_kind(ErrorKind::Unsupported));
        }
    } else {
        return Err(from_kind(ErrorKind::OutOfBounds));
    }
    Ok(())
}

/// Return stride offset for this dimension and index.
///
/// Return None if the indices are out of bounds, or the calculation would wrap
/// around.
fn stride_offset_checked_arithmetic<D>(dim: &D, strides: &D, index: &D)
    -> Option<isize>
    where D: Dimension
{
    let mut offset = 0;
    for (&d, &i, &s) in zipsl(dim.slice(), index.slice()).zip_cons(strides.slice()) {
        if i >= d {
            return None;
        }

        if let Some(offset_) = (i as isize)
                                   .checked_mul((s as Ixs) as isize)
                                   .and_then(|x| x.checked_add(offset)) {
            offset = offset_;
        } else {
            return None;
        }
    }
    Some(offset)
}

/// Stride offset checked general version (slices)
pub fn stride_offset_checked(dim: &[Ix], strides: &[Ix], index: &[Ix]) -> Option<isize> {
    if index.len() != dim.len() {
        return None;
    }
    let mut offset = 0;
    for (&d, &i, &s) in zipsl(dim, index).zip_cons(strides)
    {
        if i >= d {
            return None;
        }
        offset += stride_offset(i, s);
    }
    Some(offset)
}

/// Implementation-specific extensions to `Dimension`
pub trait DimensionExt {
// note: many extensions go in the main trait if they need to be special-
// cased per dimension
    /// Get the dimension at `axis`.
    ///
    /// *Panics* if `axis` is out of bounds.
    #[inline]
    fn axis(&self, axis: Axis) -> Ix;

    /// Set the dimension at `axis`.
    ///
    /// *Panics* if `axis` is out of bounds.
    #[inline]
    fn set_axis(&mut self, axis: Axis, value: Ix);
}

impl<D> DimensionExt for D
    where D: Dimension
{
    #[inline]
    fn axis(&self, axis: Axis) -> Ix {
        self[axis.axis()]
    }

    #[inline]
    fn set_axis(&mut self, axis: Axis, value: Ix) {
        self[axis.axis()] = value;
    }
}

impl<'a> DimensionExt for [Ix]
{
    #[inline]
    fn axis(&self, axis: Axis) -> Ix {
        self[axis.axis()]
    }

    #[inline]
    fn set_axis(&mut self, axis: Axis, value: Ix) {
        self[axis.axis()] = value;
    }
}

/// Collapse axis `axis` and shift so that only subarray `index` is
/// available.
///
/// **Panics** if `index` is larger than the size of the axis
// FIXME: Move to Dimension trait
pub fn do_sub<A, D: Dimension>(dims: &mut D, ptr: &mut *mut A, strides: &D,
                               axis: usize, index: Ix) {
    let dim = dims.slice()[axis];
    let stride = strides.slice()[axis];
    assert!(index < dim);
    dims.slice_mut()[axis] = 1;
    let off = stride_offset(index, stride);
    unsafe {
        *ptr = ptr.offset(off);
    }
}

// NOTE: These tests are not compiled & tested
#[cfg(test)]
mod test {
    use super::Dimension;
    use error::{from_kind, ErrorKind};

    #[test]
    fn slice_indexing_uncommon_strides() {
        let v: Vec<_> = (0..12).collect();
        let dim = (2, 3, 2);
        let strides = (1, 2, 6);
        assert!(super::can_index_slice(&v, &dim, &strides).is_ok());

        let strides = (2, 4, 12);
        assert_eq!(super::can_index_slice(&v, &dim, &strides),
                   Err(from_kind(ErrorKind::OutOfBounds)));
    }

    #[test]
    fn overlapping_strides_dim() {
        let dim = (2, 3, 2);
        let strides = (5, 2, 1);
        assert!(super::dim_stride_overlap(&dim, &strides));
        let strides = (6, 2, 1);
        assert!(!super::dim_stride_overlap(&dim, &strides));
        let strides = (6, 0, 1);
        assert!(super::dim_stride_overlap(&dim, &strides));
    }
}


text:
<?php

use common\assets\RecurrenceRuleAsset;
use common\models\Recurrence;

use kartik\builder\Form;
use kartik\datetime\DateTimePicker;
use kartik\helpers\Enum;
use kartik\widgets\ActiveForm;
use kartik\widgets\DatePicker;
use kartik\widgets\TimePicker;
use kartik\widgets\TouchSpin;

use yii\helpers\Html;
use yii\bootstrap\Modal;

/* @var $this yii\web\View */
/* @var $model common\models\Competition */
/* @var $form yii\widgets\ActiveForm */

RecurrenceRuleAsset::register($this);

$model = new Recurrence();
Modal::begin([
    'header' => '
'.Yii::t('golf', 'Repeat Event').'
',
	'id' => 'recurrence-modal',
]);

?>

	<?php
	echo Form::widget([
	    'model' => $model,
	    'form' => $form,
	    'columns' => 12,
	    'attributes' => [
			'frequency' => [
				'label' => Yii::t('golf', 'Recurrence'),
				'type' => Form::INPUT_DROPDOWN_LIST,
				'items' => Recurrence::getLocalizedConstants('FREQUENCY_'),
	            'columnOptions' => ['colspan' => 4],
			],
			'interval' => [
				'type' => Form::INPUT_WIDGET,
				'widgetClass'=> TouchSpin::className(),
				'options' => ['pluginOptions' => [
					'initval' => 1,
					'min' => 1,
					'max' => 30
				]],
	            'columnOptions' => ['colspan' => 4],
			],
			'repeat' => [
				'label' => Yii::t('golf', 'every'),
				'type' => Form::INPUT_STATIC,
	            'columnOptions' => ['colspan' => 4],
			],
		],
	]);

	echo '
';
	echo $form->field($model, 'byweekday')->checkboxButtonGroup(Enum::dayList())->label(false);
	echo '
';

	echo '
';
	echo Form::widget([
	    'model' => $model,
	    'form' => $form,
	    'columns' => 12,
	    'attributes' => [
			'option' => [
				'type' => Form::INPUT_RADIO_LIST,
				'items' => ['bymonthday'=>Yii::t('golf', 'on day')],
	            'columnOptions' => ['colspan' => 2],
				'label' => false,
			],
			'bymonthday' => [
				'type' => Form::INPUT_DROPDOWN_LIST,
				'items' => Enum::dateList(1, 31),
	            'columnOptions' => ['colspan' => 2],
				'label' => false,
			],
		],
	]);

	echo Form::widget([
	    'model' => $model,
	    'form' => $form,
	    'columns' => 12,
	    'attributes' => [
			'option' => [
				'type' => Form::INPUT_RADIO_LIST,
				'items' => ['byposday'=>Yii::t('golf', 'on the')],
	            'columnOptions' => ['colspan' => 2],
				'label' => false,
			],
			'bypos4month' => [
				'type' => Form::INPUT_DROPDOWN_LIST,
				'items' => Recurrence::getLocalizedConstants('POSITION_'),
	            'columnOptions' => ['colspan' => 4],
				'label' => false,
			],
			'weekday4month' => [
				'type' => Form::INPUT_DROPDOWN_LIST,
				'items' => Enum::dayList() + Recurrence::getLocalizedConstants('DAY_'),
	            'columnOptions' => ['colspan' => 4],
				'label' => false,
			],
		],
	]);
	echo '
';

	echo '
';
	echo Form::widget([
	    'model' => $model,
	    'form' => $form,
	    'columns' => 12,
	    'attributes' => [
			'option' => [
				'type' => Form::INPUT_RADIO_LIST,
				'items' => ['bymonth'=>Yii::t('golf', 'on')],
	            'columnOptions' => ['colspan' => 2],
				'label' => false,
			],
			'bymonth' => [
				'type' => Form::INPUT_DROPDOWN_LIST,
				'items' => Enum::monthList(),
	            'columnOptions' => ['colspan' => 4],
				'label' => false,
			],
			'monthday4year' => [
				'type' => Form::INPUT_DROPDOWN_LIST,
				'items' => Enum::dateList(1, 31),
	            'columnOptions' => ['colspan' => 2],
				'label' => false,
			],
		],
	]);

	echo Form::widget([
	    'model' => $model,
	    'form' => $form,
	    'columns' => 12,
	    'attributes' => [
			'option' => [
				'type' => Form::INPUT_RADIO_LIST,
				'items' => ['byposmonth'=>Yii::t('golf', 'on the')],
	            'columnOptions' => ['colspan' => 2],
				'label' => false,
			],
			'bypos4year' => [
				'type' => Form::INPUT_DROPDOWN_LIST,
				'items' => Recurrence::getLocalizedConstants('POSITION_'),
	            'columnOptions' => ['colspan' => 3],
				'label' => false,
			],
			'weekday4year' => [
				'type' => Form::INPUT_DROPDOWN_LIST,
				'items' => Enum::dayList() + Recurrence::getLocalizedConstants('DAY_'),
	            'columnOptions' => ['colspan' => 3],
				'label' => false,
			],
			'month4year' => [
				'type' => Form::INPUT_DROPDOWN_LIST,
				'items' => Enum::monthList(),
	            'columnOptions' => ['colspan' => 4],
				'label' => false,
			],
		],
	]);
	echo '
';

	echo '
';
	echo Form::widget([
	    'model' => $model,
	    'form' => $form,
	    'columns' => 12,
	    'attributes' => [
			'until' => [
				'type' => Form::INPUT_DROPDOWN_LIST,
				'items' => Recurrence::getLocalizedConstants('UNTIL_'),
	            'columnOptions' => ['colspan' => 4],
			],
			'count' => [
				'type' => Form::INPUT_WIDGET,
				'widgetClass'=> TouchSpin::className(),
				'options' => ['pluginOptions' => [
					'initval' => 1,
					'min' => 1,
					'max' => 20
				]],
	            'columnOptions' => ['colspan' => 4],
			],
			'date_end' => [
				'type' => Form::INPUT_WIDGET,
				'widgetClass'=> DatePicker::className(),
				'options' => ['pluginOptions' => [
	                'format' => 'yyyy/mm/dd',
	                'todayHighlight' => true
	            ]],
	            'columnOptions' => ['colspan' => 4],
				'label' => Yii::t('golf', 'End Date'),
			],
		],
	]);
	echo '
';
	?>

	    <?= Html::button(Yii::t('golf', 'Cancel'), ['class' => 'btn btn-danger', 'data' => ['dismiss' => 'modal']]) ?>
	    <?= Html::button(Yii::t('golf', 'OK'), ['class' => 'btn btn-success action-ok', 'data' => ['dismiss' => 'modal']]) ?>

<?php
$this->registerJs($this->blocks['JS_SCHEDULER'], yii\web\View::POS_READY);

Modal::end();


text:
<project name="__PROJECT_SHORT_NAME_LOWER__" default="dist">
	<description>
		Ant build script for Titanium Android module __PROJECT_SHORT_NAME__
	</description>

	<property name="ti.module.root" location="${basedir}"/>
	<property file="build.properties" />

	<import file="${titanium.platform}/../module/android/build.xml"/>
</project>


text:
@interface MXChatBaseCell ()

@property (nonatomic, readonly) MXChatStateButton *stateButton;

@end

@implementation MXChatBaseCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self setSelectionStyle:UITableViewCellSelectionStyleNone];
        [self setBackgroundColor:[UIColor clearColor]];

        [self initialize];
        _direction = -777;
        self.chatContentSize = CGSizeMake(120, 60);
        self.direction = MXChatCellDirectionLeft;
        self.chatContentInsets = MXCC_CONTENT_INSETS;
        self.showNameLabel = NO;
    }
    return self;
}

- (void)initialize
{
    UILabel *label = [UILabel new];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:MXCC_TIMELABEL_FONT_SIZE];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"2015-05-21 12:09";
    [self.contentView addSubview:label];
    _timeLabel = label;

    UIButton *button = [UIButton new];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setImage:mxc_imageInChatBundle(@"avator") forState:UIControlStateNormal];
    [button mxc_setRadius:MXCC_AVATAR_SIZE.width / 2];
    [self.contentView addSubview:button];
    _avatarButton = button;

    label = [UILabel new];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:MXCC_NAMELABEL_FONT_SIZE];
    label.text = @"小X";
    [self.contentView addSubview:label];
    _nameLabel = label;

    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:view];
    _chatContentView = view;

    UIImageView *imageView = [UIImageView new];
    [_chatContentView addSubview:imageView];
    _chatContentBackgroundView = imageView;

    MXChatStateButton *sbutton = [MXChatStateButton new];
    [sbutton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    sbutton.titleLabel.font = [UIFont boldSystemFontOfSize:10];
    [sbutton addTarget:self action:@selector(stateButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:sbutton];
    _stateButton = sbutton;
}

- (CGFloat)maxContentWidth
{
    return self.contentView.bounds.size.width - MXCC_AVATAR_SPACE - MXCC_AVATAR_SIZE.width - MXCC_CHATVIEW_SPACE - MXCC_STATEBUTTON_SIZE.width - MXCC_STATEBUTTON_SPACE - MXCC_LR_SPACE;
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    CGRect frame = self.contentView.bounds;

    //时间
    CGRect lframe = frame;
    lframe.size.height = self.showTimeLabel && !mxc_stringIsNil(self.timeLabel.text) ? MXCC_TIMELABEL_HEIGHT : 0;
    self.timeLabel.frame = lframe;

    //头像
    CGRect aframe;
    aframe.origin.y = lframe.size.height;
    aframe.size = MXCC_AVATAR_SIZE;

    //名字
    CGRect nframe = aframe;
    nframe.size.height = self.showNameLabel && !mxc_stringIsNil(self.nameLabel.text) ? MXCC_NAMELABEL_HEIGHT : 0;
    nframe.size.width = frame.size.width - aframe.size.width - MXCC_AVATAR_SPACE * 4;

    //内容
    CGRect cframe = aframe;
    cframe.origin.y = nframe.size.height + nframe.origin.y;
    cframe.size = self.chatContentSize;
    UIEdgeInsets insets = self.chatContentInsets;
    cframe.size.width += insets.left + insets.right;
    cframe.size.height += insets.top + insets.bottom;

    //发送状态
    CGRect sframe = aframe;
    sframe.size = MXCC_STATEBUTTON_SIZE;

    if (self.direction == MXChatCellDirectionLeft) {
        aframe.origin.x = MXCC_AVATAR_SPACE;
        nframe.origin.x = aframe.size.width + aframe.origin.x + MXCC_CHATVIEW_SPACE;
        cframe.origin.x = aframe.size.width + aframe.origin.x + MXCC_CHATVIEW_SPACE;
        sframe.origin.x = cframe.origin.x + cframe.size.width + MXCC_STATEBUTTON_SPACE;
    }
    else {
        aframe.origin.x = frame.size.width - MXCC_AVATAR_SIZE.width - MXCC_AVATAR_SPACE;
        nframe.origin.x = MXCC_CHATVIEW_SPACE * 2;
        cframe.origin.x = aframe.origin.x - cframe.size.width - MXCC_CHATVIEW_SPACE;
        sframe.origin.x = cframe.origin.x - MXCC_STATEBUTTON_SPACE - sframe.size.width;
    }
    self.avatarButton.frame = aframe;
    self.nameLabel.frame = nframe;
    self.stateButton.frame = sframe;
    self.chatContentView.frame = cframe;
    self.chatContentBackgroundView.frame = self.chatContentView.bounds;

    CGRect ssframe = self.frame;
    CGFloat cyh = cframe.size.height + cframe.origin.y;
    CGFloat ayh = aframe.size.height + aframe.origin.y;
    ssframe.size.height = MAX(cyh, ayh) + MXCC_BOTTOM_SPACE;
    self.frame = ssframe;
}

- (void)setDirection:(MXChatCellDirection)direction
{
    if (_direction == direction) return;
    _direction = direction;

    UIImage *image = mxc_imageInChatBundle(direction ? @"mr" : @"ml");
    image = [image stretchableImageWithLeftCapWidth:image.size.width/2 topCapHeight:image.size.height/2];
    self.chatContentBackgroundView.image = image;

    self.nameLabel.textAlignment = direction ? NSTextAlignmentRight : NSTextAlignmentLeft;
}

- (void)setState:(MXChatCellState)state
{
    self.stateButton.cellState = state;
}

- (void)setShowTimeLabel:(BOOL)showTimeLabel
{
    _showTimeLabel = showTimeLabel;
    self.timeLabel.hidden = !showTimeLabel;
}

- (void)setShowNameLabel:(BOOL)showNameLabel
{
    _showNameLabel = showNameLabel;
    self.nameLabel.hidden = !showNameLabel;
}

- (MXChatCellState)state
{
    return self.stateButton.cellState;
}

- (void)stateButtonTouched:(UIButton *)button
{
    if ([self.delegate respondsToSelector:@selector(chatCellStateButtonTouched:)]) {
        [self.delegate chatCellStateButtonTouched:self];
    }
}

@end


text:
Contributors in the order of first contribution

* [Jakob Stoeck](https://github.com/jakob-stoeck)
* [Roy Pardee](https://github.com/rpardee)
* [Matthew Kastin aka FriedEgg](https://github.com/FriedEgg)


text:
package com.bocekm.skycontrol.cas;

import java.nio.ByteBuffer;

/**
 * Loads values from byte buffer which contains TIFF field data.
 */
public class TiffField {

    private int mType;
    private int mCount;
    private int mValueOrOffset;

    public static final int TIFF_TYPE_LONG = 4;
    public static final int TIFF_TYPE_DOUBLE = 12;

    public TiffField(ByteBuffer buffer) {
        readField(buffer);
    }

    private void readField(ByteBuffer buffer) {
        // Tag has been already read from the buffer. It is followed by 2 bytes describing
        // representation of the value (TIFF-Type)
        mType = buffer.getShort();
        // Log.d(SkyControlConst.DEBUG_TAG, "Type: " + mType + "\n");

        // Follows number of values of 'type' that are stored in this field (4 bytes).
        mCount = buffer.getInt();
        // Log.d(SkyControlConst.DEBUG_TAG, "Count: " + mCount + "\n");

        // Last 4 bytes store the value itself (if count*sizeof(type) <= 4B) or points to a value
        // storage
        mValueOrOffset = buffer.getInt();
        // Log.d(SkyControlConst.DEBUG_TAG, "Value or offset: " + mValueOrOffset + "\n");
    }

    public int getType() {
        return mType;
    }

    public int getCount() {
        return mCount;
    }

    public int getValueOrOffset() {
        return mValueOrOffset;
    }
}


text:
<?php
namespace oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2;

/**
 * @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2
 * @xmlType DamageRemarksType
 * @xmlName DamageRemarks
 * @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\DamageRemarks
 */
class DamageRemarks
	extends DamageRemarksType
	{

} // end class DamageRemarks