text:
.class Lcom/android/server/devicepolicy/DeviceOwner$OwnerInfo;
.super Ljava/lang/Object;
.source "DeviceOwner.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/devicepolicy/DeviceOwner;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "OwnerInfo"
.end annotation

# instance fields
.field public final admin:Landroid/content/ComponentName;

.field public final name:Ljava/lang/String;

.field public final packageName:Ljava/lang/String;

# direct methods
.method public constructor <init>(Ljava/lang/String;Landroid/content/ComponentName;)V
    .locals 1
    .param p1, "name"    # Ljava/lang/String;
    .param p2, "admin"    # Landroid/content/ComponentName;

    .prologue
    .line 405
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 406
    iput-object p1, p0, Lcom/android/server/devicepolicy/DeviceOwner$OwnerInfo;->name:Ljava/lang/String;

    .line 407
    iput-object p2, p0, Lcom/android/server/devicepolicy/DeviceOwner$OwnerInfo;->admin:Landroid/content/ComponentName;

    .line 408
    invoke-virtual {p2}, Landroid/content/ComponentName;->getPackageName()Ljava/lang/String;

    move-result-object v0

    iput-object v0, p0, Lcom/android/server/devicepolicy/DeviceOwner$OwnerInfo;->packageName:Ljava/lang/String;

    .line 405
    return-void
.end method

.method public constructor <init>(Ljava/lang/String;Ljava/lang/String;)V
    .locals 2
    .param p1, "name"    # Ljava/lang/String;
    .param p2, "packageName"    # Ljava/lang/String;

    .prologue
    .line 399
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 400
    iput-object p1, p0, Lcom/android/server/devicepolicy/DeviceOwner$OwnerInfo;->name:Ljava/lang/String;

    .line 401
    iput-object p2, p0, Lcom/android/server/devicepolicy/DeviceOwner$OwnerInfo;->packageName:Ljava/lang/String;

    .line 402
    new-instance v0, Landroid/content/ComponentName;

    const-string/jumbo v1, ""

    invoke-direct {v0, p2, v1}, Landroid/content/ComponentName;-><init>(Ljava/lang/String;Ljava/lang/String;)V

    iput-object v0, p0, Lcom/android/server/devicepolicy/DeviceOwner$OwnerInfo;->admin:Landroid/content/ComponentName;

    .line 399
    return-void
.end method

