text:
package ca.uhn.fhir.jpa.subscription;

import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

import java.net.URI;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;

import ca.uhn.fhir.jpa.dao.DaoConfig;
import ca.uhn.fhir.jpa.provider.BaseResourceProviderDstu2Test;
import ca.uhn.fhir.model.dstu2.composite.*;
import ca.uhn.fhir.model.dstu2.resource.*;
import ca.uhn.fhir.model.dstu2.resource.Subscription.Channel;
import ca.uhn.fhir.model.dstu2.valueset.*;
import ca.uhn.fhir.rest.api.EncodingEnum;
import ca.uhn.fhir.rest.api.MethodOutcome;

/**
 * Adds a FHIR subscription with criteria through the rest interface. Then creates a websocket with the id of the
 * subscription
 *

 * Note: This test only returns a ping with the subscription id, Check FhirSubscriptionWithSubscriptionIdDstu3Test for
 * a test that returns the xml of the observation
 *

 * To execute the following test, execute it the following way:
 * 0. execute 'clean' test
 * 1. Execute the 'createSubscription' test
 * 2. Update the subscription id in the 'attachWebSocket' test
 * 3. Execute the 'attachWebSocket' test
 * 4. Execute the 'sendObservation' test
 * 5. Look in the 'attachWebSocket' terminal execution and wait for your ping with the subscription id
 */
public class FhirSubscriptionWithSubscriptionIdDstu2Test extends BaseResourceProviderDstu2Test {
	private static final Logger ourLog = org.slf4j.LoggerFactory.getLogger(FhirSubscriptionWithSubscriptionIdDstu2Test.class);

	private String myPatientId;
	private String mySubscriptionId;
	private WebSocketClient myWebSocketClient;
	private SocketImplementation mySocketImplementation;

	@After
	public void after() throws Exception {
		super.after();
		myDaoConfig.setSubscriptionEnabled(new DaoConfig().isSubscriptionEnabled());
		myDaoConfig.setSubscriptionPollDelay(new DaoConfig().getSubscriptionPollDelay());
	}

	@Before
	public void before() throws Exception {
		super.before();

		myDaoConfig.setSubscriptionEnabled(true);
		myDaoConfig.setSubscriptionPollDelay(0L);

		/*
		 * Create patient
		 */

		Patient patient = FhirDstu2Util.getPatient();
		MethodOutcome methodOutcome = ourClient.create().resource(patient).execute();
		myPatientId = methodOutcome.getId().getIdPart();

		/*
		 * Create subscription
		 */
		Subscription subscription = new Subscription();
		subscription.setReason("Monitor new neonatal function (note, age will be determined by the monitor)");
		subscription.setStatus(SubscriptionStatusEnum.ACTIVE);
		// subscription.setCriteria("Observation?subject=Patient/" + PATIENT_ID);
		subscription.setCriteria("Observation?code=SNOMED-CT|82313006");

		Channel channel = new Channel();
		channel.setType(SubscriptionChannelTypeEnum.WEBSOCKET);
		channel.setPayload("application/json");
		subscription.setChannel(channel);

		methodOutcome = ourClient.create().resource(subscription).execute();
		mySubscriptionId = methodOutcome.getId().getIdPart();

		/*
		 * Attach websocket
		 */

		myWebSocketClient = new WebSocketClient();
		mySocketImplementation = new SocketImplementation(mySubscriptionId, EncodingEnum.JSON);

		myWebSocketClient.start();
		URI echoUri = new URI("ws://localhost:" + ourPort + "/websocket/dstu2");
		ClientUpgradeRequest request = new ClientUpgradeRequest();
		ourLog.info("Connecting to : {}", echoUri);
		Future<Session> connection = myWebSocketClient.connect(mySocketImplementation, echoUri, request);
		Session session = connection.get(2, TimeUnit.SECONDS);

		ourLog.info("Connected to WS: {}", session.isOpen());
	}

	@After
	public void afterCloseWebsocket() throws Exception {
		ourLog.info("Shutting down websocket client");
		myWebSocketClient.stop();
	}

	@Test
	public void createObservation() throws Exception {
		Observation observation = new Observation();
		CodeableConceptDt cc = new CodeableConceptDt();
		observation.setCode(cc);
		CodingDt coding = cc.addCoding();
		coding.setCode("82313006");
		coding.setSystem("SNOMED-CT");
		ResourceReferenceDt reference = new ResourceReferenceDt();
		reference.setReference("Patient/" + myPatientId);
		observation.setSubject(reference);
		observation.setStatus(ObservationStatusEnum.FINAL);

		MethodOutcome methodOutcome2 = ourClient.create().resource(observation).execute();
		String observationId = methodOutcome2.getId().getIdPart();
		observation.setId(observationId);

		ourLog.info("Observation id generated by server is: " + observationId);

		int changes = mySubscriptionDao.pollForNewUndeliveredResources();
		ourLog.info("Polling showed {}", changes);
		assertEquals(1, changes);

		Thread.sleep(2000);

		ourLog.info("WS Messages: {}", mySocketImplementation.getMessages());
		assertThat(mySocketImplementation.getMessages(), contains("bound " + mySubscriptionId, "ping " + mySubscriptionId));
	}

	@Test
	public void createObservationThatDoesNotMatch() throws Exception {
		Observation observation = new Observation();
		CodeableConceptDt cc = new CodeableConceptDt();
		observation.setCode(cc);
		CodingDt coding = cc.addCoding();
		coding.setCode("8231");
		coding.setSystem("SNOMED-CT");
		ResourceReferenceDt reference = new ResourceReferenceDt();
		reference.setReference("Patient/" + myPatientId);
		observation.setSubject(reference);
		observation.setStatus(ObservationStatusEnum.FINAL);

		MethodOutcome methodOutcome2 = ourClient.create().resource(observation).execute();
		String observationId = methodOutcome2.getId().getIdPart();
		observation.setId(observationId);

		ourLog.info("Observation id generated by server is: " + observationId);

		int changes = mySubscriptionDao.pollForNewUndeliveredResources();
		ourLog.info("Polling showed {}", changes);
		assertEquals(0, changes);

		Thread.sleep(2000);

		ourLog.info("WS Messages: {}", mySocketImplementation.getMessages());
		assertThat(mySocketImplementation.getMessages(), contains("bound " + mySubscriptionId));
	}
}


text:
package lila.playban

import lila.chat.{ Chat, ChatApi }
import lila.game.Pov

final private class PlaybanFeedback(
    chatApi: ChatApi,
    lightUser: lila.common.LightUser.Getter
)(implicit ec: scala.concurrent.ExecutionContext) {

  private val tempBan = "will result in a temporary ban."

  def abort(pov: Pov): Unit = tell(pov, s"Warning, {user}. Aborting too many games $tempBan")

  def noStart(pov: Pov): Unit = tell(pov, s"Warning, {user}. Failing to start games $tempBan")

  def rageQuit(pov: Pov): Unit = tell(pov, s"Warning, {user}. Leaving games without resigning $tempBan")

  def sitting(pov: Pov): Unit =
    tell(pov, s"Warning, {user}. Letting time run out instead of resigning $tempBan")

  private def tell(pov: Pov, template: String): Unit =
    pov.player.userId foreach { userId =>
      lightUser(userId) foreach { light =>
        val message = template.replace("{user}", light.fold(userId)(_.name))
        chatApi.userChat.volatile(Chat.Id(pov.gameId), message, _.Round)
      }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using namespace DirectX;

// Constructor reads from the filesystem.
BinaryReader::BinaryReader(_In_z_ wchar_t const* fileName) noexcept(false) :
    mPos(nullptr),
    mEnd(nullptr)
{
    size_t dataSize;

    HRESULT hr = ReadEntireFile(fileName, mOwnedData, &dataSize);
    if (FAILED(hr))
    {
        DebugTrace("ERROR: BinaryReader failed (%08X) to load '%ls'\n",
            static_cast<unsigned int>(hr), fileName);
        throw std::exception("BinaryReader");
    }

    mPos = mOwnedData.get();
    mEnd = mOwnedData.get() + dataSize;
}

// Constructor reads from an existing memory buffer.
BinaryReader::BinaryReader(_In_reads_bytes_(dataSize) uint8_t const* dataBlob, size_t dataSize) noexcept :
    mPos(dataBlob),
    mEnd(dataBlob + dataSize)
{
}

// Reads from the filesystem into memory.
HRESULT BinaryReader::ReadEntireFile(_In_z_ wchar_t const* fileName, _Inout_ std::unique_ptr<uint8_t[]>& data, _Out_ size_t* dataSize)
{
    // Open the file.
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
    ScopedHandle hFile(safe_handle(CreateFile2(fileName, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr)));
#else
    ScopedHandle hFile(safe_handle(CreateFileW(fileName, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)));
#endif

    if (!hFile)
        return HRESULT_FROM_WIN32(GetLastError());

    // Get the file size.
    FILE_STANDARD_INFO fileInfo;
    if (!GetFileInformationByHandleEx(hFile.get(), FileStandardInfo, &fileInfo, sizeof(fileInfo)))
    {
        return HRESULT_FROM_WIN32(GetLastError());
    }

    // File is too big for 32-bit allocation, so reject read.
    if (fileInfo.EndOfFile.HighPart > 0)
        return E_FAIL;

    // Create enough space for the file data.
    data.reset(new uint8_t[fileInfo.EndOfFile.LowPart]);

    if (!data)
        return E_OUTOFMEMORY;

    // Read the data in.
    DWORD bytesRead = 0;

    if (!ReadFile(hFile.get(), data.get(), fileInfo.EndOfFile.LowPart, &bytesRead, nullptr))
    {
        return HRESULT_FROM_WIN32(GetLastError());
    }

    if (bytesRead < fileInfo.EndOfFile.LowPart)
        return E_FAIL;

    *dataSize = bytesRead;

    return S_OK;
}


text:
package org.activiti.engine.repository;

import org.activiti.engine.api.internal.Internal;

import java.util.Date;

/**
 * Represents a model that is stored in the model repository. In addition, a model can be deployed to the Activiti Engine in a separate deployment step.
 *
 * A model is a container for the meta data and sources of a process model that typically can be edited in a modeling environment.
 *
 */
@Internal
public interface Model {

  String getId();

  String getName();

  void setName(String name);

  String getKey();

  void setKey(String key);

  String getCategory();

  void setCategory(String category);

  Date getCreateTime();

  Date getLastUpdateTime();

  Integer getVersion();

  void setVersion(Integer version);

  String getMetaInfo();

  void setMetaInfo(String metaInfo);

  String getDeploymentId();

  void setDeploymentId(String deploymentId);

  void setTenantId(String tenantId);

  String getTenantId();

  /** whether this model has editor source */
  boolean hasEditorSource();

  /** whether this model has editor source extra */
  boolean hasEditorSourceExtra();
}


text:
title: Opera Mobile 12, and Introducing Opera Mini Next
authors:
- bruce-lawson
tags:
- opera-mobile
- opera-mini
- ios
- gum
- android
- iphone
- getusermedia
- webgl
- camera
- ipad
license: cc-by-3.0
---

Mobile analyst Peter Paul Koch recently wrote,

Opera once more overtakes Safari. It's clear now that Android's untrammeled growth has ended, and that the race for first position will continue to be between Opera and Safari.

So now's the time to download the Opera mobile browsers and test your sites.

Opera Mobile 12 for Android and Symbian

Just because a device is small enough to fit in your pocket, it doesn't mean it can't have a powerful browser. Opera Mobile 12 is packed with HTML5 goodness:

 Ragnarök, our HTML5 parser,  for  better web apps and increased compatibility with websites.

ECMAScript 5.1 for those who are too damn groovy for JavaScript.

Orientation Support

For Android only, support for camera use in the browser using the same, newer, getUserMedia syntax as Opera desktop Labs.

CSS3 radial gradients and the fabled -o-double-rainbow.

CORS (cross-origin resource sharing).

For Android only, hardware-accelerated WebGL  for all things 3D and web. With WebGL on mobile, it'll be even easier to make and distribute games that work cross-platform.

Keen standards-spotters can check out our Web specifications support in Opera products.

Loads of webapp wowzers for the browsers in your trousers!

Demos? You want demos? Try our new Shiny Demos in Opera Mobile 12 or any capable browsers (no 1998-era browser-sniffing here, thank you).

Testing Opera Mobile

In the early stages of a project, when you're constantly tweaking viewports and media queries, it can slow you down to continually deploy a site, then check on a phone. To help you, we've packaged up the Opera Mobile codebase into a desktop app for Windows, Linux and Mac, so you can test locally. It's called Opera Mobile Emulator. (Note that the Opera Mobile 12 emulator will be released in the coming weeks)

For sophisticated debugging, we have true remote debugging with Opera Dragonfly that allows you to inspect the DOM, change the CSS and set breakpoints in your device browser, from your desktop.

Patrick H. Lauke, Product Manager for Opera Dragonfly, explains more.

<object width="480" height="360"><param name="movie" value="https://www.youtube.com/v/YHwiaH8Z5vA?version=3&amp;hl=en_GB&amp;rel=0" /><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="never" /><embed src="https://www.youtube.com/v/YHwiaH8Z5vA?version=3&amp;hl=en_GB&amp;rel=0" type="application/x-shockwave-flash" width="480" height="360" allowfullscreen="true" allowscriptaccess="never" /></object>

Have a look at opera.com/developer/tools for an overview of our developer tools – and if that's not enough, we also have 'The Developer Briefcase' and other neat Opera extensions for developers.

Opera Mini Next

Be sure to check out your site in Opera Mini, and experience it as many of your users will.

Opera Mini now has a Next channel, where the latest improvements will land on in advance of an official release. In this case, those improvements include the "Home Screen" for social network integration next to Speed Dial for feature phones, and hardware-accelerated scrolling with revamped Speed Dial for smartphones.

You should also read our Opera Mini: web content authoring guidelines.

Opera Mini 7 for iOS

Opera Mini 7 Final for iOS is in the Appstore today. We've added support for file uploads, and  more than nine Speed Dials.

Gimme, gimme, gimme

Grab your Opera Mini  Next for Java, Android, Blackberry and S60 from m.opera.com/next, and Opera Mobile 12 for Android and Symbian from m.opera.com. Opera Mini 7 for iOS is available from the Appstore.


text:
Test Page

        <input type="button" value="Jolt" onclick="createDiv()">
        Checkbox Label
        <input id="checkbox-jolt" type="checkbox">

DistanceThenAlignment

            <input style="position: absolute; top: 0; left: 180;" id="dta-C" type="checkbox">
            <input style="position: absolute; top: 12; left: 181;" id="dta-B" type="checkbox">
            <input style="position: absolute; top: 12; left: 200;" id="dta-D" type="checkbox">

AlignmentThenDistance

            <input style="position: absolute; top: 0; left: 180;" id="atd-C" type="checkbox">
            <input style="position: absolute; top: 12; left: 195;" id="atd-B" type="checkbox">
            <input style="position: absolute; top: 12; left: 215;" id="atd-D" type="checkbox">

DistanceOnly

            <input style="position: absolute; top: 0; left: 180;" id="do-C" type="checkbox">
            <input style="position: absolute; top: 12; left: 195;" id="do-B" type="checkbox">

AlignmentOnly

            <input style="position: absolute; top: 0; left: 180;" id="ao-C" type="checkbox">
            <input style="position: absolute; top: 12; left: 195;" id="ao-B" type="checkbox">


text:
<?php

namespace spec\Sylius\Behat\Context\Setup;

use Behat\Behat\Context\Context;
use Doctrine\Common\Persistence\ObjectManager;
use PhpSpec\ObjectBehavior;
use Sylius\Component\Core\Factory\RuleFactoryInterface;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Model\PromotionInterface;
use Sylius\Component\Core\Test\Factory\TestPromotionFactoryInterface;
use Sylius\Component\Core\Test\Services\SharedStorageInterface;
use Sylius\Component\Promotion\Factory\ActionFactoryInterface;
use Sylius\Component\Promotion\Model\ActionInterface;
use Sylius\Component\Promotion\Model\RuleInterface;
use Sylius\Component\Promotion\Repository\PromotionRepositoryInterface;

/**
 * @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
 */
class PromotionContextSpec extends ObjectBehavior
{
    function let(
        SharedStorageInterface $sharedStorage,
        ActionFactoryInterface $actionFactory,
        RuleFactoryInterface $ruleFactory,
        TestPromotionFactoryInterface $testPromotionFactory,
        PromotionRepositoryInterface $promotionRepository,
        ObjectManager $objectManager
    ) {
        $this->beConstructedWith(
            $sharedStorage,
            $actionFactory,
            $ruleFactory,
            $testPromotionFactory,
            $promotionRepository,
            $objectManager
        );
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Sylius\Behat\Context\Setup\PromotionContext');
    }

    function it_implements_context_interface()
    {
        $this->shouldImplement(Context::class);
    }

    function it_creates_promotion(
        $sharedStorage,
        $testPromotionFactory,
        $promotionRepository,
        ChannelInterface $channel,
        PromotionInterface $promotion
    ) {
        $sharedStorage->get('channel')->willReturn($channel);

        $testPromotionFactory->createForChannel('Super promotion', $channel)->willReturn($promotion);

        $promotionRepository->add($promotion)->shouldBeCalled();
        $sharedStorage->set('promotion', $promotion)->shouldBeCalled();

        $this->thereIsPromotion('Super promotion');
    }

    function it_creates_fixed_discount_action_for_promotion(
        $actionFactory,
        $objectManager,
        ActionInterface $action,
        PromotionInterface $promotion
    ) {
        $actionFactory->createFixedDiscount(1000)->willReturn($action);
        $promotion->addAction($action)->shouldBeCalled();

        $objectManager->flush()->shouldBeCalled();

        $this->itGivesFixedDiscountToEveryOrder($promotion, 1000);
    }

    function it_creates_percentage_discount_action_for_promotion(
        $sharedStorage,
        $actionFactory,
        $objectManager,
        ActionInterface $action,
        PromotionInterface $promotion
    ) {
        $sharedStorage->get('promotion')->willReturn($promotion);

        $actionFactory->createPercentageDiscount(0.1)->willReturn($action);
        $promotion->addAction($action)->shouldBeCalled();

        $objectManager->flush()->shouldBeCalled();

        $this->itGivesPercentageDiscountToEveryOrder($promotion, 0.1);
    }

    function it_creates_fixed_discount_promotion_for_cart_with_specified_quantity(
        $sharedStorage,
        $actionFactory,
        $ruleFactory,
        $objectManager,
        ActionInterface $action,
        RuleInterface $rule,
        PromotionInterface $promotion
    ) {
        $sharedStorage->get('promotion')->willReturn($promotion);

        $actionFactory->createFixedDiscount(1000)->willReturn($action);
        $promotion->addAction($action)->shouldBeCalled();

        $ruleFactory->createCartQuantity(5)->willReturn($rule);
        $promotion->addRule($rule)->shouldBeCalled();

        $objectManager->flush()->shouldBeCalled();

        $this->itGivesFixedDiscountToEveryOrderWithQuantityAtLeast($promotion, 1000, '5');
    }

    function it_creates_fixed_discount_promotion_for_cart_with_specified_items_total(
        $actionFactory,
        $ruleFactory,
        $objectManager,
        ActionInterface $action,
        RuleInterface $rule,
        PromotionInterface $promotion
    ) {
        $actionFactory->createFixedDiscount(1000)->willReturn($action);
        $promotion->addAction($action)->shouldBeCalled();

        $ruleFactory->createItemTotal(5000)->willReturn($rule);
        $promotion->addRule($rule)->shouldBeCalled();

        $objectManager->flush()->shouldBeCalled();

        $this->itGivesFixedDiscountToEveryOrderWithItemsTotalAtLeast($promotion, 1000, 5000);
    }

    function it_creates_percentage_shipping_discount_action_for_promotion(
        $actionFactory,
        $objectManager,
        ActionInterface $action,
        PromotionInterface $promotion
    ) {
        $actionFactory->createPercentageShippingDiscount(0.1)->willReturn($action);
        $promotion->addAction($action)->shouldBeCalled();

        $objectManager->flush()->shouldBeCalled();

        $this->itGivesPercentageDiscountOnShippingToEveryOrder($promotion, 0.1);
    }
}


text:
An XML External Entity attack is a type of attack against an
application that parses XML input.

This attack occurs when XML input
containing a reference to an external entity is processed by a weakly
configured XML parser.

This attack may lead to the disclosure of
confidential data, denial of service, port scanning from the
perspective of the machine where the parser is located, and other
system impacts.


text:
using UnityEngine;
using System;
using System.Collections;

public class Edge {
	public int index;
	public Center d0, d1;  // Delaunay edge
	public Corner v0, v1;  // Voronoi edge
	public Nullable<Vector2> midpoint;  // halfway between v0,v1
	public int river;  // volume of water, or 0

}


text:
from flask import (Blueprint, current_app, flash, g, redirect, render_template, url_for)
from flask_login import current_user, login_required, logout_user
from sqlalchemy_utils import get_class_by_table

from app import db
from app.forms import SearchForm
from app.models import Word
from app.utils import get_or_create

main = Blueprint('main', __name__)

@main.route('/')
@main.route('/index')
@main.route('/index/<int:page>')
@login_required
def index(page=1):
    words = current_user.dictionary.words.paginate(page, current_app.config.get('WORDS_PER_PAGE'))
    return render_template('index.html', title='Home', words=words)

@main.route('/new/<word_class:word_class>', methods=['GET', 'POST'])
@login_required
def create_word(word_class):
    form = word_class.form()

    if form.validate_on_submit():
        word, created = get_or_create(word_class, dictionary=current_user.dictionary,
                                      **{key: value for key, value in form.data.items() if key != 'next'})
        if created:
            word.save()
            flash('Successfully created word!', 'success')
            return redirect(url_for('main.index'))
        else:
            flash('An identical word already exists.', 'error')

    return render_template('form.html', title='New Word', form=form)

@main.route('/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def edit_word(id):
    word = Word.query.filter_by(id=id, dictionary=current_user.dictionary).first_or_404()
    form = word.form(obj=word)

    if form.validate_on_submit():
        new_word = get_class_by_table(Word,
                                      Word.__table__,
                                      data={'type': word.type}).query.filter_by(
                                          **{key: value
                                             for key, value in form.data.items() if key != 'next'}).first()
        if new_word is None:
            form.populate_obj(word)
            word.save()
            flash('Successfully edited word!', 'success')
            return form.redirect('index')
        else:
            flash('An identical word already exists.', 'error')

    return render_template('form.html', title='Edit Word', form=form)

@main.route('/delete/<int:id>')
@login_required
def delete_word(id):
    word = Word.query.filter_by(id=id, dictionary=current_user.dictionary).first_or_404()
    db.session.delete(word)
    db.session.commit()
    flash('Deleted word.', 'warning')

    return redirect(url_for('main.index'))

@main.route('/search', methods=['POST'])
@login_required
def search():
    if not g.search_form.validate_on_submit():
        return redirect(url_for('main.index'))
    return redirect(url_for('main.search_results', query=g.search_form.search_field.data))

@main.route('/search_results/<query>')
@main.route('/search_results/<query>/<int:page>')
@login_required
def search_results(query, page=1):
    words = Word.query.search(query).paginate(page, current_app.config.get('WORDS_PER_PAGE'))
    return render_template('search_results.html', title='Search Results', query=query, words=words)

@main.route('/login')
def login():
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))

    return render_template('login.html', title='Log In')

@main.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('main.login'))