# virtual methods
.method public dump(Ljava/lang/String;Ljava/io/PrintWriter;)V
    .locals 2
    .param p1, "prefix"    # Ljava/lang/String;
    .param p2, "pw"    # Ljava/io/PrintWriter;

    .prologue
    .line 411
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {v0, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string/jumbo v1, "admin="

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget-object v1, p0, Lcom/android/server/devicepolicy/DeviceOwner$OwnerInfo;->admin:Landroid/content/ComponentName;

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    invoke-virtual {p2, v0}, Ljava/io/PrintWriter;->println(Ljava/lang/String;)V

    .line 412
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {v0, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string/jumbo v1, "name="

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget-object v1, p0, Lcom/android/server/devicepolicy/DeviceOwner$OwnerInfo;->name:Ljava/lang/String;

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    invoke-virtual {p2, v0}, Ljava/io/PrintWriter;->println(Ljava/lang/String;)V

    .line 413
    invoke-virtual {p2}, Ljava/io/PrintWriter;->println()V

    .line 410
    return-void
.end method


text:
namespace sling {
namespace nlp {

void EntityResolver::Init(Store *commons, const PhraseTable *aliases) {
  aliases_ = aliases;
  CHECK(names_.Bind(commons));
}

ResolverContext::ResolverContext(Store *store, const EntityResolver *resolver)
    : store_(store), resolver_(resolver), tracking_(store),
      n_popularity_(resolver->n_popularity_.handle()),
      n_links_(resolver->n_links_.handle()) {}

void ResolverContext::AddTopic(Handle entity) {
  // Add entity to context model.
  context_[entity] += resolver_->topic_weight_;
  Track(entity);
}

void ResolverContext::AddEntity(Handle entity) {
  // Add entity to context model.
  float popularity = GetPopularity(entity);
  context_[entity] += resolver_->mention_weight_ / popularity;
  Track(entity);

  // Add outbound links to context model.
  FrameDatum *item = store_->GetFrame(entity);
  Handle item_links = item->get(n_links_);
  if (!item_links.IsNil()) {
    FrameDatum *links = store_->GetFrame(item_links);
    for (const Slot *s = links->begin(); s != links->end(); ++s) {
      Handle link = s->name;
      float count = s->value.AsInt();
      float popularity = GetPopularity(link);
      context_[link] += count / popularity;
    }
  }
}

void ResolverContext::AddMention(uint64 fp, CaseForm form,
                                 Handle entity, int count) {
  // Only the first resolved entity for the mention phrase is kept.
  Mention &mention = mentions_[fp];
  if (mention.entity.IsNil()) {
    mention.entity = entity;
    mention.form = form;
    mention.count = count * resolver_->mention_boost_;
    Track(entity);
  } else if (entity == mention.entity) {
    mention.count += count * resolver_->mention_boost_;
  }
}

void ResolverContext::Score(uint64 fp, CaseForm form,
                            Candidates *candidates) const {
  // Get candidates from phrase table.
  PhraseTable::MatchList matches;
  resolver_->aliases_->Lookup(fp, &matches);

  // Add phrase match from mention model.
  auto f = mentions_.find(fp);
  if (f != mentions_.end()) {
    // Add local mention if it is not already a candidate.
    const Mention &mention = f->second;
    bool found = false;
    for (auto &c : matches) {
      if (c.item == mention.entity) {
        c.count += mention.count;
        found = true;
        break;
      }
    }
    if (!found) {
      PhraseTable::Match m;
      m.item = mention.entity;
      m.count = mention.count;
      m.form = mention.form;
      m.reliable = true;
      matches.emplace_back(m);
    }
  }

  // Score candidates.
  candidates->clear();
  for (auto &m : matches) {
    if (m.item.IsNil()) continue;

    // Compute score for candidate.
    float context = ContextScore(m.item, resolver_->base_context_score);

    // Add scores from outbound links for candidate.
    if (!m.item.IsNil()) {
      FrameDatum *item = store_->GetFrame(m.item);
      Handle item_links = item->get(n_links_);
      if (!item_links.IsNil()) {
        FrameDatum *links = store_->GetFrame(item_links);
        for (const Slot *s = links->begin(); s != links->end(); ++s) {
          context += ContextScore(s->name) * s->value.AsInt();
        }
      }
    }

    // Combine context score with name prior.
    float score = context;
    score *= m.count;

    // Apply case form penalty.
    if (form != CASE_NONE && m.form != CASE_NONE && form != m.form) {
      score *= resolver_->case_form_penalty;
    }

    // Add final score to top-k candidate list. Local match has empty id.
    candidates->push(Candidate(m.item, score, m.count, context, m.id.empty()));
  }
}

Handle ResolverContext::Resolve(uint64 fp, CaseForm form) const {
  Candidates best(1);
  Score(fp, form, &best);
  return best.empty() ? Handle::nil() : best[0].entity;
}

}  // namespace nlp
}  // namespace sling

redpajama_set_name: RedPajamaGithub


text:
import pytest
import os
from pathlib2 import os_path_realpath, _make_selector, Path

@pytest.mark.skipif(os.name != "nt", reason="Windows only test")
def test_realpath_nt_nul():
    assert os_path_realpath(b'nul') == b'\\\\.\\NUL'
    assert os_path_realpath('nul') == '\\\\.\\NUL'

@pytest.mark.skipif(os.name != "nt", reason="Windows only test")
def test_realpath_nt_unc():
    assert os_path_realpath('\\\\?\\UNC\\localhost\\C$') == '\\\\?\\UNC\\localhost\\C$'

@pytest.mark.skipif(os.name != "nt", reason="Windows only test")
def test_realpath_nt_badpath():
    with pytest.raises(FileNotFoundError):
        os_path_realpath('\\\\invalid\\server')
    with pytest.raises(FileNotFoundError):
        os_path_realpath('does/not/exist', strict=True)

def test_realpath_bytes():
    assert os_path_realpath(b'abc.xyz').endswith(b'abc.xyz')

def test_make_selector():
    with pytest.raises(ValueError, match="Invalid pattern"):
        _make_selector(("x**x",), None)

def test_parents_repr():
    p = Path("/some/path/here")
    assert repr(p.parents).endswith(".parents>")

def test_bad_glob():
    p = Path("some/path")
    files = p.glob("/test/**")
    with pytest.raises(NotImplementedError,
                       match="Non-relative patterns are unsupported"):
        next(files)

@pytest.mark.skipif(os.name != "nt", reason="only for windows")
def test_is_mount_windows():
    p = Path("some/path")
    with pytest.raises(NotImplementedError):
        p.is_mount()


text:
<?php

namespace Scrutinizer\PhpAnalyzer\DataFlow\TypeInference\MethodInterpreter;

class ChainableMethodInterpreter implements \Scrutinizer\PhpAnalyzer\DataFlow\TypeInference\MethodInterpreter\MethodInterpreterInterface
{
    private $interpreters;

    /**
     * @param array<MethodInterpreterInterface> $interpreters
     */
    public function __construct(array $interpreters)
    {
        $this->interpreters = $interpreters;
    }

    public function getPreciserMethodReturnTypeKnowingArguments(\Scrutinizer\PhpAnalyzer\Model\ContainerMethodInterface $method, array $argValues, array $argTypes)
    {
        foreach ($this->interpreters as $interpreter) {
            if (null !== $restrictedType = $interpreter->getPreciserMethodReturnTypeKnowingArguments($method, $argValues, $argTypes)) {
                return $restrictedType;
            }
        }

        return null;
    }
}


text:
const env = process.env.NODE_ENV || 'development';
const API_URL = env === 'development' ? 'http://localhost:3000/api/' : '/api/'

export default {
  API_URL: API_URL,
  BADGES_URL: API_URL + 'badges/',
  CURRENT_EVENT_URL: API_URL + 'events/current',
  EVENTS_URL: API_URL + 'events/',
  FORGOT_URL: API_URL + 'forgot/',
  LOGIN_URL: API_URL + 'authenticate/',
  PROFILE_URL: API_URL + 'profile/',
  RESET_API_URL: API_URL + 'reset/',
  RESET_URL: env === 'development' ? 'http://localhost:8080/reset/' : 'http://mbu.online/reset/',
  SCOUTS_URL: API_URL + 'scouts/',
  SIGNUP_URL: API_URL + 'signup/',
  USERS_URL: API_URL + 'users/'
};


text:
   './seasonreview.html'

///// HELPERS /////

Template.seasonreviewPage.helpers({
    seasonreviewEach() {
        return DevTest.find( { spirit: {$exists: true}}, {sort: {createdAt: -1}}); },

});

////////* seasonreview Events *//////


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Transactional_False extends Controller_Transactional_Undeclared {

	public $_transactional = false;

}


text:
import copy
from itertools import cycle, islice

from model import *
import view
import parserLastFM

__author__ = "Rafael Arquero Gimeno"

def add(users, parser):
    """

    :type users: Hash
    """
    for user in islice(parser, 5000):
        users.insert(user)
    return users

def search(source, minimum=0.0, maximum=1.0):
    """

    :type source: Hash
    """
    assert minimum <= maximum

    result = Hash(source.size)

    for key in xrange(source.size):
        source_tree = source.table[key]

        if source_tree:  # not empty
            min_node, max_node = source_tree.min, source_tree.max

            if minimum <= min_node and max_node <= maximum:
                result.table[key] = copy.copy(source_tree)
            elif min_node <= minimum <= max_node:
                result.table[key] = copy.copy(source_tree).deleteLower(minimum)
            elif min_node <= maximum <= max_node:
                result.table[key] = copy.copy(source_tree).deleteHigher(maximum)

    return cycle(result) if result else None

def useful_info(source):
    return ""

def emptyType():
    return Hash()

if __name__ == "__main__":
    parser = parserLastFM.parser("LastFM_small.dat")
    app = view.MainApp(parser, add, search, None, useful_info, emptyType())
    app.mainloop()


text:
<?php

  if($_POST){
    include("DBconnect.php");

    $TeamID = mysqli_real_escape_string($conn, $_POST["TeamID"]);

    $sql = "UPDATE `team`
            SET `Active`= 1
            WHERE `TeamID` = '$TeamID'";

    if(mysqli_query($conn, $sql)){
        echo "resurrect successful";
    }else{
      echo "something went wrong";
    }
  }else{
    echo "Post error";
  }
?>


text:
package com.impetus.client.crud.datatypes.entities;

import java.sql.Timestamp;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import com.impetus.kundera.index.Index;
import com.impetus.kundera.index.IndexCollection;

@Entity
@Table(name = "StudentTimestamp", schema = "KunderaCassandraDataType@CassandraDataTypeTest")
@IndexCollection(columns = { @Index(name = "age"), @Index(name = "name") })
public class StudentTimestamp
{

    @Id
    private Timestamp id;

    @Column(name = "AGE")
    private short age;

    @Column(name = "NAME")
    private String name;

    /**
     * @return the id
     */
    public Timestamp getId()
    {
        return id;
    }

    /**
     * @param id
     *            the id to set
     */
    public void setId(Timestamp id)
    {
        this.id = id;
    }

    /**
     * @return the age
     */
    public short getAge()
    {
        return age;
    }

    /**
     * @param age
     *            the age to set
     */
    public void setAge(short age)
    {
        this.age = age;
    }

    /**
     * @return the name
     */
    public String getName()
    {
        return name;
    }

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

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: naggelakis
 * Date: 24/3/15
 * Time: 15:53
 */

namespace HSpace\Bundle\ApiCacherBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;

class EraseCacheListener
{
    protected $request;
    protected $root_cache;

    public function __construct(Request $request) // this is @service_container
    {
        $this->request = $request;
        $this->root_cache = __DIR__.'/../Cache';
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        $erase = $request->get('eraseCache');
        if(isset($erase) && $erase === 'true'){
            array_map('unlink', glob($this->root_cache.'/*'));
        }
    }

}


text:
  Bourideys est
       un village
       situé dans le département de Gironde en Aquitaine. Elle totalisait 86 habitants en 2008.

Si vous pensez emmenager à Bourideys, vous pourrez aisément trouver une maison à vendre.

La ville compte quelques  équipements sportifs, elle propose entre autres un bassin de natation, un terrain de tennis et une boucle de randonnée.

À proximité de Bourideys sont localisées les communes de
Saint-Léger-de-Balson à 7 km, 272 habitants,
Sore située à 11 km, 985 habitants,
Balizac située à 13 km, 376 habitants,
Villandraut localisée à 11 km, 900 habitants,
Lucmau à 11 km, 237 habitants,
Pompéjac localisée à 13 km, 234 habitants,
 entre autres. De plus, Bourideys est située à seulement 26 km de Langon.

Le parc d'habitations, à Bourideys, était réparti en 2011 en six appartements et 53 maisons soit
 un marché plutôt équilibré.


text:
<?php

namespace frontend\modules\complaint\controllers;

use common\classes\Debug;
use common\models\db\Complaint;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;

class DefaultController extends Controller
{

    public $layout = 'page';

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionAdd(){
        $model = new Complaint();
        if ($model->load(Yii::$app->request->post())) {
            $model->dt_add = time();
            $model->read_complaint = 0;
            $model->from_user = Yii::$app->user->id;
            $model->save();
            Yii::$app->session->setFlash('success','Жалоба отправленна');
            $complaint = Complaint::find()->where(['from_user'=>Yii::$app->user->id])->all();
            return $this->render('complaint', ['complaint' => $complaint]);
        }
        else {
            return $this->render('add', ['model' => $model]);
        }
    }

    public function actionDel(){
        $model = Complaint::deleteAll(['id' => $_GET['id']]);
        Yii::$app->session->setFlash('success','Жалоба удалена');
        $complaint = Complaint::find()->where(['from_user'=>Yii::$app->user->id])->all();
        return $this->render('complaint', ['complaint' => $complaint]);
    }

    public function actionView(){
        $complaint = Complaint::find()->where(['id' => $_GET['id']])->one();
        return $this->render('view', ['complaint' => $complaint]);
    }

    public function actionComplaint(){
        $complaint = Complaint::find()->where(['from_user'=>Yii::$app->user->id])->all();
        return $this->render('complaint', ['complaint' => $complaint]);
    }
}


text:
TapeFollower::TapeFollower(int* leftInputVar, int* midInputVar, int* rightInputVar, double* output)
{
	leftInput = leftInputVar;
	midInput = midInputVar;
	rightInput = rightInputVar;
	Output = output;

	fixedSampleRate = false;

	lastTime = millis();
	lastError = 0;
	error = 0;
	lastExtremeError = 0;

	outMax = 100;
	outMin = -100;

	kp = new double(0);
	ki = new double(0);
	kd = new double(0);

    THRESHOLD = 250;
    LeftOffset = 0;
    MidOffset = 0;
    RightOffset = 0;
}

double TapeFollower::Compute()
{
	timeChange = millis() - lastTime;

	if (fixedSampleRate == true && timeChange < SampleTime)
	{
		// Don't update the PID loop
		return *Output;
	} //Else, uses the time since last update to calculate PID

	updateOldData();

	error = calculateError();

	PTerm = *kp*(error);
	DTerm = *kd*(error - lastError) / timeChange;
	ITerm += *ki*(error)*timeChange;

	StandardCalc::boundValueBetween(&ITerm, outMin, outMax);

	*Output = PTerm + ITerm + DTerm;

	// Output is useful for testing
	return *Output;
}

void TapeFollower::updateOldData()
{
	lastError3 = lastError2;
	lastError2 = lastError;
	lastError = error;
	if (error == -3 || error == 3)
	{
		lastExtremeError = error;
	}
	lastTime = millis();
}

double TapeFollower::calculateError()
{
	if (goingStraight())
	{
		error = 0;
	}
	else if (slightlyRight())
	{
		error = 1;
	}
	else if (slightlyLeft())
	{
		error = -1;
	}
	else if (moreLeft())
	{
		error = -2;
	}
	else if (moreRight())
	{
		error = 2;
	}
	else if (tooMuchOnLeft())
	{
		error = -3;
	}
	else if (tooMuchOnRight())
	{
		error = 3;
	}
	// else if (missedState())
	// {
	// 	error = -lastExtremeError;
	// }
	return error;
}

void TapeFollower::attach_Kd_To(double* newKd) { delete kd; kd = newKd; }

void TapeFollower::attach_Kp_To(double* newKp) { delete kp;	kp = newKp; }

void TapeFollower::attach_Ki_To(double* newKi) { delete ki; ki = newKi; }

void TapeFollower::setKp(double newKp) { *kp = newKp; }

void TapeFollower::setKd(double newKd) { *kd = newKd; }

void TapeFollower::setKi(double newKi) { *ki = newKi; }

double TapeFollower::GetKp() { return *kp; }

double TapeFollower::GetKi() { return *ki; }

double TapeFollower::GetKd() { return *kd; }

double TapeFollower::GetError() { return error; }

void TapeFollower::tune(double newKp, double newKi, double newKd)
{
	*kp = newKp;
	*ki = newKi;
	*kd = newKd;
}

void TapeFollower::SetSampleTime(int sampleTimeInMilliseconds)
{
	SampleTime = sampleTimeInMilliseconds;
	fixedSampleRate = true;
}

inline void TapeFollower::AutoSample() { fixedSampleRate = false; }

void TapeFollower::setBounds(double newOutputMin, double newOutputMax)
{
	outMax = newOutputMax;
	outMin = newOutputMin;
}

void TapeFollower::SetThreshold(double newThreshold)
{
    THRESHOLD = newThreshold;
}

void TapeFollower::SetOffsets(double left, double mid, double right)
{
    LeftOffset = left;
    MidOffset = mid;
    RightOffset = right;
}

bool TapeFollower::goingStraight() { return  (*leftInput < THRESHOLD + LeftOffset) && (*midInput >= THRESHOLD + MidOffset) && (*rightInput < THRESHOLD + RightOffset); }

bool TapeFollower::slightlyLeft() { return (*leftInput < THRESHOLD + LeftOffset) && (*midInput >= THRESHOLD + MidOffset) && (*rightInput >= THRESHOLD + RightOffset); }

bool TapeFollower::slightlyRight() { return (*leftInput >= THRESHOLD + LeftOffset) && (*midInput >= THRESHOLD + MidOffset) && (*rightInput < THRESHOLD + RightOffset); }

bool TapeFollower::moreLeft() { return (*leftInput < THRESHOLD + LeftOffset) && (*midInput < THRESHOLD + MidOffset) && (*rightInput >= THRESHOLD + RightOffset); }

bool TapeFollower::moreRight() { return (*leftInput >= THRESHOLD + LeftOffset) && (*midInput < THRESHOLD + MidOffset) && (*rightInput < THRESHOLD + RightOffset); }

bool TapeFollower::offTape() { return (*leftInput < THRESHOLD + LeftOffset) && (*midInput < THRESHOLD + MidOffset) && (*rightInput < THRESHOLD + RightOffset); }

bool TapeFollower::tooMuchOnRight() { return offTape() && (lastError > 0) && (lastError2 > 0); }

bool TapeFollower::tooMuchOnLeft() { return offTape() && (lastError < 0) && (lastError2 < 0); }

bool TapeFollower::missedState() {return offTape() && (lastError == 0); }


text:
package com.graphhopper.routing.util.spatialrules;

import com.graphhopper.GraphHopper;
import com.graphhopper.json.geo.JsonFeature;
import com.graphhopper.json.geo.JsonFeatureCollection;
import com.graphhopper.routing.ev.Country;
import com.graphhopper.routing.util.parsers.SpatialRuleParser;
import com.graphhopper.routing.util.parsers.TagParser;
import com.graphhopper.routing.util.parsers.TagParserFactory;
import com.graphhopper.util.Helper;
import com.graphhopper.util.PMap;
import org.locationtech.jts.geom.Envelope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * Helper class to build the spatial rule index. This is kind of an ugly plugin mechanism to avoid requiring a
 * jackson dependency on the core.
 *
 * @author Robin Boldt
 */
public class SpatialRuleLookupHelper {

    private static final Logger logger = LoggerFactory.getLogger(SpatialRuleLookupHelper.class);
    static String JSON_ID_FIELD = "ISO_A3";

    /**
     * This method limits the JsonFeatures to the specified subset
     */
    static List<JsonFeatureCollection> reorder(List<JsonFeatureCollection> jsonFeatureCollections, List<String> subset) {
        Map<String, JsonFeature> map = new LinkedHashMap<>();
        for (JsonFeatureCollection featureCollection : jsonFeatureCollections) {
            for (JsonFeature jsonFeature : featureCollection.getFeatures()) {
                String id = (String) jsonFeature.getProperty(JSON_ID_FIELD);
                if (!Helper.isEmpty(id))
                    map.put(Helper.toLowerCase(id), jsonFeature);
            }
        }
        if (map.isEmpty())
            throw new IllegalArgumentException("Input JsonFeatureCollection cannot be empty. Subset: " + subset + ", original.size:" + jsonFeatureCollections.size());

        List<JsonFeature> newCollection = new ArrayList<>();
        for (String val : subset) {
            JsonFeature jsonFeature = map.get(val);
            if (jsonFeature == null)
                throw new IllegalArgumentException("SpatialRule does not exist. ID: " + val);
            newCollection.add(jsonFeature);
        }
        JsonFeatureCollection coll = new JsonFeatureCollection();
        coll.getFeatures().addAll(newCollection);
        return Arrays.asList(coll);
    }

    public static void buildAndInjectCountrySpatialRules(GraphHopper graphHopper, Envelope maxBounds, List<JsonFeatureCollection> jsonFeatureCollections) {
        List<String> subset = new ArrayList<>();
        for (Country c : Country.values()) {
            if (c != Country.DEFAULT)
                subset.add(c.toString());
        }
        final SpatialRuleLookup index = SpatialRuleLookupBuilder.buildIndex(reorder(jsonFeatureCollections, subset),
                JSON_ID_FIELD, new CountriesSpatialRuleFactory(), maxBounds);
        logger.info("Set spatial rule lookup with {} rules", index.getRules().size());
        final TagParserFactory oldTPF = graphHopper.getTagParserFactory();
        graphHopper.setTagParserFactory(new TagParserFactory() {

            @Override
            public TagParser create(String name, PMap configuration) {
                if (name.equals(Country.KEY))
                    return new SpatialRuleParser(index, Country.create());

                return oldTPF.create(name, configuration);
            }
        });
    }
}


text:
<!DOCTYPE html>

  <title>About the website</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <link href="http://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" type="text/css">
  <link href="http://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      </button>
      Ceperunt in ea Manus

LOGOUT

SETTINGS

FORUMS

BLOG

My Profile

well development

          label 1
          label 2
          label 3
          label 4
          label 5
          label 6

        ×

Other NGO sites

       NGO websites

Link

Link

Link

Upload details of person in need

        <form action="/upload" method="post" enctype="multipart/form-data" style="margin-left: 80px;">

            <input type="file" name="image">

            Latitude : <input id="field1" type="text" name="lat">

            Longitude : <input id="field2" type="text" name="long">

          <button type="Submit" style="float: center;" class="btn btn-primary">Submit</button>
        </form>

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      </button>
      Ceperunt in ea Manus


text:
module Fog
  module AWS
    class ELB
      class Real

        require 'fog/aws/parsers/elb/tag_list_parser'

        # returns a Hash of tags for a load balancer
        # http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_DescribeTags.html
        # ==== Parameters
        # * elb_id <~String> - name(s) of the ELB instance whose tags are to be retrieved (allows 1-20 of them)
        # ==== Returns
        # * response<~Excon::Response>:
        #   * body<~Hash>:
        def describe_tags(elb_ids)
          request({
              'Action' => 'DescribeTags',
              :parser  => Fog::Parsers::AWS::ELB::TagListParser.new
            }.merge(Fog::AWS.indexed_param('LoadBalancerNames.member.%d', elb_ids))
          )
        end
        # def describe_tags(filters = {})
        #   params = Fog::AWS.indexed_filters(filters)
        #   request({
        #     'Action'    => 'DescribeTags',
        #     :idempotent => true,
        #     :parser     => Fog::Parsers::AWS::Compute::DescribeTags.new
        #   }.merge!(params))
        # end

      end

      class Mock

        def describe_tags(elb_id)
          response = Excon::Response.new

          if server = self.data[:load_balancers][elb_id]
            response.status = 200
            ##{"DescribeTagsResult"=>{"LoadBalancers"=>[{"Tags"=>{"Name"=>"2esakowski-test-opsworks-elb"}, "LoadBalancerName"=>"esakowski-test-opsworks"}]}}
            response.body = {"DescribeTagsResult"=>{"LoadBalancers"=>[{"Tags"=>self.data[:tags][elb_id], "LoadBalancerName"=>elb_id}]}}

#            response.body = {
#              "DescribeTagsResult" =>
#               {"TagDescriptions" => self.data[:tags][elb_id]}
#            }
            response
          else
            raise Fog::AWS::ELB::NotFound.new("Elastic load balancer #{elb_id} not found")
          end
        end

      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/home/rodrigo/Desenvolvimento/work.androidstudio/Sunshine/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/21.0.3/res/values-xlarge-land/values.xml -->
    <eat-comment/>
    <dimen name="abc_search_view_text_min_width">256dip</dimen>
</resources>


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Picturepark.SDK.V1.Contract;

namespace Picturepark.SDK.V1.Tests.Fixtures
{
    public class ChannelFixture : ClientFixture
    {
        private readonly ConcurrentQueue<string> _createdChannelIds = new ConcurrentQueue<string>();

        public async Task<IReadOnlyList<Channel>> CreateChannels(int count)
        {
            var createRequests = Enumerable.Range(0, count).Select(_ =>
                new ChannelCreateRequest
                {
                    Names = new TranslatedStringDictionary
                    {
                        { "en", $"Channel_test_{Guid.NewGuid()}" }
                    },
                    SearchIndexId = "RootContentSearchIndex",
                    ViewForAll = false
                }).ToArray();

            var tasks = createRequests.Select(r => Client.Channel.CreateAsync(r));

            var created = await Task.WhenAll(tasks).ConfigureAwait(false);

            foreach (var set in created)
            {
                _createdChannelIds.Enqueue(set.Id);
            }

            return created.ToArray();
        }

        public async Task<Channel> CreateChannel()
        {
            return (await CreateChannels(1)).Single();
        }

        public override void Dispose()
        {
            if (!_createdChannelIds.IsEmpty)
            {
                foreach (var id in _createdChannelIds)
                {
                    try
                    {
                        Client.Channel.DeleteAsync(id).GetAwaiter().GetResult();
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                }
            }

            base.Dispose();
        }
    }
}


text:
package com.feeyo.net.nio.util;

import java.util.Calendar;

/**
 * 弱精度的计时器,考虑性能不使用同步策略。
 **/
public class TimeUtil {

	private static volatile long CURRENT_TIME = System.currentTimeMillis();
	private static volatile int CURRENT_TIME_SECOND_INDEX = (int) ((CURRENT_TIME / 1000) % 60);

	private static volatile int OFFSET = 0;

	static {
		Calendar cal = Calendar.getInstance();
		int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET);
		int dstOffset = cal.get(java.util.Calendar.DST_OFFSET);
		OFFSET = zoneOffset + dstOffset;
	}

	public static final long currentUtcTimeMillis() {
		return CURRENT_TIME - OFFSET;
	}

	public static final long currentTimeMillis() {
		return CURRENT_TIME;
	}

	public static final int currentTimeSecondIndex() {
		return CURRENT_TIME_SECOND_INDEX;
	}

	public static final long currentTimeNanos() {
		return System.nanoTime();
	}

	public static final void update() {
		CURRENT_TIME = System.currentTimeMillis();
		CURRENT_TIME_SECOND_INDEX = (int) ((CURRENT_TIME / 1000) % 60);
	}

}


text:
$(function() {
	//微信浏览器不支持calc,在JS里面解决
	var $picture = $('.cover-picture-picture'),
		$picChild = $picture.children('div'),
		pictureParentHeight = $picture.parent().height();
	$picture.height(pictureParentHeight - 145);
	$picChild.height(pictureParentHeight - 145 - 10);

	$.fn['animateCss']=function (animationName) {
		var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
		$(this).addClass('animated ' + animationName).one(animationEnd, function() {
			$(this).removeClass('animated ' + animationName);
		});
	};

	var baseUrl = '../../../public/';
	var url = baseUrl + 'invitationInfo/' + getParam('id');
	$.get(url, function(data) {
		init(data);
	});

	function getParam(paramName) {
		var ret = '',
			matches =location.search.match(paramName + '=([^&]*)');
		if(matches) {
			ret = matches[1];
		}
		return ret;
	}

	function htmlEncode(value){
		//create a in-memory div, set it's inner text(which jQuery automatically encodes)
		//then grab the encoded contents back out.  The div never exists on the page.
		return $('
').text(value).html();
	}

	function init(jsonData) {
		var $pages = $('li.page'),
			maxIndex = $pages.length,
			currentIndex = maxIndex > 0 ? 1 : maxIndex,
			isAnimating = false,
			$ul = $('.content > ul'),
			ulHeight = $ul.height(),
			ulWidth = $ul.width(),
			$canvasList = [],
			$downArrow = $('.downArrow'),
			$upArrow = $('.upArrow'),
			$musicCtrl = $('#musicCtrl'),
			Media = new Audio(jsonData.music),
			$pictureCorridor = $('#pictureCorridor'),
			$mask = $('#mask'),
			imgSrcList = {},
			inTransition = false;
		Media.loop = true;
		$downArrow.show();
		$pictureCorridor.hide();
		$downArrow.tap(function() {
			$ul.trigger('swipeUp');
		});
		$upArrow.tap(function() {
			$ul.trigger('swipeDown');
		});
		if('ontouchend' in document) {
			$musicCtrl.tap(function(e) {
				$musicCtrl.hasClass('stop') ? startMusic() : stopMusic();
			});
		} else {
			$musicCtrl.on('click', function(e) {
				$musicCtrl.hasClass('stop') ? startMusic() : stopMusic();
			});
		}
		Media.addEventListener('canplay', function() {
			Media.play();
		});
		document.addEventListener('touchmove',function(event){
			event.preventDefault();
		},false);
		$ul.swipeUp(function() {
			if(currentIndex < maxIndex) {
				currentIndex++;
				if(!showCurrentPage()) {
					currentIndex--;
				}
			}
		});
		$ul.swipeDown(function() {
			if(currentIndex > 0) {
				currentIndex--;
				if(!showCurrentPage()) {
					currentIndex++;
				}
			}
		});
		var spinner = new Spinner().spin();
		$mask.append(spinner.el);
		loadPic(jsonData.images).done(function() {
			$('.scrolldiv').each(function() {
				touchDiv(this, {
					scrollDivToTop: function() {
						if(currentIndex > 1) {
							$upArrow.show();
						}
					},
					scrollDivTouchMove: function() {
						$upArrow.hide();
						$downArrow.hide();
					},
					topToTopFunc: function() {
						$ul.trigger('swipeDown');
					},
					buttomToButtomFunc: function() {
						$ul.trigger('swipeUp');
					},
					scrollDivToBottom: function() {
						if(currentIndex < maxIndex){
							$downArrow.show();
						}
					}
				});
			});
			$.each(imgSrcList, function(key, value) {
				var $_ul = $pictureCorridor.children('ul'),
					$li = $('

');
				$li.css('background-image', 'url(\'' + value + '\')');
				$_ul.append($li);
			});
			mobileSlide($pictureCorridor.find('ul')[0], {
				beforeTransitionFunc: function() {
					inTransition = true;
				},
				afterTransitionFunc: function() {
					inTransition = false;
				}
			});
			$mask.hide();
		});

		(function() {
			var deltaX = 0, deltaY = 0, firstX, firstY, lastX, lastY, _mousedown = false, tapTimeOut = 50, recordTime;;
			$('#pic_page').on('touchend mouseup', 'canvas', function(e) {
				e.stopPropagation();
				if(!e.touches && !_mousedown) {
					return;
				}
				var spendTime = new Date().getTime() - recordTime;
				if(deltaX <30 && deltaY < 30 && !Number.isNaN(spendTime) && spendTime >= tapTimeOut) {
					var index = $canvasList.index(this);
					li = $pictureCorridor.children('ul').children()[index];
					$(li).css('display', 'block').siblings().css('display', 'none');
					$pictureCorridor.show();
					$pictureCorridor.animateCss('fadeIn');
				}
				deltaX = deltaY = 0;
			}).on('mouseout', 'canvas', function(e) {
				e.stopPropagation();
				_mousedown = false;
				deltaX = deltaY = 0;
			}).on('touchmove mousemove', 'canvas', function(e) {
				e.stopPropagation();
				if(e.touches) {
					lastX = e.touches[0].clientX;
					lastY = e.touches[0].clientY;
				} else if(_mousedown) {
					lastX = e.clientX;
					lastY = e.clientY;
				} else {
					return;
				}
				deltaX += Math.abs(lastX - firstX);
				deltaY += Math.abs(lastY - firstY);
			}).on('touchstart mousedown', 'canvas', function(e) {
				e.stopPropagation();
				recordTime = new Date().getTime();
				if(e.touches) {
					firstX = e.touches[0].clientX;
					firstY = e.touches[0].clientY;
				} else {
					firstX = e.clientX;
					firstY = e.clientY;
					_mousedown = true;
				}
			});
		})();

		(function() {
			var deltaX = 0, deltaY = 0, firstX, firstY, lastX, lastY, _mousedown = false, tapTimeOut = 50, recordTime;
			$pictureCorridor.on('touchend mouseup', function(e) {
				e.stopPropagation();
				if(!e.touches && !_mousedown) {
					return;
				}
				var spendTime = new Date().getTime() - recordTime;
				if(deltaX < 10 && deltaY < 10 && !Number.isNaN(spendTime) && spendTime >= tapTimeOut && !inTransition) {
					$pictureCorridor.hide();
				}
				deltaX = deltaY = 0;
			}).on('mouseout', function(e) {
				e.stopPropagation();
				_mousedown = false;
				deltaX = deltaY = 0;
			}).on('touchmove mousemove', function(e) {
				e.stopPropagation();
				if(e.touches) {
					lastX = e.touches[0].clientX;
					lastY = e.touches[0].clientY;
				} else if(_mousedown) {
					lastX = e.clientX;
					lastY = e.clientY;
				} else {
					return;
				}
				deltaX += Math.abs(lastX - firstX);
				deltaY += Math.abs(lastY - firstY);
			}).on('touchstart mousedown', function(e) {
				e.stopPropagation();
				recordTime = new Date().getTime();
				if(e.touches) {
					firstX = e.touches[0].clientX;
					firstY = e.touches[0].clientY;
				} else {
					firstX = e.clientX;
					firstY = e.clientY;
					_mousedown = true;
				}
			});
		})();

		(function() {
			var bMap = new BMap.Map('bMap');
			bMap.disableDragging();
			// 创建地址解析器实例
			var myGeo = new BMap.Geocoder();
			var marker,_point;
			myGeo.getPoint(jsonData.hotel_address, function(point){
				if (point) {
					_point = point;
					bMap.centerAndZoom(point, 15);
					marker = new BMap.Marker(point);
					bMap.addOverlay(marker);
					var opts = {
						width : 200,     // 信息窗口宽度
						height: 100,     // 信息窗口高度
						title : jsonData.hotel_name // 信息窗口标题
					};
					var infoWindow = new BMap.InfoWindow("地址:"+jsonData.hotel_address, opts);  // 创建信息窗口对象
					if(marker && _point) {
						marker.addEventListener('click', function() {
							bMap.openInfoWindow(infoWindow, _point);
						});
						bMap.openInfoWindow(infoWindow, _point);
					}
				}
			}, "");
		})();

		(function() {
			var $blessBtn = $('#bless'),
				$commentForm = $('#commentForm'),
				$sendBtn = $('#send_btn'),
				$textarea = $('#comment');
			if($textarea.length > 0) {
				addScroll($textarea[0]);
			}
			$blessBtn.on('touchend mousedown', function(e){
				$commentForm.css({
					left: 0
				});
			});
			$sendBtn.on('touchend mousedown', function() {
				var name = $('#custom_name').val(),
					comment = $('#comment').val();
				if(!name) {
					$('#custom_name').addClass('error-input');
					return;
				}
				if(!comment) {
					$('#comment').addClass('errot-input');
					return;
				}
				var url = baseUrl + 'custom/addcomment/' + getParam('id');
				$.get(url, {
					name: name,
					comment: comment
				});
				prependComment({name: name, comment: comment});
				$commentForm.css({
					left: '100%'
				});
			});
			$commentForm.on('touchmove', function(e) {
				e.preventDefault();
				e.stopPropagation();
			},false);

			$.each(jsonData.comments, function(i, obj) {
				appendComment(obj);
			});
			function appendComment(commentObj) {
				$('#comments_panel').append(createCommentDiv(commentObj.name,commentObj.comment));
			}
			function prependComment(commentObj) {
				$('#comments_panel').prepend(createCommentDiv(commentObj.name,commentObj.comment));
			}
			function createCommentDiv(name, comment) {
				var template = 	'
' +
									'
' +
										'
[[name]]:
' +
										'
[[comment]]
' +
									'
' +
								'
';
				template = template.replace(/\[\[name\]\]/, htmlEncode(name));
				template = template.replace(/\[\[comment\]\]/, htmlEncode(comment));
				return $(template);
			}
		})();

		function stopMusic() {
			$musicCtrl.addClass('stop');
			Media.pause();
		}
		function startMusic() {
			$musicCtrl.removeClass('stop');
			Media.play();
		}
		function showCurrentPage() {
			if(currentIndex > 0 && !isAnimating) {
				isAnimating = true;
				$ul.css('margin-top', -(currentIndex-1)*ulHeight);
				$ul.one('webkitTransitionEnd transitionend', function() {
					isAnimating = false;
				});
				$upArrow.hide();
				$downArrow.hide();
				if(currentIndex > 1) {
					$upArrow.show();
				} else {
					$upArrow.hide();
				}
				if(currentIndex < maxIndex) {
					$downArrow.show();
				} else {
					$downArrow.hide();
				}
				return true;
			}
			return false;
		}
		function loadPic(imgs) {
			var dtd = $.Deferred();
			var dtds = [];
			var $pic_page = $('#pic_page');
			var img = new Image();
			img.src = imgs[0];
			dtds.push($.Deferred());
			img.onload = function() {
				$picChild.css('background-image', 'url(\'' + img.src + '\')');
				dtds[0].resolve();
			};

			for(var i = 0; i < imgs.length; ++i) {
				$('<canvas></canvas>').appendTo($pic_page);
				dtds.push($.Deferred());
			}
			$canvasList = $pic_page.find('canvas');
			var canvasWidth = Math.floor(ulWidth / 4) - 1,
				canvasHeight = canvasWidth;
			$canvasList.each(function(i) {
				this.width = canvasWidth;
				this.height = canvasHeight;
				var img = new Image(),
					self = this;
				img.src = imgs[i];
				img.onload = function() {
					var ctx = self.getContext('2d'),
						canvas = document.createElement('canvas');
					imgSrcList[i] = imgs[i];

					ctx.drawImage(img,0,0,self.width,self.height);
					dtds[i+1].resolve();
				}
			});
			$.when.apply(null,dtds)
				.done(function() {
					dtd.resolve();
				});
			return dtd.promise();
		}

		//设置标记文字
		$('#groom_name').text(jsonData.groom_name);
		$('#bride_name').text(jsonData.bride_name);
		$('#wedding_date').text(jsonData.wedding_date);
		$('#wedding_time').text(jsonData.wedding_date +  ' ' + jsonData.wedding_time);
		$('#hotel_name').text(jsonData.hotel_name);
		$('#hotel_room').text(jsonData.hotel_room);
		$('#hotel_address').text(jsonData.hotel_address);
		$('#hotel_phone').text(jsonData.hotel_phone);
	}
});


text:
require 'spec_helper'
require 'whois/record/parser/whois.registry.qa.rb'

describe Whois::Record::Parser::WhoisRegistryQa, "status_registered.expected" do

  subject do
    file = fixture("responses", "whois.registry.qa/status_registered.txt")
    part = Whois::Record::Part.new(:body => File.read(file))
    described_class.new(part)
  end

  describe "#disclaimer" do
    it do
      lambda { subject.disclaimer }.should raise_error(Whois::AttributeNotSupported)
    end
  end
  describe "#domain" do
    it do
      subject.domain.should == "qtel.com.qa"
    end
  end
  describe "#domain_id" do
    it do
      lambda { subject.domain_id }.should raise_error(Whois::AttributeNotSupported)
    end
  end
  describe "#status" do
    it do
      subject.status.should == ["serverDeleteProhibited (Legacy)", "serverRenewProhibited (Legacy)", "serverTransferProhibited (Legacy)"]
    end
  end
  describe "#available?" do
    it do
      subject.available?.should == false
    end
  end
  describe "#registered?" do
    it do
      subject.registered?.should == true
    end
  end
  describe "#created_on" do
    it do
      lambda { subject.created_on }.should raise_error(Whois::AttributeNotSupported)
    end
  end
  describe "#updated_on" do
    it do
      lambda { subject.updated_on }.should raise_error(Whois::AttributeNotSupported)
    end
  end
  describe "#expires_on" do
    it do
      lambda { subject.expires_on }.should raise_error(Whois::AttributeNotSupported)
    end
  end
  describe "#registrar" do
    it do
      subject.registrar.should be_a(Whois::Record::Registrar)
      subject.registrar.id.should           == "QatarTelecom"
      subject.registrar.name.should         == "Qatar Telecom (Qtel) Q. S. C"
      subject.registrar.organization.should == "Qatar Telecom (Qtel) Q. S. C"
    end
  end
  describe "#registrant_contacts" do
    it do
      subject.registrant_contacts.should be_a(Array)
      subject.registrant_contacts.should have(1).items
      subject.registrant_contacts[0].should be_a(Whois::Record::Contact)
      subject.registrant_contacts[0].type.should         == Whois::Record::Contact::TYPE_REGISTRANT
      subject.registrant_contacts[0].id.should           == "QT11734"
      subject.registrant_contacts[0].name.should         == "DNS Administrator - Qtel Internet Services"
      subject.registrant_contacts[0].organization.should == nil
      subject.registrant_contacts[0].address.should      == nil
      subject.registrant_contacts[0].city.should         == nil
      subject.registrant_contacts[0].zip.should          == nil
      subject.registrant_contacts[0].state.should        == nil
      subject.registrant_contacts[0].country_code.should == nil
      subject.registrant_contacts[0].phone.should        == nil
      subject.registrant_contacts[0].fax.should          == nil
      subject.registrant_contacts[0].email.should        == "Visit portal.registry.qa for Web based WhoIs"
    end
  end
  describe "#admin_contacts" do
    it do
      lambda { subject.admin_contacts }.should raise_error(Whois::AttributeNotSupported)
    end
  end
  describe "#technical_contacts" do
    it do
      subject.technical_contacts.should be_a(Array)
      subject.technical_contacts.should have(1).items
      subject.technical_contacts[0].should be_a(Whois::Record::Contact)
      subject.technical_contacts[0].type.should         == Whois::Record::Contact::TYPE_TECHNICAL
      subject.technical_contacts[0].id.should           == "QT11734"
      subject.technical_contacts[0].name.should         == "DNS Administrator - Qtel Internet Services"
      subject.technical_contacts[0].organization.should == nil
      subject.technical_contacts[0].address.should      == nil
      subject.technical_contacts[0].city.should         == nil
      subject.technical_contacts[0].zip.should          == nil
      subject.technical_contacts[0].state.should        == nil
      subject.technical_contacts[0].country_code.should == nil
      subject.technical_contacts[0].phone.should        == nil
      subject.technical_contacts[0].fax.should          == nil
      subject.technical_contacts[0].email.should        == "Visit portal.registry.qa for Web based WhoIs"
    end
  end
  describe "#nameservers" do
    it do
      subject.nameservers.should be_a(Array)
      subject.nameservers.should have(2).items
      subject.nameservers[0].should be_a(Whois::Record::Nameserver)
      subject.nameservers[0].name.should == "ns1.qtel.com.qa"
      subject.nameservers[0].ipv4.should == "212.77.203.185"
      subject.nameservers[1].should be_a(Whois::Record::Nameserver)
      subject.nameservers[1].name.should == "ns2.qtel.com.qa"
      subject.nameservers[1].ipv4.should == "213.130.113.101"
    end
  end
end


text:
#ifndef PANGOLIN_VIDEO_UNPACK_H
#define PANGOLIN_VIDEO_UNPACK_H

#include <pangolin/pangolin.h>
#include <pangolin/video/video.h>

namespace pangolin
{

// Video class that debayers its video input using the given method.
class PANGOLIN_EXPORT UnpackVideo :
    public VideoInterface,
    public VideoFilterInterface,
    public VideoPropertiesInterface
{
public:
    UnpackVideo(VideoInterface* videoin, VideoPixelFormat new_fmt);
    ~UnpackVideo();

    //! Implement VideoInput::Start()
    void Start();

    //! Implement VideoInput::Stop()
    void Stop();

    //! Implement VideoInput::SizeBytes()
    size_t SizeBytes() const;

    //! Implement VideoInput::Streams()
    const std::vector<StreamInfo>& Streams() const;

    //! Implement VideoInput::GrabNext()
    bool GrabNext( unsigned char* image, bool wait = true );

    //! Implement VideoInput::GrabNewest()
    bool GrabNewest( unsigned char* image, bool wait = true );

    //! Implement VideoFilterInterface method
    std::vector<VideoInterface*>& InputStreams();

    //! Implement VideoPropertiesInterface method
    const json::value& DeviceProperties() const;

    //! Implement VideoPropertiesInterface method
    const json::value& FrameProperties() const;

protected:
    void Process(unsigned char* image, const unsigned char* buffer);

    std::vector<VideoInterface*> videoin;
    std::vector<StreamInfo> streams;
    size_t size_bytes;
    unsigned char* buffer;

    json::value device_properties;
    json::value frame_properties;
};

}

#endif // PANGOLIN_VIDEO_UNPACK_H


text:
package com.asakusafw.lang.inspection.cli;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.TreeMap;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.asakusafw.lang.inspection.InspectionNode;
import com.asakusafw.lang.inspection.InspectionNodeRepository;
import com.asakusafw.lang.inspection.json.JsonInspectionNodeRepository;
import com.asakusafw.lang.inspection.processor.DetailProcessor;
import com.asakusafw.lang.inspection.processor.DotProcessor;
import com.asakusafw.lang.inspection.processor.InspectionNodeProcessor;
import com.asakusafw.lang.inspection.processor.ListProcessor;
import com.asakusafw.lang.inspection.processor.StoreProcessor;

/**
 * Processes inspection object.
 */
public final class Cli {

    static final Logger LOG = LoggerFactory.getLogger(Cli.class);

    private static final InspectionNodeProcessor DEFAULT_PROCESSOR = new DetailProcessor();

    private static final Map<String, InspectionNodeProcessor> BUILTIN_PROCESSORS;
    static {
        Map<String, InspectionNodeProcessor> map = new LinkedHashMap<>();
        map.put("ls", new ListProcessor()); //$NON-NLS-1$
        map.put("list", new ListProcessor()); //$NON-NLS-1$
        map.put("txt", new DetailProcessor()); //$NON-NLS-1$
        map.put("text", new DetailProcessor()); //$NON-NLS-1$
        map.put("json", new StoreProcessor()); //$NON-NLS-1$
        map.put("dot", new DotProcessor()); //$NON-NLS-1$
        BUILTIN_PROCESSORS = map;
    }

    private static final String PATH_SEPARATOR = "/"; //$NON-NLS-1$

    private Cli() {
        return;
    }

    /**
     * The program entry.
     * @param args application arguments
     * @throws Exception if failed
     */
    public static void main(String[] args) throws Exception {
        int status = execute(args);
        if (status != 0) {
            System.exit(status);
        }
    }

    /**
     * The program entry.
     * @param args application arguments
     * @return the exit code
     */
    public static int execute(String... args) {
        Configuration configuration;
        try {
            configuration = parse(args);
        } catch (Exception e) {
            LOG.error(MessageFormat.format(
                    "error occurred while analyzing arguments: {0}",
                    Arrays.toString(args)), e);
            HelpFormatter formatter = new HelpFormatter();
            formatter.setWidth(Integer.MAX_VALUE);
            formatter.printHelp(
                    MessageFormat.format(
                            "java -classpath ... {0}", //$NON-NLS-1$
                            Cli.class.getName()),
                    new Opts().options,
                    true);
            return 1;
        }
        try {
            process(configuration);
        } catch (Exception e) {
            LOG.error(MessageFormat.format(
                    "error occurred while processing inspection object: {0}",
                    Arrays.toString(args)), e);
            return 1;
        }
        return 0;
    }

    static Configuration parse(String... args) throws ParseException {
        LOG.debug("analyzing command line arguments: {}", Arrays.toString(args)); //$NON-NLS-1$

        Opts opts = new Opts();
        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(opts.options, args);

        Configuration results = new Configuration();
        results.input = parseFile(cmd, opts.input, true);
        results.output = parseFile(cmd, opts.output, false);
        results.path = parseOpt(cmd, opts.path, false);
        results.format = parseOpt(cmd, opts.format, false);
        results.properties = parseProperties(cmd, opts.properties);
        return results;
    }

    private static File parseFile(CommandLine cmd, Option opt, boolean mandatory) {
        String value = parseOpt(cmd, opt, mandatory);
        if (value == null) {
            return null;
        }
        return new File(value);
    }

    private static Map<String, String> parseProperties(CommandLine cmd, Option option) {
        Properties properties = cmd.getOptionProperties(option.getLongOpt());
        Map<String, String> results = new TreeMap<>();
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            results.put((String) entry.getKey(), (String) entry.getValue());
        }
        return results;
    }

    private static String parseOpt(CommandLine cmd, Option opt, boolean mandatory) {
        String value = cmd.getOptionValue(opt.getLongOpt());
        if (value != null) {
            value = value.trim();
            if (value.isEmpty()) {
                value = null;
            }
        }
        LOG.debug("--{}: {}", opt.getLongOpt(), value); //$NON-NLS-1$
        if (value == null) {
            if (mandatory) {
                throw new IllegalArgumentException(MessageFormat.format(
                        "option \"--{0}\" is mandatory",
                        opt.getLongOpt()));
            }
            return null;
        }
        return value;
    }

    static void process(Configuration configuration) throws IOException, ReflectiveOperationException {
        InspectionNodeProcessor processor = loadProcessor(configuration.format);
        InspectionNodeProcessor.Context context = new InspectionNodeProcessor.Context(configuration.properties);
        InspectionNode node = loadInput(configuration.input, configuration.repository, configuration.path);
        if (configuration.output == null) {
            processor.process(context, node, configuration.defaultOutput);
        } else {
            try (OutputStream output = openOutput(configuration.output)) {
                processor.process(context, node, output);
            }
        }
    }

    private static InspectionNodeProcessor loadProcessor(String format) throws ReflectiveOperationException {
        if (format == null) {
            return DEFAULT_PROCESSOR;
        }
        InspectionNodeProcessor builtin = BUILTIN_PROCESSORS.get(format);
        if (builtin != null) {
            return builtin;
        }
        LOG.debug("loading processor: {}", format); //$NON-NLS-1$
        return Class.forName(format).asSubclass(InspectionNodeProcessor.class).newInstance();
    }

    private static InspectionNode loadInput(
            File file, InspectionNodeRepository repository, String path) throws IOException {
        InspectionNode node = loadInput(file, repository);
        if (path != null) {
            return find(node, path);
        }
        return node;
    }

    private static InspectionNode loadInput(File file, InspectionNodeRepository repository) throws IOException {
        LOG.debug("loading file: {}", file); //$NON-NLS-1$
        try (InputStream input = new FileInputStream(file)) {
            return repository.load(input);
        }
    }

    private static OutputStream openOutput(File file) throws IOException {
        File parent = file.getAbsoluteFile().getParentFile();
        if (parent.mkdirs() == false && parent.isDirectory() == false) {
            throw new IOException(MessageFormat.format(
                    "failed to create output: {0}",
                    file));
        }
        return new FileOutputStream(file);
    }

    private static InspectionNode find(InspectionNode node, String path) {
        InspectionNode current = node;
        StringBuilder history = new StringBuilder();
        for (String segment : path.split(PATH_SEPARATOR)) {
            if (segment.isEmpty()) {
                continue;
            }
            if (history.length() >= 1) {
                history.append(PATH_SEPARATOR);
            }
            history.append(segment);
            InspectionNode next = current.getElements().get(segment);
            if (next == null) {
                throw new NoSuchElementException(history.toString());
            }
            current = next;
        }
        return current;
    }

    private static class Opts {

        final Option input = required("input", 1) //$NON-NLS-1$
                .withDescription("input inspection file")
                .withArgumentDescription("/path/to/input-file.json"); //$NON-NLS-1$

        final Option path = optional("path", 1) //$NON-NLS-1$
                .withDescription("inspection path (default: root)")
                .withArgumentDescription("path/to/target-node"); //$NON-NLS-1$

        final Option output = optional("output", 1) //$NON-NLS-1$
                .withDescription("output file (default: stdout)")
                .withArgumentDescription("/path/to/output-file"); //$NON-NLS-1$

        final Option format = optional("format", 1) //$NON-NLS-1$
                .withDescription("output format (default: txt)")
                .withArgumentDescription("ls|txt|dot|json|class-name"); //$NON-NLS-1$

        final Option properties = properties("P", "property") //$NON-NLS-1$ //$NON-NLS-2$
                .withValueSeparator('=')
                .withDescription("format property")
                .withArgumentDescription("key=value"); //$NON-NLS-1$

        final Options options = new Options();

        Opts() {
            for (Field field : Opts.class.getDeclaredFields()) {
                if (Option.class.isAssignableFrom(field.getType()) == false) {
                    continue;
                }
                try {
                    Option option = (Option) field.get(this);
                    options.addOption(option);
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            }
        }

        private static RichOption optional(String name, int arguments) {
            return new RichOption(null, name, arguments, false);
        }

        private static RichOption required(String name, int arguments) {
            return new RichOption(null, name, arguments, true);
        }

        private static RichOption properties(String shortName, String longName) {
            RichOption option = new RichOption(shortName, longName, 2, false);
            return option;
        }
    }

    static class Configuration {

        File input;

        File output;

        String path;

        String format;

        Map<String, String> properties;

        InspectionNodeRepository repository = new JsonInspectionNodeRepository();

        OutputStream defaultOutput = System.out;
    }
}


text:
require_relative "vocabulary_class_factory"

module ConceptQL
  module Vocabularies
    class Entry
      attr :hash

      METHODS = %i(
        id
        omopv4_vocabulary_id
        omopv5_vocabulary_id
        domain
        vocabulary_short_name
        vocabulary_long_name
        format_regexp
      )

      METHODS.each do |meth|
        define_method(meth) do
          hash[meth]
        end
      end

      METADATA_METHODS = METHODS + %i(
        preferred_name
        predominant_domains
      )

      STANDARD_VOCABS = %w(
        ABMS
        AMT
        APC
        CDM
        CDT
        CMS Place of Service
        CPT4
        CVX
        Condition Type
        Cost
        Cost Type
        Currency
        DRG
        Death Type
        Device Type
        Drug Type
        Episode
        Episode Type
        Ethnicity
        GGR
        Gemscript
        Gender
        HCPCS
        HES Specialty
        HemOnc
        ICD10PCS
        ICD9Proc
        ICDO3
        JMDC
        LOINC
        MDC
        MMI
        Meas Type
        Medicare Specialty
        NAACCR
        NUCC
        Note Type
        OPCS4
        OSM
        Obs Period Type
        Observation Type
        PCORNet
        PHDSC
        PPI
        Plan
        Plan Stop Reason
        Procedure Type
        Provider
        Race
        Relationship
        Revenue Code
        RxNorm
        RxNorm Extension
        SNOMED
        SNOMED Veterinary
        Specimen Type
        Sponsor
        Supplier
        UB04 Pri Typ of Adm
        UB04 Typ bill
        UCUM
        US Census
        Visit
        Visit Type
        dm+d
      )

      COST_RELATED_VOCABS = [
        'Revenue Code',
        'DRG'
      ]

      def initialize(hash)
        @hash = hash
        @hash[:omopv5_vocabulary_id] ||= @hash[:id]
        @hash[:aliases_arr] ||= []
        @hash[:aliases_arr] |= (@hash[:aliases] || "").split(";")
        @hash[:id] = @hash[:id].to_s.downcase
        @hash[:aliases_arr] << @hash[:id] if @hash[:id] =~ /\s/
        @hash[:id] = translate_id(@hash[:id].gsub(/\W+/, "_"))
        @hash[:aliases_arr] -= [@hash[:id]]
      end

      def translate_id(id)
        {
          "icd10" => "icd10who"
        }[id] || id
      end

      def merge(other_entry)
        self.class.new(hash.merge(other_entry.hash))
      end

      def belongs_in_omopv4_plus?
        @belongs_in_omopv4_plus ||= (!from_lexicon? || from_csv?) \
          && has_domain? \
          && visible?
      end

      def is_standard?
        belongs_in_omopv4_plus? && STANDARD_VOCABS.include?(omopv5_vocabulary_id)
      end

      def is_source?
        belongs_in_omopv4_plus? && !is_standard?
      end

      def to_hash
        METADATA_METHODS.each_with_object({}) do |meth, h|
          h[meth] = send(meth)
        end
      end

      def short_name
        vocabulary_short_name || vocabulary_long_name
      end

      def long_name
        vocabulary_long_name || vocabulary_short_name
      end

      def preferred_name
        omopv5_id || id
      end

      def aliases
        @hash[:aliases_arr]
      end

      def predominant_domains
        Array(domain || :condition_occurrence).flatten
      end

      def from_lexicon?
        hash[:from_lexicon].present?
      end

      def from_csv?
        hash[:from_csv].present?
      end

      def has_domain?
        hash[:domain].present?
      end

      def hidden?
        hash[:hidden].present?
      end

      def is_labish?
        hash[:domain] =~ /observation|measurement/i
      end

      def is_drugish?
        hash[:domain] =~ /drug_exposure/i
      end

      def is_costish?
        belongs_in_omopv4_plus? && COST_RELATED_VOCABS.include?(omopv5_vocabulary_id)
      end

      def visible?
        !hidden?
      end

      def omopv5_id
        omopv5_vocabulary_id || id
      end

      def omopv4_id
        omopv4_vocabulary_id
      end

      def get_klasses
        VocabularyClassFactory.new(self).get_klasses
      end
    end
  end
end


text:
package me.nereo.baiduimageview.ui.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import me.nereo.baiduimageview.R;
import me.nereo.baiduimageview.model.Image;

/**
 * Created by Administrator on 2014-07-07.
 */
public class ImageGridAdapter extends BaseAdapter {

    private List<Image> images = new ArrayList<Image>();
    private LayoutInflater mInflater;
    ImageLoader imageLoader = ImageLoader.getInstance();
    DisplayImageOptions options;
    private int itemWidth;

    private FrameLayout.LayoutParams mImageLayoutParams;

    private ImageLoadingListener animateFirstListener;

    private Drawable mDefaultImageDrawable = new ColorDrawable(Color.argb(255, 201, 201, 201));

    public ImageGridAdapter(Context ctx){
        mInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        options = new DisplayImageOptions.Builder()
                //.cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        mImageLayoutParams = new
                FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        animateFirstListener = new AnimateFirstDisplayListener();
    }

    public void setData(List<Image> images){
        if(images.size()>0){
            images.remove(images.size()-1);
        }
        this.images.addAll(images);
        //this.images = images;
        notifyDataSetChanged();
    }

    public List<Image> getData(){
        return images;
    }

    public void clearData(){
        if(images.size() > 0)
            images.clear();
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return images.size();
    }

    @Override
    public Object getItem(int i) {
        return images.get(i);
    }

    @Override
    public long getItemId(int i) {
        return Long.valueOf(images.get(i).getId());
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder;
        if(view != null){
            holder = (ViewHolder) view.getTag();
        }else{
            view = mInflater.inflate(R.layout.item_image_grid, viewGroup, false);
            holder = new ViewHolder();
            holder.imageView = (ImageView) view.findViewById(R.id.image);
            holder.textView = (TextView) view.findViewById(R.id.text);
            holder.albumNum = (TextView) view.findViewById(R.id.albumNum);
            view.setTag(holder);
        }

        Image img = (Image) getItem(i);
        if(img != null){

            if(img.getAlbumNum() > 1){
                if(holder.albumNum.getVisibility() != View.VISIBLE)
                    holder.albumNum.setVisibility(View.VISIBLE);
                holder.albumNum.setText(String.valueOf(img.getAlbumNum()));
            }else{
                if(holder.albumNum.getVisibility() != View.GONE)
                    holder.albumNum.setVisibility(View.GONE);
            }

            int imageHeight = 0;
            if(holder.imageView.getLayoutParams().height != imageHeight){
                double ratio;
                if(img.getImageWidth() == null || img.getImageHeight() == null){
                    ratio = 1;
                }else{
                    ratio = (double)img.getImageHeight() / (double)img.getImageWidth();
                   // System.out.println("iWidth: "+img.getImageWidth()+";iHeight: "+img.getImageHeight()+";"+"ratio: "+ratio);
                }
                imageHeight = (int) ( itemWidth*ratio );

                mImageLayoutParams = new FrameLayout.LayoutParams(itemWidth, imageHeight);

               // System.out.println("height1: "+imageHeight+"; width1:"+itemWidth);

            }

            holder.imageView.setLayoutParams(mImageLayoutParams);

            Bitmap bm = Bitmap.createBitmap(holder.imageView.getLayoutParams().width, holder.imageView.getLayoutParams().height, Bitmap.Config.RGB_565);

            holder.imageView.setImageBitmap(bm);
            //holder.imageView.setImageDrawable(mDefaultImageDrawable);

            //System.out.println("height: "+holder.imageView.getLayoutParams().height+"; width:"+holder.imageView.getLayoutParams().width);

            imageLoader.displayImage(img.getImageUrl(), holder.imageView, options, animateFirstListener);
            holder.textView.setText(img.getTitle());
        }

        return view;
    }

    public void setItemWidth(int width){
        if(itemWidth == width) return;

        itemWidth = width;
        mImageLayoutParams = new
                FrameLayout.LayoutParams(width, FrameLayout.LayoutParams.MATCH_PARENT);
        notifyDataSetChanged();
    }

    static class ViewHolder{
        ImageView imageView;
        TextView textView;
        TextView albumNum;
    }

    private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener{
        static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if(loadedImage != null){
                ImageView iv = (ImageView) view;
                if(!displayedImages.contains(imageUri)) {
                    FadeInBitmapDisplayer.animate(iv, 500);
                    displayedImages.add(imageUri);
                }
            }
        }
    }
}


text:
require "chef/provisioning"
require "chef/resource/vagrant_cluster"
require "chef/provider/vagrant_cluster"
require "chef/resource/vagrant_box"
require "chef/provider/vagrant_box"
require "chef/provisioning/vagrant_driver/driver"

class Chef
  module Provisioning
    module VagrantDriver
      def self.with_vagrant_box(run_context, box_name, vagrant_options = {}, &block)
        if box_name.is_a?(Chef::Resource::VagrantBox)
          new_options = { :vagrant_options => { "vm.box" => box_name.name } }
          new_options[:vagrant_options]["vm.box_url"] = box_name.url if box_name.url
          new_options[:vagrant_provider] = box_name.vagrant_provider
        else
          new_options = { :vagrant_options => { "vm.box" => box_name } }
        end

        run_context.chef_provisioning.add_machine_options(new_options, &block)
      end
    end
  end

  module DSL
    module Recipe
      def with_vagrant_cluster(cluster_path, &block)
        with_driver("vagrant:#{cluster_path}", &block)
      end

      def with_vagrant_box(box_name, vagrant_options = {}, &block)
        Chef::Provisioning::VagrantDriver.with_vagrant_box(run_context, box_name, vagrant_options, &block)
      end
    end
  end
end


text:
System.register([], function(exports_1) {
    var DirtyChecker, DirtyCheckProperty;
    return {
        setters:[],
        execute: function() {
            DirtyChecker = (function () {
                function DirtyChecker() {
                    this.tracked = [];
                    this.checkDelay = 120;
                }
                DirtyChecker.prototype.addProperty = function (property) {
                    var tracked = this.tracked;
                    tracked.push(property);
                    if (tracked.length === 1) {
                        this.scheduleDirtyCheck();
                    }
                };
                DirtyChecker.prototype.removeProperty = function (property) {
                    var tracked = this.tracked;
                    tracked.splice(tracked.indexOf(property), 1);
                };
                DirtyChecker.prototype.scheduleDirtyCheck = function () {
                    var _this = this;
                    setTimeout(function () { return _this.check(); }, this.checkDelay);
                };
                DirtyChecker.prototype.check = function () {
                    var tracked = this.tracked, i = tracked.length;
                    while (i--) {
                        var current = tracked[i];
                        if (current.isDirty()) {
                            current.call();
                        }
                    }
                    if (tracked.length) {
                        this.scheduleDirtyCheck();
                    }
                };
                return DirtyChecker;
            })();
            exports_1("DirtyChecker", DirtyChecker);
            DirtyCheckProperty = (function () {
                function DirtyCheckProperty(dirtyChecker, obj, propertyName) {
                    this.dirtyChecker = dirtyChecker;
                    this.obj = obj;
                    this.propertyName = propertyName;
                    this.callbacks = [];
                    this.isSVG = obj instanceof SVGElement;
                }
                DirtyCheckProperty.prototype.getValue = function () {
                    return this.obj[this.propertyName];
                };
                DirtyCheckProperty.prototype.setValue = function (newValue) {
                    if (this.isSVG) {
                        this.obj.setAttributeNS(null, this.propertyName, newValue);
                    }
                    else {
                        this.obj[this.propertyName] = newValue;
                    }
                };
                DirtyCheckProperty.prototype.call = function () {
                    var callbacks = this.callbacks, i = callbacks.length, oldValue = this.oldValue, newValue = this.getValue();
                    while (i--) {
                        callbacks[i](newValue, oldValue);
                    }
                    this.oldValue = newValue;
                };
                DirtyCheckProperty.prototype.isDirty = function () {
                    return this.oldValue !== this.getValue();
                };
                DirtyCheckProperty.prototype.beginTracking = function () {
                    this.tracking = true;
                    this.oldValue = this.newValue = this.getValue();
                    this.dirtyChecker.addProperty(this);
                };
                DirtyCheckProperty.prototype.endTracking = function () {
                    this.tracking = false;
                    this.dirtyChecker.removeProperty(this);
                };
                DirtyCheckProperty.prototype.subscribe = function (callback) {
                    var callbacks = this.callbacks, that = this;
                    callbacks.push(callback);
                    if (!this.tracking) {
                        this.beginTracking();
                    }
                    return function () {
                        callbacks.splice(callbacks.indexOf(callback), 1);
                        if (callbacks.length === 0) {
                            that.endTracking();
                        }
                    };
                };
                return DirtyCheckProperty;
            })();
            exports_1("DirtyCheckProperty", DirtyCheckProperty);
        }
    }
});


text:
<?php

namespace MadeSimple\Database\Tests\Unit;

use MadeSimple\Database\CompilerInterface;
use MadeSimple\Database\Connection;
use MadeSimple\Database\Pool;
use MadeSimple\Database\Tests\MockConnection;
use MadeSimple\Database\Tests\MockConnector;
use MadeSimple\Database\Tests\TestCase;

class PoolTest extends TestCase
{
    /**
     * @var \Mockery\Mock|\PDO
     */
    private $mockPdo;

    /**
     * @var MockConnector
     */
    private $mockConnector;

    /**
     * @var \Mockery\Mock|CompilerInterface
     */
    private $mockCompiler1;

    /**
     * @var \Mockery\Mock|CompilerInterface
     */
    private $mockCompiler2;

    /**
     * @var \Mockery\Mock|Connection
     */
    private $connection1;

    /**
     * @var \Mockery\Mock|Connection
     */
    private $connection2;

    protected function setUp(): void
    {
        parent::setUp();

        $this->mockPdo       = \Mockery::mock(\PDO::class);
        $this->mockConnector = new MockConnector($this->mockPdo);
        $this->mockCompiler1 = \Mockery::mock(CompilerInterface::class);
        $this->mockCompiler2 = \Mockery::mock(CompilerInterface::class);
        $this->mockCompiler1->shouldReceive('setConnection')->once();
        $this->mockCompiler2->shouldReceive('setConnection')->once();
        $this->connection1   = new MockConnection($this->mockConnector, $this->mockCompiler1);
        $this->connection2   = new MockConnection($this->mockConnector, $this->mockCompiler2);
    }

    /**
     * Test Pool construction.
     */
    public function testConstruct()
    {
        $pool = new Pool($this->connection1, $this->connection2);
        $this->assertEquals($this->connection1->config('unique'), $pool->get()->config('unique'));
        $this->assertNotEquals($this->connection2->config('unique'), $pool->get()->config('unique'));
    }

    /**
     * Test construct throws exception.
     */
    public function testConstructThrowsInvalidArgumentException()
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('Pool only accepts Connections');

        new Pool('Not A Connection');
    }

    /**
     * Test pool set default.
     */
    public function testSetDefault()
    {
        $pool = new Pool(['mysql' => $this->connection1, 'sqlite' => $this->connection2]);
        $this->assertEquals($this->connection1->config('unique'), $pool->get()->config('unique'));
        $pool->setDefault('sqlite');
        $this->assertEquals($this->connection2->config('unique'), $pool->get()->config('unique'));
    }

    /**
     * Test pool get.
     */
    public function testGet()
    {
        $pool = new Pool(['mysql' => $this->connection1, 'sqlite' => $this->connection2]);
        $this->assertEquals($this->connection1->config('unique'), $pool->get()->config('unique'));
        $this->assertEquals($this->connection1->config('unique'), $pool->get('mysql')->config('unique'));
        $this->assertEquals($this->connection2->config('unique'), $pool->get('sqlite')->config('unique'));
    }

    /**
     * Test pool set.
     */
    public function testSet()
    {
        $pool = new Pool(['mysql' => $this->connection1]);
        $pool->set('sqlite', $this->connection2);
        $this->assertEquals($this->connection1->config('unique'), $pool->get()->config('unique'));
        $this->assertEquals($this->connection1->config('unique'), $pool->get('mysql')->config('unique'));
        $this->assertEquals($this->connection2->config('unique'), $pool->get('sqlite')->config('unique'));
    }
}


text:
function handlelog(player, interfaceId, button, idx, idx2) {
    if (button == 6) {
        player.getProtocol().sendLogout();
    } else if (button == 1) {
        player.sendMessage("Sorry we do not support this currently")
    }
}


text:
export { default as Basic } from './Basic';
export { default as Locale } from './Locale';
export { default as ProviderLocale } from './ProviderLocale';
export { default as Range } from './Range';
export default {
  parameters: {
    previewTabs: {
      'storybook/docs/panel': {
        hidden: true
      }
    },
    storyshots: {
      disable: true
    }
  },
  title: 'Stories/Calendar'
};
//# sourceMappingURL=index.stories.js.map


text:
{% extends "dashboard/base.html" %}
{% load i18n %}
{% load prices_i18n %}
{% load materializecss %}

{% block title %}{% trans "Customers" %} - {{ block.super }}{% endblock %}

{% block body_class %}body-customers{% endblock %}

{% block breadcrumbs %}

{% trans "Customers" %}

{% endblock %}

{% block menu_sales_class %} active{% endblock %}

{% block content %}
    <form method="get">

            {{ form.email|materializecss:"s12 m3 l3" }}
            {{ form.name|materializecss:"s12 m3 l3" }}
            {{ form.order_status|materializecss:"s7 m3 l2" }}

                <button type="submit" class="btn btn--inline">{% trans "Filter" %}</button>
                {% if form.is_bound %}
                    {% trans "Clear" %}
                {% endif %}

    </form>

{{ title }}

        {% if customers %}

                            {% trans "Email" %}
                            {% trans "Name" %}
                            {% trans "Location" %}
                            {% trans "Number of orders" %}
                            {% trans "Last order" %}

                    {% for customer in customers %}

                            {% with customer.default_billing_address as default_address %}

                                {{ customer.email }}

                            {% if default_address %}

                                    {{ default_address.first_name }} {{ default_address.last_name }}

                                    {{ default_address.city }}, {{ default_address.get_country_display }}

                            {% else %}

                            {% endif %}
                            {% endwith %}

                                {{ customer.num_orders }}

                                {% if customer.last_order %}
                                    #{{ customer.last_order }}
                                {% endif %}

                    {% endfor %}

        {% else %}

{% trans "No customers found." %}

        {% endif %}

    {% include "dashboard/includes/_pagination.html" with page_obj=customers %}
{% endblock %}


text:
require 'rails_helper'
require 'spec_helper'

RSpec.describe ArtLabel, type: :model do
  it { should have_valid(:name).when("Johnny") }
  it { should_not have_valid(:name).when(nil, "") }

  it { should have_valid(:brewery).when("Smith") }
  it { should_not have_valid(:brewery).when(nil, "") }

end