@main.before_request
def before_request():
    g.search_form = SearchForm()

@main.context_processor
def inject_word_classes():
    return {'word_classes': [word_class.__mapper_args__['polymorphic_identity']
                             for word_class in Word.__subclasses__()]}


text:
package com.google.tmch.model;

import java.io.Serializable;

public class Child implements Serializable{
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private String child_id;
	private String mom_id;
	private String child_order;
	private String child_firstname;
	private String child_lastname;
	private String child_blood;
	private String child_id13;
	private String child_region;
	private String child_gender;
	private String child_birthday;
	private double child_weight;
	private double child_height;
	private double child_length_of_head;
	private String child_false_born;
	private String child_health_born;
	private String child_crtd_time;
	private String child_uptd_time;

	public String getChild_id() {
		return child_id;
	}

	public void setChild_id(String child_id) {
		this.child_id = child_id;
	}

	public String getMom_id() {
		return mom_id;
	}

	public void setMom_id(String mom_id) {
		this.mom_id = mom_id;
	}

	public String getChild_order() {
		return child_order;
	}

	public void setChild_order(String child_order) {
		this.child_order = child_order;
	}

	public String getChild_firstname() {
		return child_firstname;
	}

	public void setChild_firstname(String child_firstname) {
		this.child_firstname = child_firstname;
	}

	public String getChild_lastname() {
		return child_lastname;
	}

	public void setChild_lastname(String child_lastname) {
		this.child_lastname = child_lastname;
	}

	public String getChild_blood() {
		return child_blood;
	}

	public void setChild_blood(String child_blood) {
		this.child_blood = child_blood;
	}

	public String getChild_id13() {
		return child_id13;
	}

	public void setChild_id13(String child_id13) {
		this.child_id13 = child_id13;
	}

	public String getChild_region() {
		return child_region;
	}

	public void setChild_region(String child_region) {
		this.child_region = child_region;
	}

	public String getChild_gender() {
		return child_gender;
	}

	public void setChild_gender(String child_gender) {
		this.child_gender = child_gender;
	}

	public String getChild_birthday() {
		return child_birthday;
	}

	public void setChild_birthday(String child_birthday) {
		this.child_birthday = child_birthday;
	}

	public double getChild_weight() {
		return child_weight;
	}

	public void setChild_weight(double child_weight) {
		this.child_weight = child_weight;
	}

	public double getChild_height() {
		return child_height;
	}

	public void setChild_height(double child_height) {
		this.child_height = child_height;
	}

	public double getChild_length_of_head() {
		return child_length_of_head;
	}

	public void setChild_length_of_head(double child_length_of_head) {
		this.child_length_of_head = child_length_of_head;
	}

	public String getChild_false_born() {
		return child_false_born;
	}

	public void setChild_false_born(String child_false_born) {
		this.child_false_born = child_false_born;
	}

	public String getChild_health_born() {
		return child_health_born;
	}

	public void setChild_health_born(String child_health_born) {
		this.child_health_born = child_health_born;
	}

	public String getChild_crtd_time() {
		return child_crtd_time;
	}

	public void setChild_crtd_time(String child_crtd_time) {
		this.child_crtd_time = child_crtd_time;
	}

	public String getChild_uptd_time() {
		return child_uptd_time;
	}

	public void setChild_uptd_time(String child_uptd_time) {
		this.child_uptd_time = child_uptd_time;
	}

	@Override
	public String toString() {
		return "Child [child_id=" + child_id + ", mom_id=" + mom_id
				+ ", child_order=" + child_order + ", child_firstname="
				+ child_firstname + ", child_lastname=" + child_lastname
				+ ", child_blood=" + child_blood + ", child_id13=" + child_id13
				+ ", child_region=" + child_region + ", child_gender="
				+ child_gender + ", child_birthday=" + child_birthday
				+ ", child_weight=" + child_weight + ", child_height="
				+ child_height + ", child_length_of_head="
				+ child_length_of_head + ", child_false_born="
				+ child_false_born + ", child_health_born=" + child_health_born
				+ ", child_crtd_time=" + child_crtd_time + ", child_uptd_time="
				+ child_uptd_time + "]";
	}

}


text:
var success = "\x1b[42;30m✓\x1b[0m",
	failure = "\x1b[41;30m✗\x1b[0m";

// Right-align runtime in a field that's 10 columns wide
function formatRuntime( runtime ) {
	var index,
		str = "" + runtime,
		indent = "";

	for ( index = 0; index < Math.max( 0, 10 - str.length ); index++ ) {
		indent += " ";
	}

	return indent + str;
}

module.exports = {
	moduleStart: function( status ) {

		// Parameters: status: { name, tests }

		if ( status.name ) {
			console.log( "\n### " + status.name );
		}
	},
	testStart: function( status ) {

		// Parameters: status: { name, module, testId }

		if ( status.name ) {
			console.log( "\n" + status.name );
		}
	},
	log: function( status ) {

		// Parameters: status: { module, result(t/f), message, actual, expected, testId, runtime }

		console.log(
			( status.result ? success : failure ) +
			" @" + formatRuntime( status.runtime ) + ": " +
			status.message );
		if ( !status.result ) {
			console.log( "Actual: " );
			console.log( this.dump.parse( status.actual ) );
			console.log( "Expected: " );
			console.log( this.dump.parse( status.expected ) );
		}
	},

	done: function( status ) {
		var passed = "\x1b[42;30m " + status.passed + " \x1b[0m",
			failed = "\x1b[41;30m " + status.failed + " \x1b[0m";

		console.log( "Total assertions: " +
			"(" + passed + ( status.failed > 0 ? "+" + failed : "" ) + ") / " + status.total );

		process.exit( status.failed > 0 ? 1 : 0 );
	}
};


text:
import styled from 'styled-components'

import css, { theme } from '@/utils/css'

export const Wrapper = styled.div`
  margin-bottom: 18px;
`
export const Header = styled.div`
  ${css.flex('align-center', 'justify-between')};
`
export const Title = styled.a`
  font-size: 15.5px;
  color: ${theme('thread.articleTitle')};
  text-decoration: none;

  &:hover {
    text-decoration: underline;
    color: #139c9e;
    cursor: pointer;
  }
`
export const PubDate = styled.div`
  color: ${theme('thread.articleDigest')};
  font-size: 12px;
  margin-right: 10px;
  opacity: 0.8;
`
export const Digest = styled.div`
  ${css.lineClamp(3)}
  font-size: 13px;
  color: ${theme('thread.articleDigest')};
  margin-top: 7px;
`


text:
<?php
namespace Payum\Registry;

use Payum\PaymentInterface;
use Payum\Exception\InvalidArgumentException;

interface PaymentRegistryInterface
{
    /**
     * @return string
     */
    function getDefaultPaymentName();

    /**
     * @param string|null $name
     *
     * @throws InvalidArgumentException if payment with such name not exist
     *
     * @return PaymentInterface
     */
    function getPayment($name = null);
}


text:
package com.bsencan.openchess.model.pieces;

import com.bsencan.openchess.model.Move;
import com.bsencan.openchess.model.Piece;

/**
 * Represents a rook chess piece. See {@link Piece}.
 *
 * @author Baris Sencan
 */
public class Rook extends Piece {

	public Rook(int x, int y, boolean isWhite) {
		super(x, y, isWhite, isWhite ? "white-rook" : "black-rook");

		/* Add valid moves. */
		this.validMoves.add(new Move(0, 1, true));
		this.validMoves.add(new Move(1, 0, true));
		this.validMoves.add(new Move(0, -1, true));
		this.validMoves.add(new Move(-1, 0, true));
	}

}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>FFCS Free Slots</title>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
      <link rel="stylesheet" href="css/style1.css">

FFCS - Free Slots

Visualize and get the most free time slots of peers. Enter the timetable of your friends in the database and enjoy coffee with them during their free slots.

Click here!


text:
//
//  TXView3.m
//  TXCustomMenu
//
//  Created by komlin on 2017/10/27.
//  Copyright © 2017年 komlin. All rights reserved.
//

#import "TXView3.h"

@implementation TXView3

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright (C) 2012-2013 Facebook, Inc.

    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.

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

    <parent>
        <groupId>com.facebook.nifty</groupId>
        <artifactId>nifty-parent</artifactId>
        <version>0.16.0-SNAPSHOT</version>
    </parent>

    <description>Load tester</description>
    <artifactId>nifty-load-tester</artifactId>
    <packaging>jar</packaging>

    <properties>
        <air.main.basedir>${project.parent.basedir}</air.main.basedir>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.2.5</version>
                <exclusions>
                    <exclusion>
                        <groupId>commons-logging</groupId>
                        <artifactId>commons-logging</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>

            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpcore</artifactId>
                <version>4.2.4</version>
                <exclusions>
                    <exclusion>
                        <groupId>commons-logging</groupId>
                        <artifactId>commons-logging</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>com.facebook.nifty</groupId>
            <artifactId>nifty-core</artifactId>
        </dependency>
        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>bootstrap</artifactId>
        </dependency>
        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>configuration</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libthrift</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <configuration>
                    <transformers>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                            <mainClass>com.facebook.nifty.perf.NiftyLoadTester</mainClass>
                        </transformer>
                    </transformers>
                </configuration>
            </plugin>

            <!-- Configure PMD plugin to skip checking of thrift-generated files -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-pmd-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>**/LoadTest.java</exclude>
                        <exclude>**/LoadError.java</exclude>
                    </excludes>
                </configuration>
            </plugin>

            <!-- This is mainly for perf testing, doesn't need to be deployed -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.7</version>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
createHTTPRequestObject = function() {
    // although IE supports the XMLHttpRequest object, but it does not work on local files.
    var forceActiveX = (window.ActiveXObject && location.protocol === "file:");
    if (window.XMLHttpRequest && !forceActiveX) {
        return new XMLHttpRequest();
    } else {
        try {
            return new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {}
    }
    alert ("Your browser doesn't support XML handling!");
    return null;
}

getJSON = function(url, callback)
{
    var xhr = createHTTPRequestObject();
    xhr.open("get", url, true);
    xhr.setRequestHeader("Accept", "application/json, text/javascript, */*; q=0.01");
    xhr.setRequestHeader("Authorization", "token " + config.access_token);
    xhr.onreadystatechange = function() {
        if (xhr.readyState==4 && xhr.status==200) {
            var headers = {};
            if (xhr.getAllResponseHeaders) {
                var headersArray = xhr.getAllResponseHeaders().split("\n");
                for (var i=0; i<headersArray.length; i++) {
                    var kv = headersArray[i].split(": ");
                    if (kv.length==2) {
                        var k = kv[0].toLowerCase();
                        headers[k] = kv[1];
                    }
                }
            }
            callback(JSON.parse(xhr.responseText), headers);
        }
    }
    xhr.send();
}

ajax = function(post, url, callback) {
    var xhr = createHTTPRequestObject();
    var method = "post";
    if (post == null) {
        method = "get";
    }
    xhr.open(method, url, true);
    xhr.setRequestHeader("Accept", "application/json, text/javascript, */*; q=0.01");
    xhr.setRequestHeader("Authorization", "token " + config.access_token);
    xhr.onreadystatechange = function() {
        if (xhr.readyState==4 && xhr.status==200)
        {
            callback(xhr.responseText);
        }
    }
    xhr.send(JSON.stringify(post));
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="css/app.css">
  <title><%= name %></title>

<%= name %>


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

<title>F-Index</title>
<meta name="date" content="2014-02-07">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B D E F G H I J K L M N O P R S T U V

F

fields - Variable in class hu.szabot.transloadit.ApiData

Data fields of a request (key - value pairs)

fields - Variable in class hu.szabot.transloadit.executor.ParsedApiData

The parsed fields (custom and params)

fileCheck(File) - Method in class hu.szabot.transloadit.assembly.AssemblyBuilder

Validates the passed key

fileIncrement - Variable in class hu.szabot.transloadit.assembly.AssemblyBuilder

File increment value to store the index of the files to be uploaded which have auto generated key

FILENAME_KEY_POSTFIX - Static variable in class hu.szabot.transloadit.assembly.AssemblyBuilder

Prefix for autogenerated file keys

FILENAME_KEY_PREFIX - Static variable in class hu.szabot.transloadit.assembly.AssemblyBuilder

Postfix for autogenerated file keys

FileNotOpenableException - Exception in hu.szabot.transloadit.exceptions

Thrown when a File not openable or not readable

FileNotOpenableException(File) - Constructor for exception hu.szabot.transloadit.exceptions.FileNotOpenableException

files - Variable in class hu.szabot.transloadit.ApiData

File objects of the files which will be sent

files - Variable in class hu.szabot.transloadit.executor.ParsedApiData

File objects of the files which will be sent

fromJson(Object) - Method in class hu.szabot.transloadit.parser.JSONResponseParser

Parse the Object

A B D E F G H I J K L M N O P R S T U V

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
///////////////////////////////////////////////////////////////////////////////
//Copyright (C) 2005 Thomas Morton
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
//////////////////////////////////////////////////////////////////////////////
package ch.epfl.bbp.shaded.opennlp.tools.util;

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Comparator;

/**
 * This class implements the heap interface using a {@link java.util.List} as the underlying
 * data structure.  This heap allows values which are equals to be inserted, however
 * the order in which they are extracted is arbitrary.
 */
public class ListHeap implements Heap {
  private List list;

  private Comparator comp;

  private int size;

  private Object max = null;

  /**
   * Creates a new heap with the specified size using the sorted based on the
   * specified comparator.
   * @param sz The size of the heap.
   * @param c The comparator to be used to sort heap elements.
   */
  public ListHeap(int sz, Comparator c) {
    size = sz;
    comp = c;
    list = new ArrayList(sz);
  }

  /**
   * Createa a new heap of the specified size.
   * @param sz The size of the new heap.
   */
  public ListHeap(int sz) {
    this(sz, null);
  }

  private int parent(int i) {
    return (i - 1) / 2;
  }

  private int left(int i) {
    return (i + 1) * 2 - 1;
  }

  private int right(int i) {
    return (i + 1) * 2;
  }

  public int size() {
    return list.size();
  }

  private void swap(int x, int y) {
    Object ox = list.get(x);
    Object oy = list.get(y);

    list.set(y, ox);
    list.set(x, oy);
  }

  private boolean lt(Object o1, Object o2) {
    if (comp != null) {
      return (comp.compare(o1, o2) < 0);
    }
    else {
      return (((Comparable) o1).compareTo(o2) < 0);
    }
  }

  private boolean gt(Object o1, Object o2) {
    if (comp != null) {
      return (comp.compare(o1, o2) > 0);
    }
    else {
      return (((Comparable) o1).compareTo(o2) > 0);
    }
  }

  private void heapify(int i) {
    while (true) {
      int l = left(i);
      int r = right(i);
      int smallest;

      if (l < list.size() && lt(list.get(l), list.get(i)))
        smallest = l;
      else
        smallest = i;

      if (r < list.size() && lt(list.get(r), list.get(smallest)))
        smallest = r;

      if (smallest != i) {
        swap(smallest, i);
        i = smallest;
      }
      else
        break;
    }
  }

  public Object extract() {
    if (list.size() == 0) {
      throw new RuntimeException("Heap Underflow");
    }
    Object top = list.get(0);
    int last = list.size() - 1;
    if (last != 0) {
      list.set(0, list.remove(last));
      heapify(0);
    }
    else {
      list.remove(last);
    }

    return top;
  }

  public void setSize() {
    setSize(size);
  }

  public void setSize(int sz) {
    if (sz > list.size()) {
      return;
    }
    else {
      List t = new ArrayList(sz);
      for (int i = 0; i < sz; i++) {
        t.add(this.extract());
      }
      list = t;
    }
  }

  public Object top() {
    if (list.size() == 0) {
      throw new RuntimeException("Heap Underflow");
    }
    return (list.get(0));
  }

  public void add(Object o) {
    /* keep track of min to prevent unnecessary insertion */
    if (max == null) {
      max = o;
    }
    else if (gt(o, max)) {
      if (list.size() < size) {
        max = o;
      }
      else {
        return;
      }
    }
    list.add(o);

    int i = list.size() - 1;

    //percolate new node to correct position in heap.
    while (i > 0 && gt(list.get(parent(i)), o)) {
      list.set(i, list.get(parent(i)));
      i = parent(i);
    }

    list.set(i, o);
  }

  public void clear() {
    list.clear();
  }

  public Iterator iterator() {
    return (list.iterator());
  }

  public boolean isEmpty() {
    return this.list.isEmpty();
  }

  public static void main(String[] args) {
   Heap heap = new ListHeap(5);
   for (int ai=0;ai<args.length;ai++){
     heap.add(new Integer(Integer.parseInt(args[ai])));
   }
   while (!heap.isEmpty()) {
     System.out.print(heap.extract()+" ");
   }
   System.out.println();
  }
}


text:
namespace VideoStore.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class Genres : DbMigration
    {
        public override void Up()
        {
            Sql("INSERT INTO Genres (Id, Name) VALUES (1, 'Action')");
            Sql("INSERT INTO Genres (Id, Name) VALUES (2, 'Thriller')");
            Sql("INSERT INTO Genres (Id, Name) VALUES (3, 'Family')");
            Sql("INSERT INTO Genres (Id, Name) VALUES (4, 'Romance')");
            Sql("INSERT INTO Genres (Id, Name) VALUES (5, 'Comedy')");
        }

        public override void Down()
        {
        }
    }
}


text:
//
//  DCFiltrateViewController.m
//  CDDMall
//
//  Created by apple on 2017/6/16.
//  Copyright © 2017年 RocketsChen. All rights reserved.
//
#define FiltrateViewScreenW ScreenW * 0.7

#import "DCFiltrateViewController.h"

// Controllers

// Models
#import "DCFiltrateItem.h"
// Views
#import "DCFiltrateAttrCell.h"
#import "DCFiltrateHeaderView.h"
// Vendors
#import <MJExtension.h>
#import "UIViewController+XWTransition.h"
// Categories

// Others

@interface DCFiltrateViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

/* 筛选父View */
@property (strong , nonatomic)UIView *filtrateConView;

/* collectionView */
@property (strong , nonatomic)UICollectionView *collectionView;

@property (nonatomic , strong) NSMutableArray<DCFiltrateItem *> *filtrateItem;

@end

static NSString * const DCFiltrateAttrCellID = @"DCFiltrateAttrCell";
static NSString * const DCFiltrateHeaderViewID = @"DCFiltrateHeaderView";

@implementation DCFiltrateViewController

#pragma mark - LazyLoad

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.alwaysBounceVertical = YES;

        [_collectionView registerClass:[DCFiltrateAttrCell class] forCellWithReuseIdentifier:DCFiltrateAttrCellID];

        [_collectionView registerClass:[DCFiltrateHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:DCFiltrateHeaderViewID]; //头部
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter"]; //尾部
    }
    return _collectionView;
}

#pragma mark - LifeCyle
- (void)viewDidLoad {
    [super viewDidLoad];

    [self setUpFootprintAlterView];

    [self setUpInit];

    [self setUpFiltrateData];

    [self setUpBottomButton];
}

#pragma mark - initialize
- (void)setUpInit
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    _filtrateConView = [[UIView alloc] init];
    _filtrateConView.backgroundColor = self.view.backgroundColor;

    _filtrateConView.frame = CGRectMake(0, 0, FiltrateViewScreenW, ScreenH);
    [self.view addSubview:_filtrateConView];

    [_filtrateConView addSubview:self.collectionView];
    _collectionView.frame = CGRectMake(5, 0, FiltrateViewScreenW - DCMargin, ScreenH - 50);
}

#pragma mark - 筛选Item数据
- (void)setUpFiltrateData
{
    _filtrateItem = [DCFiltrateItem mj_objectArrayWithFilename:@"FiltrateItem.plist"];
}

#pragma mark - 底部重置确定按钮
- (void)setUpBottomButton
{
    CGFloat buttonW = FiltrateViewScreenW/2;
    CGFloat buttonH = 50;
    CGFloat buttonY = ScreenH - buttonH;
    NSArray *titles = @[@"重置",@"确定"];
    for (NSInteger i = 0; i < titles.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:titles[i] forState:UIControlStateNormal];
        button.tag = i;
        if (i == 0) {
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
        CGFloat buttonX = i*buttonW;
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        button.titleLabel.font = PFR16Font;
        button.backgroundColor = (i == 0) ? self.collectionView.backgroundColor : [UIColor redColor];
        [button addTarget:self action:@selector(bottomButtonClick:) forControlEvents:UIControlEventTouchUpInside];

        [_filtrateConView addSubview:button];
    }
}

#pragma mark - <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.filtrateItem.count;
}

#pragma mark - <UICollectionViewDelegate>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return self.filtrateItem[section].isOpen ? self.filtrateItem[section].content.count + self.filtrateItem[section].header.count: self.filtrateItem[section].header.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    DCFiltrateAttrCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:DCFiltrateAttrCellID forIndexPath:indexPath];

    cell.content = self.filtrateItem[indexPath.section].header[indexPath.row];

    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {

    if ([kind  isEqualToString:UICollectionElementKindSectionHeader]) {

        DCFiltrateHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:DCFiltrateHeaderViewID forIndexPath:indexPath];
        headerView.title = _filtrateItem[indexPath.section].title;

        return headerView;
    }else {

        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter" forIndexPath:indexPath];
        [DCSpeedy dc_setUpAcrossPartingLineWith:footerView WithColor:[[UIColor lightGrayColor]colorWithAlphaComponent:0.4]];
        return footerView;
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout

#pragma mark - item宽高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((FiltrateViewScreenW - 7 * 5) / 3, 22);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {

    return CGSizeMake(self.collectionView.dc_width, 55);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeMake(FiltrateViewScreenW, DCMargin);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 5;
}
#pragma mark - 弹出弹框
- (void)setUpFootprintAlterView
{
    XWInteractiveTransitionGestureDirection direction = XWInteractiveTransitionGestureDirectionLeft;
    __weak typeof(self)weakSelf = self;
    [self xw_registerBackInteractiveTransitionWithDirection:direction transitonBlock:^(CGPoint startPoint){
        [weakSelf selfViewBack];
    } edgeSpacing:80];
}

#pragma mark - 展开列表
- (void)openSection:(NSInteger)section{

    if (!self.filtrateItem[section].content) {return;}
    [self.collectionView insertItemsAtIndexPaths:[self getIndexArray:section]];
}

#pragma mark - 关闭列表
- (void)closeSection:(NSInteger)section{

    if (!self.filtrateItem[section].content) {return;}
    [self.collectionView deleteItemsAtIndexPaths:[self getIndexArray:section]];
}

#pragma mark - 获得需要展开的数据
- (NSMutableArray *)getIndexArray : (NSInteger)section {

    NSMutableArray *indexArray = [NSMutableArray array];
    NSInteger subCount = self.filtrateItem[section].content.count;
    if (subCount <= 0) {return nil;}

    for (int i = 0; i < subCount; i++) {

        NSIndexPath *indexpath = [NSIndexPath indexPathForRow:i inSection:section];
        [indexArray addObject:indexpath];
    }
    return indexArray;
}

#pragma mark - 退出当前View
- (void)selfViewBack{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 点击事件
- (void)bottomButtonClick:(UIButton *)button
{
    if (button.tag == 0) {//重置点击
        [self.collectionView reloadData];
    }else if (button.tag == 1){//确定点击

    }
}

@end


text:
#import <Foundation/NSMutableDictionary_mapTable.h>

#import <Foundation/NSEnumerator_dictionaryKeys.h>
#import <Foundation/NSAutoreleasePool-private.h>
#import <Foundation/NSString.h>
#import <Foundation/NSException.h>
#import <Foundation/NSRaise.h>
#import <Foundation/NSRaiseException.h>

@implementation NSMutableDictionary_mapTable

-(NSUInteger)count {
   return NSCountMapTable(_table);
}

-objectForKey:key {
   id object=NSMapGet(_table,key);

   return object;
}

-(NSEnumerator *)keyEnumerator {
   return NSAutorelease(NSEnumerator_dictionaryKeysNew(_table));
}

static inline void setObjectForKey(NSMutableDictionary_mapTable *self,id object,id key){
   if (key==nil)
    NSRaiseException(NSInvalidArgumentException,self,@selector(setObject:forKey:),@"Attempt to insert object with nil key");
   else if(object==nil)
    NSRaiseException(NSInvalidArgumentException,self,@selector(setObject:forKey:),@"Attempt to insert nil object for key %@", key);

   key=[key copy];
   NSMapInsert(self->_table,key,object);
   [key release];
}

-(void)setObject:object forKey:key {
   setObjectForKey(self,object,key);
}

-(void)removeObjectForKey:key {
   NSMapRemove(_table,key);
}

-initWithCapacity:(NSUInteger)capacity {
   _table=NSCreateMapTableWithZone(NSObjectMapKeyCallBacks,
     NSObjectMapValueCallBacks,capacity,NULL);
   return self;
}

-(void)dealloc {
   if(_table!=NULL)
    NSFreeMapTable(_table);
   NSDeallocateObject(self);
   return;
   [super dealloc];
}

-(void)addEntriesFromDictionary:(NSDictionary *)dictionary {
   NSEnumerator *keyEnum=[dictionary keyEnumerator];
   id            key;

   while((key=[keyEnum nextObject])!=nil)
    setObjectForKey(self,[dictionary objectForKey:key],key);
}

@end


text:
import React from 'react';
import ReactDOM from 'react-dom';

jest.dontMock('./../react_components/PaginationBoxView');
jest.dontMock('./../react_components/PageView');
jest.dontMock('./../react_components/BreakView');

const PaginationBoxView = require('./../react_components/PaginationBoxView').default;
const PageView = require('./../react_components/PageView').default;
const BreakView = require('./../react_components/BreakView').default;

import ReactTestUtils from 'react-addons-test-utils';

describe('PaginationBoxView', () => {
  const pagination = ReactTestUtils.renderIntoDocument(
    <PaginationBoxView />
  );

  it('should render a pagination component', () => {
    expect(ReactDOM.findDOMNode(pagination).nodeName).toEqual("UL");

    ReactTestUtils.scryRenderedComponentsWithType(pagination, PaginationBoxView);

    expect(ReactDOM.findDOMNode(pagination).querySelector("li:first-child a").textContent).toBe("Previous");
    expect(ReactDOM.findDOMNode(pagination).querySelector(".selected a").textContent).toBe("1");
    expect(ReactDOM.findDOMNode(pagination).querySelector("li:last-child a").textContent).toBe("Next");

    const pages = ReactDOM.findDOMNode(pagination).querySelectorAll("li");
    // 3*2 margins + 1 break label + previous & next buttons == 9:
    expect(pages.length).toEqual(9);
  });

  it('test previous and next buttons', () => {
    let elmts = ReactTestUtils.scryRenderedDOMComponentsWithTag(pagination, 'a');
    let previous = elmts[0];
    let next = elmts[elmts.length - 1];

    ReactTestUtils.Simulate.click(next);

    expect(ReactDOM.findDOMNode(pagination).querySelector(".selected a").textContent).toBe("2");

    ReactTestUtils.Simulate.click(previous);

    expect(ReactDOM.findDOMNode(pagination).querySelector(".selected a").textContent).toBe("1");
  });

  it('test click on a page item', () => {
    ReactTestUtils.findRenderedComponentWithType(pagination, PaginationBoxView);

    const pageItem = ReactDOM.findDOMNode(pagination).querySelector("li:nth-child(3) a");

    ReactTestUtils.Simulate.click(pageItem);

    expect(ReactDOM.findDOMNode(pagination).querySelector(".selected a").textContent).toBe("2");
  });

  it('test rendering only active page item', function() {
    const smallPagination = ReactTestUtils.renderIntoDocument(
      <PaginationBoxView
        initialPage={0}
        pageRangeDisplayed={0}
        marginPagesDisplayed={0}
        breakLabel={null} />
    );

    const pageItems = ReactDOM.findDOMNode(smallPagination).querySelectorAll("li");
    // Prev, selected page, next
    expect(pageItems.length).toBe(3);
  });

  it('should render href attribute in items if hrefBuilder is specified', function() {
    const linkedPagination = ReactTestUtils.renderIntoDocument(
      <PaginationBoxView
        initialPage={1}
        hrefBuilder={(page) => '/page/' + page } />
    );

    expect(ReactDOM.findDOMNode(linkedPagination).querySelector('li:last-child a')
      .getAttribute('href')).toBe('/page/3');
    expect(ReactDOM.findDOMNode(linkedPagination).querySelector('li:first-child a')
      .getAttribute('href')).toBe('/page/1');
    expect(ReactDOM.findDOMNode(linkedPagination).querySelector('.selected a')
      .getAttribute('href')).toBe(null);

    const linkedPaginationWithPageCount = ReactTestUtils.renderIntoDocument(
      <PaginationBoxView
        pageCount={5}
        pageRangeDisplayed={10}
        initialPage={1}
        hrefBuilder={(page) => '/pagexx/' + page }
      />
    );

    expect(
      ReactDOM.findDOMNode(linkedPaginationWithPageCount)
        .querySelector('li:nth-child(2) a').getAttribute('href')
    ).toBe('/pagexx/1');
  });

  it('should not render href attribute in items if hrefBuilder is not specified', function() {
    const linkedPagination = ReactTestUtils.renderIntoDocument(
      <PaginationBoxView />
    );

    expect(ReactDOM.findDOMNode(linkedPagination).querySelector('li:last-child a')
      .hasAttribute('href')).toBe(false);
    expect(ReactDOM.findDOMNode(linkedPagination).querySelector('li:first-child a')
      .hasAttribute('href')).toBe(false);
    expect(ReactDOM.findDOMNode(linkedPagination).querySelector('.selected a')
      .hasAttribute('href')).toBe(false);
  });

  it('test breakClassName rendering', function() {
    const smallPagination = ReactTestUtils.renderIntoDocument(
      <PaginationBoxView breakClassName={"break-me"}/>
    );

    const breakItem = ReactDOM.findDOMNode(smallPagination).querySelectorAll(".break-me");
    expect(breakItem.length).toBe(1);
  });

  describe('prop disableInitialCallback', () => {
    it('test when true', function() {
      const onPageChange = jest.fn();
      const smallPagination = ReactTestUtils.renderIntoDocument(
        <PaginationBoxView
          disableInitialCallback={true}
          initialPage={5}
          onPageChange={onPageChange}
        />
      );

      expect(onPageChange).not.toHaveBeenCalled();
    });
    it('test when false', function() {
      const onPageChange = jest.fn();
      const smallPagination = ReactTestUtils.renderIntoDocument(
        <PaginationBoxView initialPage={5} onPageChange={onPageChange} />
      );

      expect(onPageChange).toHaveBeenCalled();
    });
  });
});


text:
var LOG_FILE = 'test/express_leg.log',
	fs = require('fs'),
	express = require('express'),
	leg = require('leg')(LOG_FILE, { level: 'info' }),
	logger = require('../index.js'),
	request = require('request'),
	should = require('should');

describe('connect-leg for Express', function() {
	'use strict';

	before(function(done) {
		var app = express();

		app.use(logger(leg));

		app.get('/', function(req, res) {
		  res.send('Hello World!');
		});

		var server = app.listen(3000, function () {
			done();
		});
	});

	after(function(done) {
		try {
			fs.unlink(LOG_FILE, function(err) {
				done();
			});
		}
		catch(e) {
			done();
		}
	});

	it('Should be able to log a request', function(done) {
		request('http://localhost:3000', function (err, response, body) {
			(err === null).should.be.ok;
			response.should.exist;

			try {
				fs.statSync(LOG_FILE).isFile().should.be.ok;

				var logFileContent = fs.readFileSync(LOG_FILE).toString();

				logFileContent.indexOf('"host":"localhost"').should.be.greaterThan(-1);
				logFileContent.indexOf('"INFO","request"').should.be.greaterThan(-1);
				logFileContent.indexOf('"method":"GET"').should.be.greaterThan(-1);
				logFileContent.indexOf('"path":"/"').should.be.greaterThan(-1);
				logFileContent.indexOf('"INFO","response"').should.be.greaterThan(-1);
				logFileContent.indexOf('"response":{"status":200}}').should.be.greaterThan(-1);

				done();
			}
			catch(e) {
				(e === null).should.be.ok;
				done();
			}
		});
	});
});


text:
// Package changeset provides Knative utilities for fetching GitHub Commit ID
// from kodata directory. It requires GitHub HEAD file to be linked into
// Knative component source code via the following command:
//   ln -s -r .git/HEAD ./cmd/<knative-component-name>/kodata/
// Then ko will build this file into $KO_DATA_PATH when building the container
// for a Knative component.
package changeset


text:
namespace mozc {

// Simple synchronous HTTP client
//
// Usage:
// 1) Simple GET
// string output;
// CHECK(mozc::HTTPClient::Get("http://www.google.com/", &output));
//
// 2) GET with some manual options.
// mozc::HTTPClient::Option option;
// option.timeout = 200;     // get data within 200msec
// option.headers.push_back("Host: foo.bar.com"); // replace/add header
// CHECK(mozc::HTTPClient::Get("http://www.google.com/", option, &output));
//
// 3) Rewrite an actual implementation (for unittesting)
// class MyHandler: public HTTPClientInterface { .. };
// MyHandler handler;
// mozc::HTTPClient::SetHTTPClientInterface(handler);
class HTTPClientInterface;

class HTTPClient {
 public:
  struct Option {
    bool   include_header;       // include header in output
    size_t max_data_size;        // maximum data size client can retrieve
    int32  timeout;              // timeout
    vector<string> headers;      // additional headers;

    // set default parameter
    Option()
        : include_header(false),
          max_data_size(10 * 1024 * 1024),  // 10Mbyte
          timeout(600000) {}  // 10min
  };

  // Synchronous HTTP GET, HEAD and POST

  // string interface
  static bool Get(const string &url, string *output);
  static bool Head(const string &url, string *output);
  static bool Post(const string &url, const string &data, string *output);

  static bool Get(const string &url, const Option &option, string *output);
  static bool Head(const string &url, const Option &option, string *output);
  static bool Post(const string &url, const string &data,
                   const Option &option, string *output);

  // Inject a dependency for unittesting
  static void SetHTTPClientHandler(const HTTPClientInterface *handler);

 private:
  DISALLOW_IMPLICIT_CONSTRUCTORS(HTTPClient);
};

// Interface class for injecting an actual implementation
class HTTPClientInterface {
 public:
  HTTPClientInterface() {}
  virtual ~HTTPClientInterface() {}

  virtual bool Get(const string &url, const HTTPClient::Option &option,
                   string *output) const = 0;
  virtual bool Head(const string &url, const HTTPClient::Option &option,
                    string *output) const = 0;
  virtual bool Post(const string &url, const string &data,
                    const HTTPClient::Option &option,
                    string *output) const = 0;
};
}  // namespace mozc
#endif  // MOZC_NET_HTTP_CLIENT_H_


text:
#include "core/html/forms/FileInputType.h"

#include "bindings/core/v8/ExceptionStatePlaceholder.h"
#include "core/HTMLNames.h"
#include "core/InputTypeNames.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/events/Event.h"
#include "core/fileapi/File.h"
#include "core/fileapi/FileList.h"
#include "core/frame/UseCounter.h"
#include "core/html/FormData.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/forms/FormController.h"
#include "core/layout/LayoutFileUploadControl.h"
#include "core/page/ChromeClient.h"
#include "core/page/DragData.h"
#include "platform/FileMetadata.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/UserGestureIndicator.h"
#include "platform/text/PlatformLocale.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/text/WTFString.h"

namespace blink {

using blink::WebLocalizedString;
using namespace HTMLNames;

inline FileInputType::FileInputType(HTMLInputElement& element)
    : BaseClickableWithKeyInputType(element)
    , m_fileList(FileList::create())
{
}

PassRefPtrWillBeRawPtr<InputType> FileInputType::create(HTMLInputElement& element)
{
    return adoptRefWillBeNoop(new FileInputType(element));
}

DEFINE_TRACE(FileInputType)
{
    visitor->trace(m_fileList);
    BaseClickableWithKeyInputType::trace(visitor);
}

Vector<FileChooserFileInfo> FileInputType::filesFromFormControlState(const FormControlState& state)
{
    Vector<FileChooserFileInfo> files;
    for (size_t i = 0; i < state.valueSize(); i += 2) {
        if (!state[i + 1].isEmpty())
            files.append(FileChooserFileInfo(state[i], state[i + 1]));
        else
            files.append(FileChooserFileInfo(state[i]));
    }
    return files;
}

const AtomicString& FileInputType::formControlType() const
{
    return InputTypeNames::file;
}

FormControlState FileInputType::saveFormControlState() const
{
    if (m_fileList->isEmpty())
        return FormControlState();
    FormControlState state;
    unsigned numFiles = m_fileList->length();
    for (unsigned i = 0; i < numFiles; ++i) {
        if (m_fileList->item(i)->hasBackingFile()) {
            state.append(m_fileList->item(i)->path());
            state.append(m_fileList->item(i)->name());
        }
        // FIXME: handle Blob-backed File instances, see http://crbug.com/394948
    }
    return state;
}

void FileInputType::restoreFormControlState(const FormControlState& state)
{
    if (state.valueSize() % 2)
        return;
    filesChosen(filesFromFormControlState(state));
}

void FileInputType::appendToFormData(FormData& formData) const
{
    FileList* fileList = element().files();
    unsigned numFiles = fileList->length();
    if (numFiles == 0) {
        formData.append(element().name(), File::create(""));
        return;
    }

    for (unsigned i = 0; i < numFiles; ++i)
        formData.append(element().name(), fileList->item(i));
}

bool FileInputType::valueMissing(const String& value) const
{
    return element().isRequired() && value.isEmpty();
}

String FileInputType::valueMissingText() const
{
    return locale().queryString(element().multiple() ? WebLocalizedString::ValidationValueMissingForMultipleFile : WebLocalizedString::ValidationValueMissingForFile);
}

void FileInputType::handleDOMActivateEvent(Event* event)
{
    if (element().isDisabledFormControl())
        return;

    if (!UserGestureIndicator::processingUserGesture())
        return;

    if (ChromeClient* chromeClient = this->chromeClient()) {
        FileChooserSettings settings;
        HTMLInputElement& input = element();
        settings.allowsDirectoryUpload = input.fastHasAttribute(webkitdirectoryAttr);
        settings.allowsMultipleFiles = settings.allowsDirectoryUpload || input.fastHasAttribute(multipleAttr);
        settings.acceptMIMETypes = input.acceptMIMETypes();
        settings.acceptFileExtensions = input.acceptFileExtensions();
        settings.selectedFiles = m_fileList->pathsForUserVisibleFiles();
        settings.useMediaCapture = RuntimeEnabledFeatures::mediaCaptureEnabled() && input.fastHasAttribute(captureAttr);
        chromeClient->openFileChooser(input.document().frame(), newFileChooser(settings));
    }
    event->setDefaultHandled();
}

LayoutObject* FileInputType::createLayoutObject(const ComputedStyle&) const
{
    return new LayoutFileUploadControl(&element());
}

bool FileInputType::canSetStringValue() const
{
    return false;
}

FileList* FileInputType::files()
{
    return m_fileList.get();
}

bool FileInputType::canSetValue(const String& value)
{
    // For security reasons, we don't allow setting the filename, but we do allow clearing it.
    // The HTML5 spec (as of the 10/24/08 working draft) says that the value attribute isn't
    // applicable to the file upload control at all, but for now we are keeping this behavior
    // to avoid breaking existing websites that may be relying on this.
    return value.isEmpty();
}

bool FileInputType::getTypeSpecificValue(String& value)
{
    if (m_fileList->isEmpty()) {
        value = String();
        return true;
    }

    // HTML5 tells us that we're supposed to use this goofy value for
    // file input controls. Historically, browsers revealed the real
    // file path, but that's a privacy problem. Code on the web
    // decided to try to parse the value by looking for backslashes
    // (because that's what Windows file paths use). To be compatible
    // with that code, we make up a fake path for the file.
    value = "C:\\fakepath\\" + m_fileList->item(0)->name();
    return true;
}

void FileInputType::setValue(const String&, bool valueChanged, TextFieldEventBehavior)
{
    if (!valueChanged)
        return;

    m_fileList->clear();
    element().setNeedsStyleRecalc(SubtreeStyleChange, StyleChangeReasonForTracing::create(StyleChangeReason::ControlValue));
    element().setNeedsValidityCheck();
}

FileList* FileInputType::createFileList(const Vector<FileChooserFileInfo>& files, bool hasWebkitDirectoryAttr)
{
    FileList* fileList(FileList::create());
    size_t size = files.size();

    // If a directory is being selected, the UI allows a directory to be chosen
    // and the paths provided here share a root directory somewhere up the tree;
    // we want to store only the relative paths from that point.
    if (size && hasWebkitDirectoryAttr) {
        // Find the common root path.
        String rootPath = directoryName(files[0].path);
        for (size_t i = 1; i < size; ++i) {
            while (!files[i].path.startsWith(rootPath))
                rootPath = directoryName(rootPath);
        }
        rootPath = directoryName(rootPath);
        ASSERT(rootPath.length());
        int rootLength = rootPath.length();
        if (rootPath[rootLength - 1] != '\\' && rootPath[rootLength - 1] != '/')
            rootLength += 1;
        for (size_t i = 0; i < size; ++i) {
            // Normalize backslashes to slashes before exposing the relative path to script.
            String relativePath = files[i].path.substring(rootLength).replace('\\', '/');
            fileList->append(File::createWithRelativePath(files[i].path, relativePath));
        }
        return fileList;
    }

    for (size_t i = 0; i < size; ++i) {
        if (files[i].fileSystemURL.isEmpty()) {
            fileList->append(File::createForUserProvidedFile(files[i].path, files[i].displayName));
        } else {
            fileList->append(File::createForFileSystemFile(files[i].fileSystemURL, files[i].metadata, File::IsUserVisible));
        }
    }
    return fileList;
}

void FileInputType::countUsage()
{
    Document* document = &element().document();
    if (document->isSecureContext())
        UseCounter::count(*document, UseCounter::InputTypeFileInsecureOrigin);
    else
        UseCounter::count(*document, UseCounter::InputTypeFileSecureOrigin);
}

void FileInputType::createShadowSubtree()
{
    ASSERT(element().shadow());
    RefPtrWillBeRawPtr<HTMLInputElement> button = HTMLInputElement::create(element().document(), 0, false);
    button->setType(InputTypeNames::button);
    button->setAttribute(valueAttr, AtomicString(locale().queryString(element().multiple() ? WebLocalizedString::FileButtonChooseMultipleFilesLabel : WebLocalizedString::FileButtonChooseFileLabel)));
    button->setShadowPseudoId(AtomicString("-webkit-file-upload-button", AtomicString::ConstructFromLiteral));
    element().userAgentShadowRoot()->appendChild(button.release());
}

void FileInputType::disabledAttributeChanged()
{
    ASSERT(element().shadow());
    if (Element* button = toElement(element().userAgentShadowRoot()->firstChild()))
        button->setBooleanAttribute(disabledAttr, element().isDisabledFormControl());
}

void FileInputType::multipleAttributeChanged()
{
    ASSERT(element().shadow());
    if (Element* button = toElement(element().userAgentShadowRoot()->firstChild()))
        button->setAttribute(valueAttr, AtomicString(locale().queryString(element().multiple() ? WebLocalizedString::FileButtonChooseMultipleFilesLabel : WebLocalizedString::FileButtonChooseFileLabel)));
}

void FileInputType::setFiles(FileList* files)
{
    if (!files)
        return;

    RefPtrWillBeRawPtr<HTMLInputElement> input(element());

    bool filesChanged = false;
    if (files->length() != m_fileList->length()) {
        filesChanged = true;
    } else {
        for (unsigned i = 0; i < files->length(); ++i) {
            if (!files->item(i)->hasSameSource(*m_fileList->item(i))) {
                filesChanged = true;
                break;
            }
        }
    }

    m_fileList = files;

    input->notifyFormStateChanged();
    input->setNeedsValidityCheck();

    if (input->layoutObject())
        input->layoutObject()->setShouldDoFullPaintInvalidation();

    if (filesChanged) {
        // This call may cause destruction of this instance.
        // input instance is safe since it is ref-counted.
        input->dispatchChangeEvent();
    }
    input->setChangedSinceLastFormControlChangeEvent(false);
}

void FileInputType::filesChosen(const Vector<FileChooserFileInfo>& files)
{
    setFiles(createFileList(files, element().fastHasAttribute(webkitdirectoryAttr)));
}

void FileInputType::receiveDropForDirectoryUpload(const Vector<String>& paths)
{
    if (ChromeClient* chromeClient = this->chromeClient()) {
        FileChooserSettings settings;
        HTMLInputElement& input = element();
        settings.allowsDirectoryUpload = true;
        settings.allowsMultipleFiles = true;
        settings.selectedFiles.append(paths[0]);
        settings.acceptMIMETypes = input.acceptMIMETypes();
        settings.acceptFileExtensions = input.acceptFileExtensions();
        chromeClient->enumerateChosenDirectory(newFileChooser(settings));
    }
}

bool FileInputType::receiveDroppedFiles(const DragData* dragData)
{
    Vector<String> paths;
    dragData->asFilePaths(paths);
    if (paths.isEmpty())
        return false;

    HTMLInputElement& input = element();
    if (input.fastHasAttribute(webkitdirectoryAttr)) {
        receiveDropForDirectoryUpload(paths);
        return true;
    }

    m_droppedFileSystemId = dragData->droppedFileSystemId();

    Vector<FileChooserFileInfo> files;
    for (unsigned i = 0; i < paths.size(); ++i)
        files.append(FileChooserFileInfo(paths[i]));

    if (input.fastHasAttribute(multipleAttr)) {
        filesChosen(files);
    } else {
        Vector<FileChooserFileInfo> firstFileOnly;
        firstFileOnly.append(files[0]);
        filesChosen(firstFileOnly);
    }
    return true;
}

String FileInputType::droppedFileSystemId()
{
    return m_droppedFileSystemId;
}

String FileInputType::defaultToolTip() const
{
    FileList* fileList = m_fileList.get();
    unsigned listSize = fileList->length();
    if (!listSize) {
        return locale().queryString(WebLocalizedString::FileButtonNoFileSelectedLabel);
    }

    StringBuilder names;
    for (size_t i = 0; i < listSize; ++i) {
        names.append(fileList->item(i)->name());
        if (i != listSize - 1)
            names.append('\n');
    }
    return names.toString();
}

} // namespace blink


text:
const flattenIds = levels => levels.reduce((arr, level) => {
  if (level instanceof Array) {
    if (arr.length) {
      const oldArray = arr.slice();
      arr = [];
      level.forEach(id => arr = arr.concat(oldArray.map(a => `${a}_${id}`)));
    }
    else {
      arr = level.slice();
    }
  }
  else if (arr.length) {
    arr = arr.map(a => `${a}_${level}`);
  }
  else {
    arr.push(level);
  }
  return arr;
}, []);

/**
    @desc On mouseenter event for all shapes in a Viz.
    @param {Object} *d* The data object being interacted with.
    @param {Number} *i* The index of the data object being interacted with.
    @private
*/
export default function(d, i) {

  if (this._shapeConfig.hoverOpacity !== 1) {

    const filterIds = flattenIds(this._ids(d, i));
    this.hover((h, x) => {
      const ids = flattenIds(this._ids(h, x));
      return filterIds.some(id => ids.includes(id));
    });

  }

}


text:
import { PropTypes } from 'react'
import { compose, branch, pure, setPropTypes, setDisplayName, withState, mapProps, withHandlers, renderComponent } from 'recompose'

import Card from './Card'
import EditingCard from './EditingCard'
import dndCardHOC from './dndCardHOC'

export default compose(
  setDisplayName('Card'),

  pure,

  withState('isEditing', 'setEditStatus', false),
  withState('inputText', 'setInputText', props => props.text),

  mapProps(({ setEditStatus, setInputText, ...rest }) => ({
    startEdit: () => setEditStatus(true),
    stopEdit: () => setEditStatus(false),
    setInputText: text => setInputText(text),
    ...rest
  })),

  withHandlers({
    onEdit: props => () => {
      props.startEdit()
      // focus input ?
    },
    onSave: props => () => {
      props.editCard({ cardID: props.cardID, text: props.inputText })
      props.stopEdit()
    },
    onCancel: props => () => {
      props.stopEdit()
      props.setInputText(props.text)
    },
    onDelete: props => () => {
      props.deleteCard(props.cardID)
    }
  }),

  branch(
    props => !props.isEditing && props.pending,
    comp => comp,
    comp => dndCardHOC(comp)
  ),

  branch(
    props => props.isEditing,
    renderComponent(EditingCard),
    comp => comp
  ),

  setPropTypes({
    cardID: PropTypes.string, // .isRequired,
    deleteCard: PropTypes.func, // .isRequired,
    index: PropTypes.number,
    startDrag: PropTypes.func,
    endDrag: PropTypes.func,
    text: PropTypes.string.isRequired,
    pending: PropTypes.bool.isRequired,
    setText: PropTypes.func, // .isRequired
    // Injected by mapProps
    startEdit: PropTypes.func, // .isRequired,
    stopEdit: PropTypes.func, // .isRequired,
    setInputText: PropTypes.func.isRequired,
    // Injected by withState
    isEditing: PropTypes.bool.isRequired,
    inputText: PropTypes.string, // .isRequired,
    // Injected by withHandlers
    onEdit: PropTypes.func, // .isRequired,
    onSave: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onDelete: PropTypes.func, // .isRequired,
  })

)(Card)


text:
      Toggle navigation

          {{ selectLocale.name | translate }}

               {{locale.name | translate }}

          Admin Menu

               Menu1

               Menu2

                {{currentUser.firstName || currentUser.profiles[0].profile.name.givenName}}

                  {{currentUser.firstName || currentUser.profiles[0].profile.name.givenName}}

          {{currentUser | json}}
          {{masterUser | json}}

              {{currentUser.firstName || currentUser.profiles[0].profile.name.givenName}}

              Account

              Profile

              Sign out


text:
package org.jgroups.tests;

import org.jgroups.Global;
import org.jgroups.util.CondVar;
import org.jgroups.util.Condition;
import org.jgroups.util.Util;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.concurrent.TimeUnit;

/**
 * @author Bela Ban
 * @since  3.6
 */
@Test(groups=Global.FUNCTIONAL,singleThreaded=true)
public class CondVarTest implements Condition {
    protected CondVar          cond;
    protected volatile boolean done=false; // our condition

    @BeforeMethod protected void setup() {
        cond=new CondVar();
        done=false;
    }

    public void testWaitFor() {
        done=true;
        cond.waitFor(this); // needs to return immediately
    }

    public void testInterruptedWaitFor() {
        Thread.currentThread().interrupt();
        done=true;
        cond.waitFor(this); // needs to return immediately
        assert Thread.currentThread().isInterrupted();
    }

    public void testWaitForWithSignal() {
        signal(1000, true, true);
        cond.waitFor(this);
        assert isMet();
    }

    public void testWaitForWithSignalAndInterrupt() {
        signal(2000, true, true);
        interrupt(Thread.currentThread(), 200);
        cond.waitFor(this);
        assert isMet();
    }

    public void testTimedWaitForWithNegativeTimeout() {
        boolean result=cond.waitFor(this, 0, TimeUnit.SECONDS);
        assert !done && !result;
        result=cond.waitFor(this, -1, TimeUnit.SECONDS);
        assert !done && !result;
    }

    public void testTimedWaitFor() {
        boolean result=cond.waitFor(this, 1, TimeUnit.SECONDS);
        assert !done && !result;
        interrupt(Thread.currentThread(), 100);
        result=cond.waitFor(this, 1, TimeUnit.SECONDS);
        assert !done && !result;
        signal(1000, true, true);
        result=cond.waitFor(this, 5, TimeUnit.SECONDS);
        assert done && result;

        done=false;
        interrupt(Thread.currentThread(), 1);
        signal(1000, true, false);
        result=cond.waitFor(this, 5, TimeUnit.SECONDS);
        assert result && done && Thread.currentThread().isInterrupted();
    }

    public boolean isMet() {
        return done;
    }

    protected void signal(final long after_ms, final boolean flag, boolean signal_all) {
        new Thread() {
            public void run() {
                Util.sleep(after_ms);
                done=flag;
                System.out.println("signalling cond-var");
                cond.signal(true);
            }
        }.start();
    }

    protected void interrupt(final Thread target_thread, final long after_ms) {
        new Thread() {
            public void run() {
                Util.sleep(after_ms);
                System.out.println("interrupting " + target_thread);
                target_thread.interrupt();
            }
        }.start();
    }
}


text:
<component name="libraryTable">
  <library name="com.android.support:support-core-utils-25.1.0">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/support-core-utils/25.1.0/jars/classes.jar!/" />
      <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/support-core-utils/25.1.0/res" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$USER_HOME$/Library/Android/sdk/extras/android/m2repository/com/android/support/support-core-utils/25.1.0/support-core-utils-25.1.0-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$USER_HOME$/Library/Android/sdk/extras/android/m2repository/com/android/support/support-core-utils/25.1.0/support-core-utils-25.1.0-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
<bill session="115" type="h" number="3894" updated="2017-10-05T14:30:10Z">
  <state datetime="2017-10-02">REFERRED</state>
  <status>
    <introduced datetime="2017-10-02"/>
  </status>
  <introduced datetime="2017-10-02"/>
  <titles>
    <title type="short" as="introduced">Tribal Heritage and Grizzly Bear Protection Act</title>
    <title type="short" as="introduced">Tribal Heritage and Grizzly Bear Protection Act</title>
    <title type="official" as="introduced">To protect grizzly bear populations, and for other purposes.</title>
    <title type="display">Tribal Heritage and Grizzly Bear Protection Act</title>
  </titles>
  <sponsor bioguide_id="G000551"/>
  <cosponsors/>
  <actions>
    <action datetime="2017-10-02">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-10-02" state="REFERRED">
      <text>Referred to the Committee on Natural Resources, and in addition to the Committee on Agriculture, for a period to be subsequently determined by the Speaker, in each case for consideration of such provisions as fall within the jurisdiction of the committee concerned.</text>
    </action>
    <action datetime="2017-10-02">
      <text>Referred to the Committee on Natural Resources, and in addition to the Committee on Agriculture, for a period to be subsequently determined by the Speaker, in each case for consideration of such provisions as fall within the jurisdiction of the committee concerned.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="HSAG" name="House Agriculture" activity="Referral"/>
    <committee subcommittee="" code="HSII" name="House Natural Resources" activity="Referral"/>
  </committees>
  <relatedbills/>
  <subjects>
    <term name="Animals"/>
  </subjects>
  <amendments/>
  <committee-reports/>
</bill>


text:
<?php

namespace NilPortugues\Test\Serializer\SupportClasses;

class ArrayAccessClass implements \ArrayAccess
{
    /**
     * @var array
     */
    private $container = array();

    /**
     *
     */
    public function __construct()
    {
        $this->container = ['one' => 1, 'two' => 2, 'three' => 3];
    }

    /**
     * @param mixed $offset
     * @param mixed $value
     */
    public function offsetSet($offset, $value)
    {
        if (\is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * @param mixed $offset
     *
     * @return bool
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * @param mixed $offset
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * @param mixed $offset
     *
     * @return mixed|null
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}


text:
<title>Zend Framework API Documentation</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><link rel="stylesheet" href="css/black-tie/jquery-ui-1.8.2.custom.css" type="text/css"></link><link rel="stylesheet" href="css/jquery.treeview.css" type="text/css"></link><link rel="stylesheet" href="css/theme.css" type="text/css"></link>

API Documentation

Service/DeveloperGarden/Request/VoiceButler/CallStatus.php

Global

                      Classes

\Zend_Service_DeveloperGarden_Request_VoiceButler_CallStatus

Zend Framework

LICENSE

This source file is subject to the new BSD license that is bundled
with this package in the file LICENSE.txt.
It is also available through the world-wide-web at this URL:
http://framework.zend.com/license/new-bsd
If you did not receive a copy of the license and are unable to
obtain it through the world-wide-web, please send an email
to license@zend.com so we can send you a copy immediately.

category

Zend

copyright

Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)

license

New BSD License

package

Zend_Service

subpackage

DeveloperGarden

version

$Id: CallStatus.php 23775 2011-03-01 17:25:24Z ralph $

\Zend_Service_DeveloperGarden_Request_VoiceButler_CallStatus
jump to top

Extends from

\Zend_Service_DeveloperGarden_Request_VoiceButler_VoiceButlerAbstract

author

Marco Kaiser

category

Zend

copyright

Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)

license

New BSD License

package

Zend_Service

subpackage

DeveloperGarden

Properties

integer
                 $keepAlive= 'null'

extend the keep alive for this call

Default valuenullDetails

Type

integer

Methods

__construct(
          integer $environment, string $sessionId, integer $keepAlive
              =
              null
          )

        :
          \Zend_Service_DeveloperGarden_Request_RequestAbstract

constructor give them the environment and the sessionId

Parameters

Name
Type
Description

$environment
integer

$sessionId
string

$keepAlive
integer

Returns

Type
Description

\Zend_Service_DeveloperGarden_Request_RequestAbstract

getEnvironment(

          )

        :
          integer

the current configured environment value

Inherited from:
                    \Zend_Service_DeveloperGarden_Request_RequestAbstract::getEnvironment()

Returns

Type
Description

integer

getKeepAlive(

          )

        :
          integer

Returns

Type
Description

integer

getSessionId(

          )

        :
          string

Returns

Type
Description

string

setEnvironment(
          integer $environment
          )

        :
          \Zend_Service_DeveloperGarden_Request_RequestAbstract

sets a new moduleId

Inherited from:
                    \Zend_Service_DeveloperGarden_Request_RequestAbstract::setEnvironment()

Parameters

Name
Type
Description

$environment
integer

Returns

Type
Description

\Zend_Service_DeveloperGarden_Request_RequestAbstract

setKeepAlive(
          integer $keepAlive
          )

        :
          \Zend_Service_DeveloperGarden_Request_VoiceButler_CallStatus

sets new keepAlive flag

Parameters

Name
Type
Description

$keepAlive
integer

Returns

Type
Description

\Zend_Service_DeveloperGarden_Request_VoiceButler_CallStatus

setSessionId(
          string $sessionId
          )

        :
          \Zend_Service_DeveloperGarden_Request_VoiceButler_CallStatus

sets new sessionId

Parameters

Name
Type
Description

$sessionId
string

Returns

Type
Description

\Zend_Service_DeveloperGarden_Request_VoiceButler_CallStatus

Documentation was generated by DocBlox 0.13.3.