text:
module Pacemaker
  # function related to the primitives configuration
  # main structure "primitives"
  module Primitives
    # get all 'primitive' sections from CIB
    # @return [Array<REXML::Element>] at /cib/configuration/resources/primitive
    def cib_section_primitives
      REXML::XPath.match cib, '//primitive'
    end

    # sets the meta attribute of a primitive
    # @param primitive [String] primitive's id
    # @param attribute [String] atttibute's name
    # @param value [String] attribute's value
    def set_primitive_meta_attribute(primitive, attribute, value)
      options = ['--quiet', '--resource', primitive]
      options += ['--set-parameter', attribute, '--meta', '--parameter-value', value]
      retry_block { crm_resource_safe options }
    end

    # disable this primitive
    # @param primitive [String] what primitive to disable
    def disable_primitive(primitive)
      set_primitive_meta_attribute primitive, 'target-role', 'Stopped'
    end

    alias :stop_primitive :disable_primitive

    # enable this primitive
    # @param primitive [String] what primitive to enable
    def enable_primitive(primitive)
      set_primitive_meta_attribute primitive, 'target-role', 'Started'
    end

    alias :start_primitive :enable_primitive

    # manage this primitive
    # @param primitive [String] what primitive to manage
    def manage_primitive(primitive)
      set_primitive_meta_attribute primitive, 'is-managed', 'true'
    end

    # unmanage this primitive
    # @param primitive [String] what primitive to unmanage
    def unmanage_primitive(primitive)
      set_primitive_meta_attribute primitive, 'is-managed', 'false'
    end

    # ban this primitive
    # @param primitive [String] what primitive to ban
    # @param node [String] on which node this primitive should be banned
    def ban_primitive(primitive, node)
      options = ['--quiet', '--resource', primitive, '--node', node]
      options += ['--ban']
      retry_block { crm_resource_safe options }
    end

    # unban this primitive
    # @param primitive [String] what primitive to unban
    # @param node [String] on which node this primitive should be unbanned
    def unban_primitive(primitive, node)
      options = ['--quiet', '--resource', primitive, '--node', node]
      options += ['--clear']
      retry_block { crm_resource_safe options }
    end

    alias :clear_primitive :unban_primitive

    # move this primitive
    # @param primitive [String] what primitive to un-move
    # @param node [String] to which node the primitive should be moved
    def move_primitive(primitive, node)
      options = ['--quiet', '--resource', primitive, '--node', node]
      options += ['--move']
      retry_block { crm_resource_safe options }
    end

    # un-move this primitive
    # @param primitive [String] what primitive to un-move
    # @param node [String] from which node the primitive should be un-moved
    def unmove_primitive(primitive, node)
      options = ['--quiet', '--resource', primitive, '--node', node]
      options += ['--un-move']
      retry_block { crm_resource_safe options }
    end

    # cleanup this primitive
    # @param primitive [String] what primitive to cleanup
    # @param node [String] on which node to cleanup (optional)
    # cleanups on every node if node is not given
    def cleanup_primitive(primitive, node = nil)
      options = ['--quiet', '--resource', primitive]
      options += ['--node', node] if node
      options += ['--cleanup']
      retry_block { crm_resource_safe options }
    end

    ##############################################################################

    # get primitives configuration structure with primitives and their attributes
    # @return [Hash<String => Hash>]
    def primitives
      return @primitives_structure if @primitives_structure
      @primitives_structure = {}
      cib_section_primitives.each do |primitive|
        id = primitive.attributes['id']
        next unless id
        primitive_structure = attributes_to_hash primitive
        primitive_structure.store 'name', id

        if primitive.parent.name and primitive.parent.attributes['id']
          complex_structure = {
              'id' => primitive.parent.attributes['id'],
              'type' => primitive.parent.name
          }

          complex_meta_attributes = primitive.parent.elements['meta_attributes']
          if complex_meta_attributes
            complex_meta_attributes_structure = children_elements_to_hash complex_meta_attributes, 'name', 'nvpair'
            complex_meta_attributes_structure = munge_meta_attributes complex_meta_attributes_structure
            complex_structure.store 'meta_attributes', complex_meta_attributes_structure
          end

          primitive_structure.store 'name', complex_structure['id']
          primitive_structure.store 'complex', complex_structure
        end

        instance_attributes = primitive.elements['instance_attributes']
        if instance_attributes
          instance_attributes_structure = children_elements_to_hash instance_attributes, 'name', 'nvpair'
          primitive_structure.store 'instance_attributes', instance_attributes_structure
        end

        meta_attributes = primitive.elements['meta_attributes']
        if meta_attributes
          meta_attributes_structure = children_elements_to_hash meta_attributes, 'name', 'nvpair'
          meta_attributes_structure = munge_meta_attributes meta_attributes_structure
          primitive_structure.store 'meta_attributes', meta_attributes_structure
        end

        operations = primitive.elements['operations']
        if operations
          operations_structure = parse_operations operations
          primitive_structure.store 'operations', operations_structure
        end

        @primitives_structure.store id, primitive_structure
      end
      @primitives_structure
    end

    # parse the operations structure of a primitive
    # @param operations_element [REXML::Element]
    # @return [Hash]
    def parse_operations(operations_element)
      return unless operations_element.is_a? REXML::Element
      operations = {}
      ops = operations_element.get_elements 'op'
      return operations unless ops.any?
      ops.each do |op|
        op_structure = attributes_to_hash op
        id = op_structure['id']
        next unless id
        instance_attributes = op.elements['instance_attributes']
        if instance_attributes
          instance_attributes_structure = children_elements_to_hash instance_attributes, 'name', 'nvpair'
          if instance_attributes_structure.key? 'OCF_CHECK_LEVEL'
            value = instance_attributes_structure.fetch('OCF_CHECK_LEVEL', {}).fetch('value', nil)
            op_structure['OCF_CHECK_LEVEL'] = value if value
          end
        end
        operations.store id, op_structure
      end
      operations
    end

    # check if primitive exists in the configuration
    # @param primitive primitive id or name
    def primitive_exists?(primitive)
      primitives.key? primitive
    end

    # return primitive class
    # @param primitive [String] primitive id
    # @return [String] primitive class
    def primitive_class(primitive)
      return unless primitive_exists? primitive
      primitives[primitive]['class']
    end

    # return primitive type
    # @param primitive [String] primitive id
    # @return [String] primitive type
    def primitive_type(primitive)
      return unless primitive_exists? primitive
      primitives[primitive]['type']
    end

    # return primitive complex type
    # or nil is the primitive is simple
    # @param primitive [String] primitive id
    # @return [Symbol] primitive complex type
    def primitive_complex_type(primitive)
      return unless primitive_is_complex? primitive
      primitives[primitive]['complex']['type'].to_sym
    end

    # return the full name of the complex primitive
    # or just a name for a simple primitive
    # @return [String] primitive type
    def primitive_full_name(primitive)
      return unless primitive_exists? primitive
      primitives[primitive]['name']
    end

    # check if primitive is clone or multistate
    # @param primitive [String] primitive id
    # @return [TrueClass,FalseClass]
    def primitive_is_complex?(primitive)
      return unless primitive_exists? primitive
      primitives[primitive].key? 'complex'
    end

    # check if primitive is clone
    # @param primitive [String] primitive id
    # @return [TrueClass,FalseClass]
    def primitive_is_clone?(primitive)
      is_complex = primitive_is_complex? primitive
      return is_complex unless is_complex
      primitives[primitive]['complex']['type'] == 'clone'
    end

    # check if primitive is multistate
    # @param primitive [String] primitive id
    # @return [TrueClass,FalseClass]
    def primitive_is_multistate?(primitive)
      is_complex = primitive_is_complex? primitive
      return is_complex unless is_complex
      primitives[primitive]['complex']['type'] == 'master'
    end

    # determine if primitive is managed
    # @param primitive [String] primitive id
    # @return [TrueClass,FalseClass]
    def primitive_is_managed?(primitive)
      return unless primitive_exists? primitive
      is_managed = primitives.fetch(primitive).fetch('meta_attributes', {}).fetch('is-managed', {}).fetch('value', 'true')
      is_managed == 'true'
    end

    # determine if primitive has target-state started
    # @param primitive [String] primitive id
    # @return [TrueClass,FalseClass]
    def primitive_is_started?(primitive)
      return unless primitive_exists? primitive
      target_role = primitives.fetch(primitive).fetch('meta_attributes', {}).fetch('target-role', {}).fetch('value', 'Started')
      target_role == 'Started'
    end

    # generate a new XML element object
    # and fill it with the primitive data from
    # the provided primitive structure
    # @param data [Hash] primitive_structure
    # @return [REXML::Element]
    def xml_primitive(data)
      return unless data and data.is_a? Hash
      primitive_skip_attributes = %w(name parent instance_attributes operations meta_attributes utilization)
      primitive_element = xml_element 'primitive', data, primitive_skip_attributes

      # instance attributes
      if data['instance_attributes'].respond_to? :each and data['instance_attributes'].any?
        instance_attributes_document = xml_document 'instance_attributes', primitive_element
        instance_attributes_document.add_attribute 'id', data['id'] + '-instance_attributes'
        sort_data(data['instance_attributes']).each do |instance_attribute|
          instance_attribute_element = xml_element 'nvpair', instance_attribute
          instance_attributes_document.add_element instance_attribute_element if instance_attribute_element
        end
      end

      # meta attributes
      if data['meta_attributes'].respond_to? :each and data['meta_attributes'].any?
        complex_meta_attributes_document = xml_document 'meta_attributes', primitive_element
        complex_meta_attributes_document.add_attribute 'id', data['id'] + '-meta_attributes'
        sort_data(data['meta_attributes']).each do |meta_attribute|
          meta_attribute_element = xml_element 'nvpair', meta_attribute
          complex_meta_attributes_document.add_element meta_attribute_element if meta_attribute_element
        end
      end

      # operations
      if data['operations'].respond_to? :each and data['operations'].any?
        operations_document = xml_document 'operations', primitive_element
        sort_data(data['operations']).each do |operation|
          operation_element = xml_element 'op', operation, %w(OCF_CHECK_LEVEL)
          if operation.key? 'OCF_CHECK_LEVEL'
            instance_attributes_document = xml_document 'instance_attributes', operation_element
            instance_attributes_id = operation['id'] + '-instance_attributes'
            instance_attributes_document.add_attribute 'id', instance_attributes_id
            ocf_check_level_id = instance_attributes_id + '-OCF_CHECK_LEVEL'
            ocf_check_level_structure = {
              'id' => ocf_check_level_id,
              'name' => 'OCF_CHECK_LEVEL',
              'value' => operation['OCF_CHECK_LEVEL'],
            }
            ocf_check_level_element = xml_element 'nvpair', ocf_check_level_structure
            instance_attributes_document.add_element ocf_check_level_element if ocf_check_level_element
          end
          operations_document.add_element operation_element if operation_element
        end
      end

      # complex structure
      if data['complex'].is_a? Hash and data['complex']['type']
        skip_complex_attributes = 'type'
        supported_complex_types = %w(clone master meta_attributes)
        complex_tag_name = data['complex']['type']
        return unless supported_complex_types.include? complex_tag_name
        complex_element = xml_element complex_tag_name, data['complex'], skip_complex_attributes

        # complex meta attributes
        if data['complex']['meta_attributes'].respond_to? :each and data['complex']['meta_attributes'].any?
          complex_meta_attributes_document = xml_document 'meta_attributes', complex_element
          complex_meta_attributes_document.add_attribute 'id', data['complex']['id'] + '-meta_attributes'
          sort_data(data['complex']['meta_attributes']).each do |meta_attribute|
            complex_meta_attribute_element = xml_element 'nvpair', meta_attribute
            complex_meta_attributes_document.add_element complex_meta_attribute_element if complex_meta_attribute_element
          end
        end

        complex_element.add_element primitive_element
        return complex_element
      end

      primitive_element
    end
  end
end


text:
package com.xinqihd.sns.gameserver.entity.rank;

import static org.junit.Assert.*;

import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.xinqihd.sns.gameserver.entity.user.BasicUser;

public class RankUserTest {

	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testCompareTo() {
		Random random = new Random();
		RankUser[] rankUsers = new RankUser[5];
		Set<RankUser> sortUsers = new TreeSet<RankUser>();
		for ( int i=0; i<rankUsers.length; i++ ) {
			rankUsers[i] = new RankUser();
			rankUsers[i].setRank(random.nextInt(10));
			rankUsers[i].setScore(random.nextInt(10000));
			rankUsers[i].setRankChange(random.nextInt(10));
			rankUsers[i].setBasicUser(new BasicUser());

			sortUsers.add(rankUsers[i]);
		}

		for ( RankUser r : sortUsers ) {
			System.out.println(r);
		}
		assertTrue("Not yet implemented", true);
	}

}

redpajama_set_name: RedPajamaGithub


text:
"use strict"

const process = require(`process`)

const fs = require(`fs`)
const createVerge3ChrConverter = require(`../converter/createVerge3ChrConverter`)
const asset = require(`../asset`)

const chrFilename = process.argv[2]
const chrData = asset.fromDisk(chrFilename, asset.v3chr)
const chrConverter = createVerge3ChrConverter({
  bitsPerPixel: chrData.bitsPerPixel,
  frameWidth: chrData.frameWidth,
  frameHeight: chrData.frameHeight,
  frameCount: chrData.frameCount,
  frames: chrData.frames.decompressed,
})

const png = chrConverter.convertToPng()
const targetFilename = chrFilename + `.png`

png.pack().pipe(fs.createWriteStream(targetFilename))

console.log(`converted`, chrFilename, `to`, targetFilename)


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

<title>M-Index</title>
<meta name="date" content="2016-04-27">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C D E F G I L M P S T U

M

main(String[]) - Static method in class limmen.ChinookRestApplication

Main method, entry point of the application.

MainController - Class in limmen.controllers

RestController for the resource pointed by the url: /*

MainController() - Constructor for class limmen.controllers.MainController

MediaTypeController - Class in limmen.controllers

RestController for the resource pointed by the url: /resources/mediatypes*

MediaTypeController(MediaTypeService) - Constructor for class limmen.controllers.MediaTypeController

Method to be injected by the Spring container.

MediaTypeEntity - Class in limmen.integration.entities

POJO that represents a MediaType entity from the chinook database

MediaTypeEntity(int, String) - Constructor for class limmen.integration.entities.MediaTypeEntity

Class constructor.

MediaTypeEntity() - Constructor for class limmen.integration.entities.MediaTypeEntity

MediaTypeFilter - Class in limmen.business.services.filters

Class for implementing filtering and sorting functionality for the MediaTypeEntity-Resource.

MediaTypeFilter() - Constructor for class limmen.business.services.filters.MediaTypeFilter

Default constructor

MediaTypeFilterTest - Class in limmen.business.services.filters

MediaTypeFilterTest() - Constructor for class limmen.business.services.filters.MediaTypeFilterTest

MediaTypeITCase - Class in limmen.integration

Integration test-suite for the mediatype REST-resource

MediaTypeITCase() - Constructor for class limmen.integration.MediaTypeITCase

MediaTypeRepository - Class in limmen.integration.repositories

CRUD-repository for the "MediaType" table in the chinook database.

MediaTypeRepository() - Constructor for class limmen.integration.repositories.MediaTypeRepository

MediaTypeRepresentation - Class in limmen.business.representations.entity_representation

JSON-Representation of a MediaType entity.

MediaTypeRepresentation(MediaTypeEntity) - Constructor for class limmen.business.representations.entity_representation.MediaTypeRepresentation

Class constructor.

MediaTypesArrayRepresentation - Class in limmen.business.representations.array_representations

JSON-Representation of a Array of mediatypes.

MediaTypesArrayRepresentation(List<MediaTypeRepresentation>) - Constructor for class limmen.business.representations.array_representations.MediaTypesArrayRepresentation

Class constructor.

MediaTypeService - Interface in limmen.business.services

Interface for a service that provides CRUD services for mediatype-data.

MediaTypeServiceImpl - Class in limmen.business.services.implementations

Implementation of the MediaTypeService interface, uses a repository for database interaction.

MediaTypeServiceImpl(MediaTypeRepository) - Constructor for class limmen.business.services.implementations.MediaTypeServiceImpl

MediaTypeServiceImplTest - Class in limmen.business.services.implementations

Unit test-suite for the mediatype service implementation

MediaTypeServiceImplTest() - Constructor for class limmen.business.services.implementations.MediaTypeServiceImplTest

A C D E F G I L M P S T U

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
pyspider [![Build Status][Build Status]][Travis CI] [![Coverage Status][Coverage Status]][Coverage] [![Try][Try]][Demo]
========

A Powerful Spider(Web Crawler) System in Python. **[TRY IT NOW!][Demo]**

- Write script in Python
- Powerful WebUI with script editor, task monitor, project manager and result viewer
- [MySQL](https://www.mysql.com/), [MongoDB](https://www.mongodb.org/), [Redis](http://redis.io/), [SQLite](https://www.sqlite.org/), [PostgreSQL](http://www.postgresql.org/) with [SQLAlchemy](http://www.sqlalchemy.org/) as database backend
- [RabbitMQ](http://www.rabbitmq.com/), [Beanstalk](http://kr.github.com/beanstalkd/), [Redis](http://redis.io/) and [Kombu](http://kombu.readthedocs.org/) as message queue
- Task priority, retry, periodical, recrawl by age, ...
- Distributed architecture, Crawl Javascript pages, Python 2&3, ...

Sample Code
-----------

```python
from pyspider.libs.base_handler import *

class Handler(BaseHandler):
    crawl_config = {
    }

    @every(minutes=24 * 60)
    def on_start(self):
        self.crawl('http://scrapy.org/', callback=self.index_page)

    @config(age=10 * 24 * 60 * 60)
    def index_page(self, response):
        for each in response.doc('a[href^="http"]').items():
            self.crawl(each.attr.href, callback=self.detail_page)

    def detail_page(self, response):
        return {
            "url": response.url,
            "title": response.doc('title').text(),
        }
```

[![Demo][Demo Img]][Demo]

Installation
------------

* `pip install pyspider`
* run command `pyspider`, visit [http://localhost:5000/](http://localhost:5000/)

Contribute
----------

* Use It
* Open [Issue], send PR
* [User Group]

License
-------
Licensed under the Apache License, Version 2.0

[Build Status]:         https://img.shields.io/travis/binux/pyspider/master.svg?style=flat
[Travis CI]:            https://travis-ci.org/binux/pyspider
[Coverage Status]:      https://img.shields.io/coveralls/binux/pyspider.svg?branch=master&style=flat
[Coverage]:             https://coveralls.io/r/binux/pyspider
[Try]:                  https://img.shields.io/badge/try-pyspider-blue.svg?style=flat
[Demo]:                 http://demo.pyspider.org/
[Demo Img]:             imgs/demo.png
[Issue]:                https://github.com/binux/pyspider/issues
[User Group]:           https://groups.google.com/group/pyspider-users


text:
class VersionsController < ApplicationController
  menu_item :roadmap
  model_object Version
  before_filter :find_model_object, :except => [:index, :new, :create, :close_completed]
  before_filter :find_project_from_association, :except => [:index, :new, :create, :close_completed]
  before_filter :find_project, :only => [:index, :new, :create, :close_completed]
  before_filter :authorize

  def index
    @types = @project.types.find(:all, :order => 'position')
    retrieve_selected_type_ids(@types, @types.select {|t| t.is_in_roadmap?})
    @with_subprojects = params[:with_subprojects].nil? ? Setting.display_subprojects_work_packages? : (params[:with_subprojects].to_i == 1)
    project_ids = @with_subprojects ? @project.self_and_descendants.collect(&:id) : [@project.id]

    @versions = @project.shared_versions || []
    @versions += @project.rolled_up_versions.visible if @with_subprojects
    @versions = @versions.uniq.sort
    @versions.reject! {|version| version.closed? || version.completed? } unless params[:completed]

    @issues_by_version = {}
    unless @selected_type_ids.empty?
      @versions.each do |version|
        issues = version.fixed_issues.visible.find(:all,
                                                   :include => [:project, :status, :type, :priority],
                                                   :conditions => {:type_id => @selected_type_ids, :project_id => project_ids},
                                                   :order => "#{Project.table_name}.lft, #{Type.table_name}.position, #{WorkPackage.table_name}.id")
        @issues_by_version[version] = issues
      end
    end
    @versions.reject! {|version| !project_ids.include?(version.project_id) && @issues_by_version[version].blank?}
  end

  def show
    @issues = @version.fixed_issues.visible.find(:all,
      :include => [:status, :type, :priority],
      :order => "#{Type.table_name}.position, #{WorkPackage.table_name}.id")
  end

  def new
    @version = @project.versions.build
    if params[:version]
      attributes = params[:version].dup
      attributes.delete('sharing') unless attributes.nil? || @version.allowed_sharings.include?(attributes['sharing'])
      @version.safe_attributes = attributes
    end
  end

  def create
    # TODO: refactor with code above in #new
    @version = @project.versions.build
    if params[:version]
      attributes = params[:version].dup
      attributes.delete('sharing') unless attributes.nil? || @version.allowed_sharings.include?(attributes['sharing'])
      @version.safe_attributes = attributes
    end

    if request.post?
      if @version.save
        respond_to do |format|
          format.html do
            flash[:notice] = l(:notice_successful_create)
            redirect_to :controller => '/projects', :action => 'settings', :tab => 'versions', :id => @project
          end
          format.js do
            # IE doesn't support the replace_html rjs method for select box options
            render(:update) {|page| page.replace "issue_fixed_version_id",
              content_tag('select', '<option></option>'.html_safe + version_options_for_select(@project.shared_versions.open, @version).html_safe, :id => 'issue_fixed_version_id', :name => 'issue[fixed_version_id]')
            }
          end
        end
      else
        respond_to do |format|
          format.html { render :action => 'new' }
          format.js do
            render(:update) {|page| page.alert(@version.errors.full_messages.join('\n')) }
          end
        end
      end
    end
  end

  def edit
  end

  def update
    if request.put? && params[:version]
      attributes = params[:version].dup
      attributes.delete('sharing') unless @version.allowed_sharings.include?(attributes['sharing'])
      @version.safe_attributes = attributes
      if @version.save
        flash[:notice] = l(:notice_successful_update)
        redirect_to :controller => '/projects', :action => 'settings', :tab => 'versions', :id => @project
      else
        respond_to do |format|
          format.html { render :action => 'edit' }
        end
      end
    end
  end

  def close_completed
    if request.put?
      @project.close_completed_versions
    end
    redirect_to :controller => '/projects', :action => 'settings', :tab => 'versions', :id => @project
  end

  def destroy
    if @version.fixed_issues.empty?
      @version.destroy
      redirect_to :controller => '/projects', :action => 'settings', :tab => 'versions', :id => @project
    else
      flash[:error] = l(:notice_unable_delete_version)
      redirect_to :controller => '/projects', :action => 'settings', :tab => 'versions', :id => @project
    end
  end

  def status_by
    respond_to do |format|
      format.html { render :action => 'show' }
      format.js { render(:update) {|page| page.replace_html 'status_by', render_status_by(@version, params[:status_by])} }
    end
  end

private
  def find_project
    @project = Project.find(params[:project_id])
  rescue ActiveRecord::RecordNotFound
    render_404
  end

  def retrieve_selected_type_ids(selectable_types, default_types=nil)
    if ids = params[:type_ids]
      @selected_type_ids = (ids.is_a? Array) ? ids.collect { |id| id.to_i.to_s } : ids.split('/').collect { |id| id.to_i.to_s }
    else
      @selected_type_ids = (default_types || selectable_types).collect {|t| t.id.to_s }
    end
  end

end


text:
<?xml version="1.0"?>
<entry type="method" name="siblings" return="jQuery">
  <title>.siblings()</title>
  <signature>
    <added>1.0</added>
    <argument name="selector" optional="true" type="Selector">
      <desc>A string containing a selector expression to match elements against.</desc>
    </argument>
  </signature>
  <desc>Get the siblings of each element in the set of matched elements, optionally filtered by a selector.</desc>
  <longdesc>

Given a jQuery object that represents a set of DOM elements, the .siblings() method allows us to search through the siblings of these elements in the DOM tree and construct a new jQuery object from the matching elements.

The method optionally accepts a selector expression of the same type that we can pass to the $() function. If the selector is supplied, the elements will be filtered by testing whether they match it.

Consider a page with a simple list on it:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li class="third-item">list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

If we begin at the third item, we can find its siblings:

$( "li.third-item" ).siblings().css( "background-color", "red" );

The result of this call is a red background behind items 1, 2, 4, and 5. Since we do not supply a selector expression, all of the siblings are part of the object. If we had supplied one, only the matching items among these four would be included.

The original element is not included among the siblings, which is important to remember when we wish to find all elements at a particular level of the DOM tree. However, if the original collection contains more than one element, they might be mutual siblings and will both be found. If you need an exclusive list of siblings, use $collection.siblings().not($collection).

  </longdesc>
  <example>
    <desc>Find the unique siblings of all yellow li elements in the 3 lists (including other yellow li elements if appropriate).</desc>
    <![CDATA[
var len = $( ".hilite" ).siblings()
  .css( "color", "red" )
  .length;
$( "b" ).text( len );
]]>
    <css><![CDATA[
  ul {
    float: left;
    margin: 5px;
    font-size: 16px;
    font-weight: bold;
  }
  p {
    color: blue;
    margin: 10px 20px;
    font-size: 16px;
    padding: 5px;
    font-weight: bolder;
  }
  .hilite {
    background: yellow;
  }
]]></css>
    <![CDATA[

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

Eleven

Unique siblings:

]]>
  </example>
  <example>
    <desc>Find all siblings with a class "selected" of each div.</desc>
    <![CDATA[
$( "p" ).siblings( ".selected" ).css( "background", "yellow" );
]]>
    <![CDATA[

Hello

Hello Again

And Again

]]>
  </example>
  <category slug="traversing/tree-traversal"/>
  <category slug="version/1.0"/>
</entry>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cliente.controlador;

import comun.Rsa;
import java.math.BigInteger;

/**
 * Patron de diseño Façade. Intermediario entre la vista y el controlador para separar el codigo entre ambos.
 * @author Mario Codes Sánchez
 * @since 06/02/2017
 */
public class Facade {
    private static Red red = null; //Propiedades de la conexion para utilizar de aqui en adelante.

    /**
     * Comprueba si se puede establecer conexion mediante la IP y Puertos pasados como parametros. Instancia esta conexion para utilizarla de aqui en adelante.
     * @param ip IP del server a Conectarse.
     * @param puerto Puerto del server por donde entra la conexion.
     * @return Estado de la conexion.
     */
    public static boolean abrirConexionCliente(String ip, int puerto) {
        red = new Red(ip, puerto);
        Runtime.getRuntime().addShutdownHook(new NetShutdownHook());
        return red.checkConexion();
    }

    /**
     * Obtencion de la clave publica del server y envio de la privada.
     * @param clavePublica Clase estatica de donde obtengo la clave publica propia.
     * @return BigInteger[] que conforma la clave publica propia del server.
     */
    public static BigInteger[] intercambioClaves(Rsa rsa, BigInteger[] clavePublica) {
        return red.intercambioClaves(rsa, clavePublica);
    }

    public static String getSimetrica(Rsa rsa) {
        return red.getSimetrica(rsa);
    }

    /**
     * Envio de un Fichero desde el Cliente al Server.
     * @param ip IP a la que nos conectamos.
     * @param puerto Puerto por el cual nos conectamos.
     * @param rutaServer Ruta del server donde queremos el fichero.
     * @param rutaLocal Ruta local del cliente donde se encuentra el fichero.
     * @param nombreFich Nombre del fichero a copiar.
     */
    public static void envioFicheroClienteServer(String clave, Rsa rsa, String ip, int puerto, String rutaServer, String rutaLocal, String nombreFich) {
        red.envioFicheroClienteServer(clave, rsa, rutaServer, rutaLocal, nombreFich);
    }

    /**
     * Recibo de un fichero o envio desde el Server al Cliente.
     * @param ip IP a la que nos conectamos.
     * @param puerto Puerto por el cual nos conectamos.
     * @param rutaServer Ruta del Server donde se encuentra el fichero.
     * @param rutaLocal Ruta local del Cliente donde queremos el fichero.
     * @param nombreFich Nombre del fichero a copiar.
     */
    public static void envioFicheroServerCliente(String clave, Rsa rsa, String ip, int puerto, String rutaServer, String rutaLocal, String nombreFich) {
        red.reciboFicheroServerCliente(clave, rsa, rutaServer, rutaLocal, nombreFich);
    }

    /**
     * Cerrado de las conexiones abiertas en Red.
     */
    public static void cerradoConexiones() {
        red.cerrarConexiones();
        System.out.println("Cerrado de Conexiones mediante 'Shutdown Hook'.");
    }
}


text:
define(["require", "exports", '../../../unitTesting/grid/base', './pagination'], function (require, exports, base_1, pagination_1) {
    "use strict";
    describe('Pagination component', function () {
        var h;
        var getComponent = function (codeBased, domBased) {
            var gridOptions = h.getGridOptions({ pagination: codeBased }, domBased + "<columns><column field=\"Name\"></column></columns>");
            return new pagination_1.PaginationComponent(h.dataSource, h.aureliaUtils, h.gridInternals, gridOptions);
        };
        beforeEach(function () {
            h = new base_1.GridTestHelpers();
            h.beforeEach();
        });
        describe('should be able to create options', function () {
            it('from DOM based settings', function () {
                var pagination = getComponent({}, "<pagination size=\"10\" all.bind=\"[5,10,15]\" range=\"50\"></pagination>");
                var options = pagination.createOptions();
                expect(options.size).toEqual(10);
                expect(options.all).toEqual([5, 10, 15]);
                expect(options.range).toEqual(50);
            });
            it('from code based settings', function () {
                var pagination = getComponent({ size: 100, all: [100, 200, 300], range: 50 }, "<pagination size=\"10\" all.bind=\"[5,10,15]\"></pagination>");
                var options = pagination.createOptions();
                expect(options.size).toEqual(100);
                expect(options.all).toEqual([100, 200, 300]);
                expect(options.range).toEqual(50);
            });
            it('when configuration is not available', function () {
                var pagination = getComponent(false, "");
                var options = pagination.createOptions();
                expect(options).toBeFalsy();
            });
            it('with default settings', function () {
                var pagination = getComponent(true, "");
                var options = pagination.createOptions();
                expect(options).toEqual(pagination.defaultOptions);
            });
        });
        describe('changePage method should', function () {
            it('update view modela and refresh the grid', function () {
                var pagination = getComponent({}, "");
                pagination.changePage(25);
                expect(pagination.selected).toEqual(25);
                expect(h.gridInternals.refresh.calledOnce).toBe(true);
            });
            it('do nothing if page has not changed', function () {
                var pagination = getComponent({}, "");
                pagination.changePage(1);
                expect(pagination.selected).toEqual(1);
                expect(h.gridInternals.refresh.calledOnce).toBe(false);
            });
        });
        it('selectFirst method should select first page', function () {
            var pagination = getComponent({}, "");
            pagination.selected = 2;
            pagination.selectFirst();
            expect(pagination.selected).toEqual(1);
            expect(h.gridInternals.refresh.calledOnce).toBe(true);
        });
        it('selectLast method should select last page', function () {
            var pagination = getComponent({}, "");
            pagination.lastPage = 5;
            pagination.selectLast();
            expect(pagination.selected).toEqual(5);
            expect(h.gridInternals.refresh.calledOnce).toBe(true);
        });
        describe('selectPrev method should select previous page', function () {
            it('', function () {
                var pagination = getComponent({}, "");
                pagination.selected = 5;
                pagination.selectPrev();
                expect(pagination.selected).toEqual(4);
                expect(h.gridInternals.refresh.calledOnce).toBe(true);
            });
            it('but only if not first selected', function () {
                var pagination = getComponent({}, "");
                pagination.selected = 1;
                pagination.selectPrev();
                expect(pagination.selected).toEqual(1);
                expect(h.gridInternals.refresh.calledOnce).toBe(false);
            });
        });
        describe('selectNext method should select next page', function () {
            it('', function () {
                var pagination = getComponent({}, "");
                pagination.lastPage = 10;
                pagination.selected = 5;
                pagination.selectNext();
                expect(pagination.selected).toEqual(6);
                expect(h.gridInternals.refresh.calledOnce).toBe(true);
            });
            it('but only if not last selected', function () {
                var pagination = getComponent({}, "");
                pagination.lastPage = 5;
                pagination.selected = 5;
                pagination.selectNext();
                expect(pagination.selected).toEqual(5);
                expect(h.gridInternals.refresh.calledOnce).toBe(false);
            });
        });
        describe('should listen on size change', function () {
            it('and react if changed', function () {
                var pagination = getComponent({ size: 100, all: [100, 200, 300] }, "");
                pagination.tryEnable();
                pagination.selected = 2;
                h.aureliaUtils.observe.emit(pagination.options, 'size', 25, pagination.options.size);
                expect(pagination.selected).toEqual(1);
                expect(h.gridInternals.refresh.calledOnce).toBe(true);
            });
            it('and do not react if not changed', function () {
                var pagination = getComponent({ size: 100, all: [100, 200, 300] }, "");
                pagination.tryEnable();
                pagination.selected = 2;
                h.aureliaUtils.observe.emit(pagination.options, 'size', pagination.options.size, pagination.options.size);
                expect(pagination.selected).toEqual(2);
                expect(h.gridInternals.refresh.calledOnce).toBe(false);
            });
        });
        it('should attach appropriate data on data source read', function () {
            var pagination = getComponent({ size: 10 }, "");
            pagination.tryEnable();
            pagination.selected = 2;
            var params = {};
            h.dataSource.subscribe.emit('DataRead', params);
            expect(params.page).toEqual(2);
            expect(params.pageSize).toBe(10);
        });
        it('should unregister correctly', function () {
            var pagination = getComponent({}, "");
            pagination.tryEnable();
            pagination.stop();
            expect(h.dataSource.subscribe.subscribers.length).toBe(0);
            expect(h.aureliaUtils.observe.observers.length).toBe(0);
        });
        describe('should update buttons on data received', function () {
            var test = function (options, result) {
                var pagination = getComponent(options, "");
                pagination.tryEnable();
                pagination.selected = result.selected;
                h.dataSource.subscribe.emit('DataReceived', { result: {
                        total: result.total
                    } });
                expect(pagination.selected).toEqual(result.selected);
                expect(pagination.items).toEqual(result.items);
                expect(pagination.buttons).toEqual(result.buttons);
                expect(pagination.lastPage).toEqual(result.lastPage);
            };
            it('with selected first page', function () {
                test({ size: 10, range: 3 }, {
                    selected: 1,
                    items: [1, 2, 3, 4],
                    total: 31,
                    lastPage: 4,
                    buttons: {
                        prev: false,
                        next: true,
                        leftSideOutOfRange: false,
                        rightSideOutOfRange: false
                    }
                });
                test({ size: 10, range: 3 }, {
                    selected: 1,
                    items: [1, 2, 3, 4],
                    total: 41,
                    lastPage: 5,
                    buttons: {
                        prev: false,
                        next: true,
                        leftSideOutOfRange: false,
                        rightSideOutOfRange: true
                    }
                });
            });
            it('with selected last page', function () {
                test({ size: 10, range: 3 }, {
                    selected: 4,
                    items: [1, 2, 3, 4],
                    total: 31,
                    lastPage: 4,
                    buttons: {
                        prev: true,
                        next: false,
                        leftSideOutOfRange: false,
                        rightSideOutOfRange: false
                    }
                });
                test({ size: 10, range: 3 }, {
                    selected: 5,
                    items: [2, 3, 4, 5],
                    total: 41,
                    lastPage: 5,
                    buttons: {
                        prev: true,
                        next: false,
                        leftSideOutOfRange: true,
                        rightSideOutOfRange: false
                    }
                });
            });
            it('with selected page at the middle', function () {
                test({ size: 10, range: 3 }, {
                    selected: 4,
                    items: [1, 2, 3, 4, 5, 6, 7],
                    total: 61,
                    lastPage: 7,
                    buttons: {
                        prev: true,
                        next: true,
                        leftSideOutOfRange: false,
                        rightSideOutOfRange: false
                    }
                });
                test({ size: 10, range: 2 }, {
                    selected: 4,
                    items: [2, 3, 4, 5, 6],
                    total: 61,
                    lastPage: 7,
                    buttons: {
                        prev: true,
                        next: true,
                        leftSideOutOfRange: true,
                        rightSideOutOfRange: true
                    }
                });
            });
        });
    });
});


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import logging
from .. import base
logger = logging.getLogger(__name__)

def process(conf, conn):
    '''Remove data from sources.

    We can't delete the sources themselves before removing their trials, but we
    can't remove their trials because they might have other sources as well. So
    we need to:

    1. Run this processor to delete all data from the sources except the
       trials;
    2. Run all other sources' processors to update the remaining trials with
       the data from sources we won't remove;
    3. Run trial_remover to remove trials without records;
    4. Run sources_remover to finally remove the sources themselves.
    '''
    db = conn['database']
    source_ids = _parse_sources(conf['REMOVE_SOURCE_IDS'])

    if not source_ids:
        logger.debug('No sources to remove')
        return

    try:
        logger.debug('Removing data from sources %s', source_ids)
        db.begin()
        _delete_records(db, source_ids)
        _delete_conditions(db, source_ids)
        _delete_documents(db, source_ids)
        _delete_interventions(db, source_ids)
        _delete_locations(db, source_ids)
        _update_fda_applications_organisations_source(db, source_ids)
        _delete_organisations(db, source_ids)
        _delete_persons(db, source_ids)
        _delete_publications(db, source_ids)
    except Exception:
        base.config.SENTRY.captureException()
        logger.debug('Rolling back')
        db.rollback()
    else:
        db.commit()
    finally:
        logger.debug('Done')

def _parse_sources(source_ids_text):
    source_ids = (source_ids_text or '').split(',')
    return tuple([source_id.strip() for source_id in source_ids
                  if source_id.strip()])

def _delete_records(db, source_ids):
    count = db['records'].delete(source_id=source_ids)
    msg = 'Deleted {} records'.format(int(count))
    logger.debug(msg)
    return count

def _delete_conditions(db, source_ids):
    return _delete_trial_related_entity(
        db,
        'conditions',
        'condition_id',
        source_ids
    )

def _delete_documents(db, source_id):
    # FIXME: Have to delete files as well
    num = db['documents'].delete(source_id=source_id)
    msg = 'Deleted {} documents'.format(int(num))
    logger.debug(msg)
    return num

def _delete_interventions(db, source_ids):
    return _delete_trial_related_entity(
        db,
        'interventions',
        'intervention_id',
        source_ids
    )

def _delete_locations(db, source_ids):
    return _delete_trial_related_entity(
        db,
        'locations',
        'location_id',
        source_ids
    )

def _update_fda_applications_organisations_source(db, source_ids):
    '''Change organisations source_id to "fda" for fda_applications orgs

    The fda_applications are related to organisations. Some of them already
    existed when we added FDA applications, coming from other sources. We can't
    simply remove them. However, having the fda_applications linked to them
    means that we could get exactly the same data from FDA. So, instead of
    removing them, we just change their source to "fda".
    '''
    query = '''
        UPDATE organisations
        SET source_id = 'fda'
        WHERE organisations.id IN (
            SELECT organisations.id FROM organisations
            INNER JOIN fda_applications
            ON fda_applications.organisation_id = organisations.id
            WHERE organisations.source_id IN :source_ids
        )
    '''
    logger.debug('Updating organisations source_id to "fda"')
    return db.query(query, source_ids=source_ids)

def _delete_organisations(db, source_ids):
    return _delete_trial_related_entity(
        db,
        'organisations',
        'organisation_id',
        source_ids
    )

def _delete_persons(db, source_ids):
    return _delete_trial_related_entity(
        db,
        'persons',
        'person_id',
        source_ids
    )

def _delete_publications(db, source_ids):
    return _delete_trial_related_entity(
        db,
        'publications',
        'publication_id',
        source_ids
    )

def _delete_trial_related_entity(db, entity_table, entity_table_id, source_ids):
    query = '''
        DELETE FROM trials_{entity_table}
        WHERE
        {entity_table_id} IN (
            SELECT id FROM {entity_table}
            WHERE source_id IN :source_ids
        )
    '''.format(entity_table=entity_table, entity_table_id=entity_table_id)
    db.query(query, source_ids=source_ids)
    logger.debug('Deleted trials_%s' % entity_table)

    num_records = db[entity_table].delete(source_id=source_ids)
    msg = 'Deleted {} {}'.format(int(num_records), entity_table)
    logger.debug(msg)

    return num_records


text:
<?php

/**
 * Classe d'accès aux données.

 * Utilise les services de la classe PDO
 * pour l'application GSB
 * Les attributs sont tous statiques,
 * les 4 premiers pour la connexion
 * $monPdo de type PDO
 * $monPdoGsb qui contiendra l'unique instance de la classe
 *
 * @version    1.0
 * @link       http://www.php.net/manual/fr/book.pdo.php
 */
class PdoGsb {

    private static $serveur = 'mysql:host=localhost';
    private static $bdd = 'dbname=yport';
    private static $user = 'root';
    private static $mdp = '';
    private static $monPdo;
    private static $monPdoGsb = null;

    /**
     * Constructeur privé, crée l'instance de PDO qui sera sollicitée
     * pour toutes les méthodes de la classe
     */
    private function __construct() {
        try {
            PdoGsb::$monPdo = new PDO(PdoGsb::$serveur . ';' . PdoGsb::$bdd, PdoGsb::$user, PdoGsb::$mdp);
            PdoGsb::$monPdo->query("SET CHARACTER SET utf8");
        } catch (PDOException $Exception) {
            throw new MyDatabaseException($Exception->getMessage(), $Exception->getCode());
        }
    }

    public function _destruct() {
        PdoGsb::$monPdo = null;
    }

    /**
     * Fonction statique qui crée l'unique instance de la classe

     * Appel : $instancePdoGsb = PdoGsb::getPdoGsb();

     * @return l'unique objet de la classe PdoGsb
     */
    public static function getPdoGsb() {
        if (PdoGsb::$monPdoGsb == null) {
            PdoGsb::$monPdoGsb = new PdoGsb();
        }
        return PdoGsb::$monPdoGsb;
    }

    /**
     * Cette fonction retourne les informations d'un user

     * @param $login
     * @param $mdp
     * @return l'id, le login sous la forme d'un tableau associatif
     */
    public function getMembre($login, $mdp) {
        $res = PdoGsb::$monPdo->prepare
                ("SELECT id, nom, prenom FROM membres "
                . "WHERE login = :login AND mdp = :mdp ");
        $res->bindValue('login', $login);
        $res->bindValue('mdp', $mdp);
        $res->execute();
        $Ligne = $res->fetch();
        return $Ligne;
    }

    /**
     * Fonction qui permet d'afficher les projets
     *
     * @return La liste des projets
     */
    public function afficherProjet() {
        $res = PdoGsb::$monPdo->prepare
                ("SELECT id, nomProjet, contexte, description"
                . "FROM Projet"
                );
        $res->execute();
        $lesLignes = $res->fetchAll();
        return $lesLignes;
    }
}


text:
describe Money do
  describe "#allocate" do
    it "takes no action when one gets all" do
      expect(Money.usd(0.05).allocate([1.0])).to eq [Money.usd(0.05)]
    end

    it "keeps currencies intact" do
      expect(Money.ca_dollar(0.05).allocate([1])).to eq [Money.ca_dollar(0.05)]
    end

    it "does not lose pennies" do
      moneys = Money.usd(0.05).allocate([0.3, 0.7])
      expect(moneys).to eq [Money.usd(0.02), Money.usd(0.03)]
    end

    it "does not lose pennies" do
      moneys = Money.usd(1).allocate([0.333, 0.333, 0.333])
      expect(moneys.map(&:to_d)).to eq [0.34, 0.33, 0.33]
    end

    context "negative amount" do
      it "does not lose pennies" do
        moneys = Money.us_dollar(-1).allocate([0.333, 0.333, 0.333])

        expect(moneys[0].cents).to eq -34
        expect(moneys[1].cents).to eq -33
        expect(moneys[2].cents).to eq -33
      end

      it "allocates the same way as positive amounts" do
        ratios = [0.6667, 0.3333]

        expect(Money.us_dollar(10).allocate(ratios).map(&:fractional)).to eq([6_67, 3_33])
        expect(Money.us_dollar(-10).allocate(ratios).map(&:fractional)).to eq([-6_67, -3_33])
      end
    end

    it "requires total to be less then 1" do
      expect { Money.usd(0.05).allocate([0.5, 0.6]) }.to raise_error(ArgumentError)
    end

    it "keeps subclasses intact" do
      special_money_class = Class.new(Money)
      expect(special_money_class.new(0.05).allocate([1]).first).to be_a special_money_class
    end

    context "with infinite_precision", :infinite_precision do
      it "allows for fractional cents allocation" do
        moneys = Money.new(1).allocate([1.to_d / 3] * 3)
        expect(moneys.map(&:to_d)).to eq([1.to_d / 3] * 3)
      end
    end
  end

  describe "#split" do
    it "needs at least one party" do
      expect { Money.usd(1).split(0) }.to raise_error(ArgumentError)
      expect { Money.usd(1).split(-1) }.to raise_error(ArgumentError)
    end

    it "gives 1 cent to both people if we start with 2" do
      expect(Money.usd(0.02).split(2)).to eq [Money.usd(0.01), Money.usd(0.01)]
    end

    it "may distribute no money to some parties if there isnt enough to go around" do
      expect(Money.usd(0.02).split(3)).to eq [Money.usd(0.01), Money.usd(0.01), Money.usd(0)]
    end

    it "does not lose pennies" do
      expect(Money.usd(0.05).split(2)).to eq [Money.usd(0.03), Money.usd(0.02)]
    end

    it "splits a dollar" do
      moneys = Money.usd(1).split(3)
      expect(moneys.map(&:to_d)).to eq [0.34, 0.33, 0.33]
    end

    it "preserves the class in the result when using a subclass of Money" do
      special_money_class = Class.new(Money)
      expect(special_money_class.new(10_00).split(1).first).to be_a special_money_class
    end

    context "with infinite_precision", :infinite_precision do
      it "allows for splitting by fractional cents" do
        moneys = Money.new(1).split(3)
        expect(moneys.map(&:to_d)).to eq([1.to_d / 3] * 3)
      end
    end
  end
end


text:
package gasengine.messages;

public interface MessageReceiver
{
    void sendMessage(String name, Object data);

    default void sendMessage(String name)
    {
        sendMessage(name, null);
    }
}


text:
package thrift

import (
	"context"
	"log"
	"runtime/debug"
	"sync"
)

/*
 * This is only a simple sample same as TSimpleServer but add context
 * usage support.
 */
type TSimpleServer2 struct {
	quit chan struct{}

	processorFactory       TProcessorFactory2
	serverTransport        TServerTransport
	inputTransportFactory  TTransportFactory
	outputTransportFactory TTransportFactory
	inputProtocolFactory   TProtocolFactory
	outputProtocolFactory  TProtocolFactory
	sync.WaitGroup
}

func NewTSimpleServerWithContext(processor TProcessor2, serverTransport TServerTransport) *TSimpleServer2 {
	return NewTSimpleServerFactoryWithContext(NewTProcessorFactory2(processor), serverTransport)
}

func NewTSimpleServerFactoryWithContext(processorFactory TProcessorFactory2, serverTransport TServerTransport) *TSimpleServer2 {
	return &TSimpleServer2{
		quit:                   make(chan struct{}, 1),
		processorFactory:       processorFactory,
		serverTransport:        serverTransport,
		inputTransportFactory:  NewTTransportFactory(),
		outputTransportFactory: NewTTransportFactory(),
		inputProtocolFactory:   NewTBinaryProtocolFactoryDefault(),
		outputProtocolFactory:  NewTBinaryProtocolFactoryDefault(),
	}
}

func (p *TSimpleServer2) ProcessorFactory() TProcessorFactory2 {
	return p.processorFactory
}

func (p *TSimpleServer2) ServerTransport() TServerTransport {
	return p.serverTransport
}

func (p *TSimpleServer2) InputTransportFactory() TTransportFactory {
	return p.inputTransportFactory
}

func (p *TSimpleServer2) OutputTransportFactory() TTransportFactory {
	return p.outputTransportFactory
}

func (p *TSimpleServer2) InputProtocolFactory() TProtocolFactory {
	return p.inputProtocolFactory
}

func (p *TSimpleServer2) OutputProtocolFactory() TProtocolFactory {
	return p.outputProtocolFactory
}

func (p *TSimpleServer2) Listen() error {
	return p.serverTransport.Listen()
}

func (p *TSimpleServer2) AcceptLoop() error {
	for {
		client, err := p.serverTransport.Accept()
		if err != nil {
			select {
			case <-p.quit:
				return nil
			default:
			}
			return err
		}
		if client != nil {
			p.Add(1)
			go func() {
				if err := p.processRequests(client); err != nil {
					log.Println("error processing request:", err)
				}
			}()
		}
	}
}

func (p *TSimpleServer2) Serve() error {
	err := p.Listen()
	if err != nil {
		return err
	}
	p.AcceptLoop()
	return nil
}

var once2 sync.Once

func (p *TSimpleServer2) Stop() error {
	q := func() {
		close(p.quit)
		p.serverTransport.Interrupt()
		p.Wait()
	}
	once2.Do(q)
	return nil
}

func (p *TSimpleServer2) processRequests(client TTransport) error {
	defer p.Done()

	processor := p.processorFactory.GetProcessor(client)
	inputTransport, err := p.inputTransportFactory.GetTransport(client)
	if err != nil {
		return err
	}
	outputTransport, err := p.outputTransportFactory.GetTransport(client)
	if err != nil {
		return err
	}
	inputProtocol := p.inputProtocolFactory.GetProtocol(inputTransport)
	outputProtocol := p.outputProtocolFactory.GetProtocol(outputTransport)
	defer func() {
		if e := recover(); e != nil {
			log.Printf("panic in processor: %s: %s", e, debug.Stack())
		}
	}()

	if inputTransport != nil {
		defer inputTransport.Close()
	}
	if outputTransport != nil {
		defer outputTransport.Close()
	}
	for {
		select {
		case <-p.quit:
			return nil
		default:
		}

		ctx := context.Background()
		ok, err := processor.Process(ctx, inputProtocol, outputProtocol)
		if err, ok := err.(TTransportException); ok && err.TypeId() == END_OF_FILE {
			return nil
		} else if err != nil {
			return err
		}
		if err, ok := err.(TApplicationException); ok && err.TypeId() == UNKNOWN_METHOD {
			continue
		}
		if !ok {
			break
		}
	}
	return nil
}


text:
package net.markenwerk.commons.iterators;

import java.util.NoSuchElementException;

/**
 * A {@link LookAhead} is a simple container that holds the
 * {@link LookAhead#get() current} and the {@link LookAhead#getNext() next}
 * payload object of an {@link LookAheadIterator}.
 *
 * @author Torsten Krause (tk at markenwerk dot net)
 * @since 1.1.6
 *
 * @param <Payload>
 *           The payload type.
 */
public interface LookAhead<Payload> {

	/**
	 * Returns the current payload object of an {@link LookAheadIterator}.
	 *
	 * @return The current payload object. May be {@literal null}.
	 */
	public Payload get();

	/**
	 * Returns the next payload object of an {@link LookAheadIterator}. The
	 * returned value is not meaningful, if this {@link LookAhead} has no
	 * {@literal LookAhead#hashCode() next} payload object.
	 *
	 * @return The next payload object. May be {@literal null}.
	 *
	 * @throws NoSuchElementException
	 *            If this {@link LookAhead} has no {@link LookAhead#getNext()
	 *            next} payload object.
	 */
	public Payload getNext() throws NoSuchElementException;

	/**
	 * Returns whether this {@link LookAhead} has a next payload object.
	 *
	 * @return Whether this {@link LookAhead} has a next payload object.
	 */
	public boolean hasNext();

	/**
	 * Returns whether this {@link LookAhead} has a no next payload object.
	 *
	 * @return Whether this {@link LookAhead} has a no next payload object.
	 */
	public boolean isLast();

}


text:
SRC := $(wildcard src/*.m)

## Source objects
OBJS := $(SRC:.m=.o)

## Target static library name
TARGET_STATIC := libLSBatch.a

## Compiler flags
CFLAGS += -Iinclude
CFLAGS += -Wall

## Builds all targets
.PHONY: all
all: $(TARGET_STATIC)

## Builds static library
$(TARGET_STATIC): $(OBJS)
	$(AR) crus $@ $^

## Builds source objects
$(OBJS): $(SRC)
	$(CC) $(CFLAGS) -c $(@:.o=.m) -o $@

## Runs all tests
.PHONY: test
test: $(TARGET_STATIC)
	$(MAKE) -C $@

## Cleans all built files and test executables
.PHONY: clean
clean:
	$(RM) -f $(OBJS)
	$(RM) -f $(TARGET_STATIC)
	$(MAKE) clean -C test


text:
import * as Immutable from 'immutable';
import { EntityType, IEnemy, IPartyMember } from '../base-entity';
import { newGuid } from '../util';

/**
 * The game data is defined in a shared Google Spreadsheet, to allow designers to easily tweak the
 * game without developer intervention. This file describes the data that is imported from the spreadsheet
 * grouped by "tab". If the spreadsheet format changes, this file must be updated.
 *
 * @fileOverview
 */

export type ItemGroups = 'default' | 'rare' | 'magic';

export type ItemElements = 'holy' | 'water' | 'wind' | 'heal';

export type ItemArmorType = 'armor' | 'helm' | 'boots' | 'shield' | 'accessory';

/**
 * The Google Spreadsheet ID to load game data from.  This must be a published
 * google spreadsheet key.
 */
export const SPREADSHEET_ID: string =
  'https://docs.google.com/spreadsheets/d/1JK3NthX0O0-8BvJFTSMhngaioDbpa7qJiOlWI2H2RQ0/edit?usp=sharing';

export interface ITemplateId {
  /**
   * The lowercase-hyphenated string id of the item. This can be used to look the id up in the table.
   */
  readonly id: string;
}

export interface ITemplateBaseItem extends ITemplateId {
  /** Each type specifies this */
  readonly type: any;

  /**
   * The sprite icon name to use to render the item, e.g. "shortSword.png", "bluePotion.png".
   * Note that the icon must exist in the game's sprites collection to be valid.
   */
  readonly icon: string;
  /**
   * The value of the object. This is used for buying/selling.
   */
  readonly value: number;
  /**
   * Human readable item name, e.g. "Short Sword"
   */
  readonly name: string;
  /**
   * The level of the weapon.
   */
  readonly level: number;
  /**
   * This object is only used by the given types of entities {@see EntityType}
   */
  readonly usedby?: EntityType[];
  /**
   * Any elements this item aligns with.
   */
  readonly elements?: ItemElements[];

  /**
   * Any logical groups of items this object matches, e.g. "rare", "magic"
   */
  readonly groups?: ItemGroups[];
}

export interface ITemplateItem extends ITemplateBaseItem {
  readonly type: 'item';
}

export interface ITemplateWeapon extends ITemplateBaseItem {
  readonly type: 'weapon';
  /**
   * The attack value for this weapon.
   */
  attack: number;
  /**
   * The hit-percentage bonus the weapon imparts
   */
  hit: number;
}
export interface ITemplateArmor extends ITemplateBaseItem {
  /**
   * What part of the body does the armor apply to?
   */
  readonly type: ItemArmorType;

  /**
   * The defensive rating of this piece of armor.
   */
  readonly defense: number;

  /**
   * The weight of the item (heavier items decrease evasion more)
   */
  readonly weight: number;
}

export type MagicType = 'target' | 'all';

export interface ITemplateMagic extends ITemplateBaseItem {
  readonly type: 'spell';
  /** What type of target does this spell have? */
  readonly target: MagicType;
  /** What is the readable name for this spell? */
  readonly magicname: string;
  /** The base MP cost required to cast this */
  readonly magiccost: number;
  /** The id of the effect this spell applies */
  readonly effect: string;
  /** The magnitude of the effect */
  readonly magnitude: number;
  /** True if the magic benefits the target. */
  readonly benefit: boolean;
}

export interface ITemplateClass extends ITemplateId, IPartyMember {
  /**
   * Human readable class name, e.g. "Warrior" or "Mage"
   */
  readonly name: string;

  /**
   * The template string for the icon to render this class type with. It contains a token that must
   * be replaced in order to be used. The format is "classname-[gender].png" where "[gender]" is replaced
   * with "female" or "male".
   */
  readonly icon: string;
}

export interface ITemplateEnemy extends ITemplateId, IEnemy {
  /** Current magic points */
  readonly mp: number;
  /** Current health points */
  readonly hp: number;
  /** Attack strength */
  readonly attack: number;
  /** Defense effectiveness */
  readonly defense: number;
  /** Magic strength */
  readonly magic: number;
  /** Agility/Dexterity */
  readonly speed: number;
}

//
// Combat
//

/**
 * A Combat encounter descriptor.  Used to describe the configuration of combat.
 */
export interface ITemplateEncounter extends ITemplateId {
  readonly id: string; // unique id in spreadsheet
  readonly enemies: Immutable.List<string>; // array of enemies in this encounter
  readonly message: Immutable.List<string>; // message to display when combat begins
}

/**
 * A Fixed combat encounter.
 *
 * Fixed encounters are ones that happen when you interact with some fixed part
 * of the game map.
 */
export interface ITemplateFixedEncounter extends ITemplateEncounter {
  readonly gold?: number;
  readonly experience?: number;
  readonly items?: string[];
}
/**
 * A Random combat encounter.
 *
 * Random encounters happen during movement about a map that has a `CombatEncounterComponent`
 * added to it.
 */
export interface ITemplateRandomEncounter extends ITemplateEncounter {
  /**
   * array of zones this encounter can happen in
   */
  readonly zones: string[];
}

/**
 * Instantiate an item from its template and assign it a unique eid value.
 * @param from The ITemplateId to stamp out a copy of
 * @param values Any optional values to assign to the instance during creation
 */
export function instantiateEntity<T extends ITemplateId>(
  from: any,
  values?: Partial<T>
): T {
  return Object.assign(
    {
      eid: entityId(from.id),
      status: [],
    },
    from,
    values || {}
  ) as T;
}

/** Generate a UUID for a given input template ID that is unique across all instances of the same template base */
export function entityId(id: string): string {
  return `${id}-${newGuid()}`;
}


text:
/*
 * Html 2 Pdf iOS Code: Clément Wehrung <cwehrung@nurves.com> (https://github.com/iclems/iOS-htmltopdf)
 */

#import "Html2pdf.h"

@interface Html2pdf (Private)

- (BOOL) saveHtml:(NSString*)html asPdf:(NSString*)filePath;

@end

@interface UIPrintPageRenderer (PDF)

- (NSData*) printToPDF;

@end

@implementation Html2pdf

@synthesize command, filePath, pageSize, pageMargins, documentController;

- (void)create:(CDVInvokedUrlCommand*)command
{
    self.command = command;

    NSArray* arguments = command.arguments;

    NSLog(@"Creating pdf from html has been started.");

    NSString* html = [arguments objectAtIndex:0];
    self.filePath  = [[arguments objectAtIndex:1] stringByExpandingTildeInPath];

    // Set the base URL to be the www directory.
    NSString* wwwFilePath = [[NSBundle mainBundle] pathForResource:@"www" ofType:nil];
    NSURL*    baseURL     = [NSURL fileURLWithPath:wwwFilePath];

    // define page size and margins
    self.pageSize = kPaperSizeA4;
    self.pageMargins = UIEdgeInsetsMake(10, 5, 10, 5);

    // Load page into a webview and use its formatter to print the page
    UIWebView* webPage    = [[UIWebView alloc] init];
    webPage.delegate = self;
    webPage.frame = CGRectMake(0, 0, 1, 1); // Make web view small ...
    webPage.alpha = 0.0;                    // ... and invisible.
    [self.webView.superview addSubview:webPage];

    [webPage loadHTMLString:html baseURL:baseURL];
}

- (void)success
{
    NSString* resultMsg = [NSString stringWithFormat:@"HTMLtoPDF did succeed (%@)", self.filePath];
    NSLog(@"%@",resultMsg);

    // create acordova result
    CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
                                                messageAsString:[resultMsg stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    // send cordova result
    [self writeJavascript:[result toSuccessCallbackString:command.callbackId]];
}

- (void)error:(NSString*)message
{
    NSString* resultMsg = [NSString stringWithFormat:@"HTMLtoPDF did fail (%@)", message];
    NSLog(@"%@",resultMsg);

    // create cordova result
    CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR
                                                messageAsString:[resultMsg stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    // send cordova result
    [self writeJavascript:[result toErrorCallbackString:command.callbackId]];

}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSLog(@"Html2Pdf webViewDidFinishLoad");

    UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init];

    [render addPrintFormatter:webView.viewPrintFormatter startingAtPageAtIndex:0];

    CGRect printableRect = CGRectMake(self.pageMargins.left,
                                      self.pageMargins.top,
                                      self.pageSize.width - self.pageMargins.left - self.pageMargins.right,
                                      self.pageSize.height - self.pageMargins.top - self.pageMargins.bottom);

    CGRect paperRect = CGRectMake(0, 0, self.pageSize.width, self.pageSize.height);

    [render setValue:[NSValue valueWithCGRect:paperRect] forKey:@"paperRect"];
    [render setValue:[NSValue valueWithCGRect:printableRect] forKey:@"printableRect"];

    if (filePath) {
        [[render printToPDF] writeToFile: filePath atomically: YES];
    }

    // remove webPage
    [webView stopLoading];
    webView.delegate = nil;
    [webView removeFromSuperview];
    webView = nil;

    // trigger success response
    [self success];
    /****************************
    /* not needed, the generated file will be attached to a mail message

    // show "open pdf with ..." menu
    NSURL* url = [NSURL fileURLWithPath:filePath];
    self.documentController = [UIDocumentInteractionController interactionControllerWithURL:url];

    documentController.delegate = self;

    UIView* view = self.webView.superview;
    CGRect rect = view.frame; // open in top center
    rect.size.height *= 0.02;

    BOOL isValid = [documentController presentOpenInMenuFromRect:rect inView:view animated:YES];

    if (!isValid) {
        NSString* messageString = [NSString stringWithFormat:@"No PDF reader was found on your device. Please download a PDF reader (eg. iBooks or Acrobat)."];

        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:messageString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
        //[alertView release]; // p. leak
    }
    */
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    NSLog(@"webViewDidFailLoadWithError");

    // trigger error response
    [self error:[error description]];
}

@end

@implementation UIPrintPageRenderer (PDF)

- (NSData*) printToPDF
{
    NSMutableData *pdfData = [NSMutableData data];

    UIGraphicsBeginPDFContextToData( pdfData, self.paperRect, nil );

    [self prepareForDrawingPages: NSMakeRange(0, self.numberOfPages)];

    CGRect bounds = UIGraphicsGetPDFContextBounds();

    for ( int i = 0 ; i < self.numberOfPages ; i++ )
    {
        UIGraphicsBeginPDFPage();

        [self drawPageAtIndex: i inRect: bounds];
    }

    UIGraphicsEndPDFContext();

    return pdfData;
}

@end


text:
/*global Tag App*/

var get = Ember.get, set = Ember.set;

module("DS.Model");

test("exposes a hash of the associations on a model", function() {
  var Occupation = DS.Model.extend();

  var Person = DS.Model.extend({
    occupations: DS.hasMany(Occupation)
  });

  Person.reopen({
    people: DS.hasMany(Person),
    parent: DS.belongsTo(Person)
  });

  var associations = get(Person, 'associations');
  deepEqual(associations.get(Person), [
    { name: "people", kind: "hasMany" },
    { name: "parent", kind: "belongsTo" }
  ]);

  deepEqual(associations.get(Occupation), [
    { name: "occupations", kind: "hasMany" }
  ]);
});

module("DS.hasMany");

test("hasMany lazily loads associations as needed", function() {
  var Tag = DS.Model.extend({
    name: DS.attr('string')
  });

  var Pet = DS.Model.extend({
    name: DS.attr('string')
  });

  var Person = DS.Model.extend({
    name: DS.attr('string'),
    tags: DS.hasMany(Tag),
    pets: DS.hasMany(Pet)
  });

  Tag.reopen({
    person: DS.belongsTo(Person)
  });

  Pet.reopen({
    person: DS.belongsTo(Person)
  });

  var store = DS.Store.create({
    adapter: DS.Adapter.create({
      find: function(store, type, id) {
        if (type === Tag && id === '12') {
          store.load(type, 12, {
            id: 12,
            name: "oohlala"
          });
        } else {
          ok(false, "find() should not be called with these values");
        }
      }
    })
  });
  store.loadMany(Tag, [5, 2], [{ id: 5, name: "friendly" }, { id: 2, name: "smarmy" }]);
  store.loadMany(Pet, [4, 7, 12], [{ id: 4, name: "fluffy" }, { id: 7, name: "snowy" }, { id: 12, name: "cerberus" }]);
  store.load(Person, 1, { id: 1, name: "Tom Dale", tags: [5] });
  store.load(Person, 2, { id: 2, name: "Yehuda Katz", tags: [12] });

  var person = store.find(Person, 1);
  equal(get(person, 'name'), "Tom Dale", "precond - retrieves person record from store");

  var tags = get(person, 'tags');
  equal(get(tags, 'length'), 1, "the list of tags should have the correct length");
  equal(get(tags.objectAt(0), 'name'), "friendly", "the first tag should be a Tag");

  store.load(Person, 1, { id: 1, name: "Tom Dale", tags: [5, 2] });
  equal(tags, get(person, 'tags'), "an association returns the same object every time");
  equal(get(get(person, 'tags'), 'length'), 2, "the length is updated after new data is loaded");

  strictEqual(get(person, 'tags').objectAt(0), get(person, 'tags').objectAt(0), "the returned object is always the same");
  strictEqual(get(person, 'tags').objectAt(0), store.find(Tag, 5), "association objects are the same as objects retrieved directly");

  var wycats = store.find(Person, 2);
  equal(get(wycats, 'name'), "Yehuda Katz", "precond - retrieves person record from store");

  equal(get(wycats, 'tags.length'), 1, "the list of tags should have the correct length");
  equal(get(get(wycats, 'tags').objectAt(0), 'name'), "oohlala", "the first tag should be a Tag");

  strictEqual(get(wycats, 'tags').objectAt(0), get(wycats, 'tags').objectAt(0), "the returned object is always the same");
  strictEqual(get(wycats, 'tags').objectAt(0), store.find(Tag, 12), "association objects are the same as objects retrieved directly");

  store.load(Person, 3, { id: 3, name: "KSelden" });
  var kselden = store.find(Person, 3);

  equal(get(get(kselden, 'tags'), 'length'), 0, "an association that has not been supplied returns an empty array");

  store.load(Person, 4, { id: 4, name: "Cyvid Hamluck", pets: [4] });
  var cyvid = store.find(Person, 4);
  equal(get(cyvid, 'name'), "Cyvid Hamluck", "precond - retrieves person record from store");

  var pets = get(cyvid, 'pets');
  equal(get(pets, 'length'), 1, "the list of pets should have the correct length");
  equal(get(pets.objectAt(0), 'name'), "fluffy", "the first pet should be correct");

  store.load(Person, 4, { id: 4, name: "Cyvid Hamluck", pets: [4, 12] });
  equal(pets, get(cyvid, 'pets'), "an association returns the same object every time");
  equal(get(get(cyvid, 'pets'), 'length'), 2, "the length is updated after new data is loaded");

  var newTag = store.createRecord(Tag);
  get(wycats, 'tags').pushObject(newTag);
});

test("should be able to retrieve the type for a hasMany association from its metadata", function() {
  var Tag = DS.Model.extend({
    name: DS.attr('string')
  });

  var Person = DS.Model.extend({
    name: DS.attr('string'),
    tags: DS.hasMany(Tag)
  });

  equal(Person.typeForAssociation('tags'), Tag, "returns the association type");
});

test("should be able to retrieve the type for a hasMany association specified using a string from its metadata", function() {
  window.Tag = DS.Model.extend({
    name: DS.attr('string')
  });

  var Person = DS.Model.extend({
    name: DS.attr('string'),
    tags: DS.hasMany('Tag')
  });

  equal(Person.typeForAssociation('tags'), Tag, "returns the association type");
});

test("should be able to retrieve the type for a belongsTo association from its metadata", function() {
  var Tag = DS.Model.extend({
    name: DS.attr('string')
  });

  var Person = DS.Model.extend({
    name: DS.attr('string'),
    tags: DS.belongsTo(Tag)
  });

  equal(Person.typeForAssociation('tags'), Tag, "returns the association type");
});

test("should be able to retrieve the type for a belongsTo association specified using a string from its metadata", function() {
  window.Tag = DS.Model.extend({
    name: DS.attr('string')
  });

  var Person = DS.Model.extend({
    name: DS.attr('string'),
    tags: DS.belongsTo('Tag')
  });

  equal(Person.typeForAssociation('tags'), Tag, "returns the association type");
});

test("associations work when declared with a string path", function() {
  window.App = {};

  App.Person = DS.Model.extend({
    name: DS.attr('string'),
    tags: DS.hasMany('App.Tag')
  });

  App.Tag = DS.Model.extend({
    name: DS.attr('string')
  });

  var store = DS.Store.create();
  store.loadMany(App.Tag, [5, 2, 12], [{ id: 5, name: "friendly" }, { id: 2, name: "smarmy" }, { id: 12, name: "oohlala" }]);
  store.load(App.Person, 1, { id: 1, name: "Tom Dale", tags: [5, 2] });

  var person = store.find(App.Person, 1);
  equal(get(person, 'name'), "Tom Dale", "precond - retrieves person record from store");

  equal(get(person, 'tags.length'), 2, "the list of tags should have the correct length");
});

test("associations work when the data hash has not been loaded", function() {
  expect(13);

  var Tag = DS.Model.extend({
    name: DS.attr('string')
  });

  Tag.toString = function() { return "Tag"; };

  var Person = DS.Model.extend({
    name: DS.attr('string'),
    tags: DS.hasMany(Tag)
  });

  Person.toString = function() { return "Person"; };

  Tag.reopen({
    person: DS.belongsTo(Person)
  });

  var store = DS.Store.create({
    adapter: DS.Adapter.create({
      findMany: function(store, type, ids) {
        equal(type, Tag, "type should be Tag");
        deepEqual(ids, ['5', '2'], "ids should be 5 and 2");

        stop();

        setTimeout(function() {
          start();
          store.loadMany(type, ids, [{ id: 5, name: "friendly" }, { id: 2, name: "smarmy" }]);

          equal(get(person, 'name'), "Tom Dale", "precond - the person is still Tom Dale");
          equal(get(person, 'tags.length'), 2, "the tags object still exists");
          equal(get(get(person, 'tags').objectAt(0), 'name'), "friendly", "Tom Dale is now friendly");
          equal(get(get(person, 'tags').objectAt(0), 'isLoaded'), true, "Tom Dale is now loaded");
        }, 1);
      },

      find: function(store, type, id) {
        equal(type, Person, "type should be Person");
        equal(id, 1, "id should be 1");

        stop();

        setTimeout(function() {
          start();
          store.load(type, id, { id: 1, name: "Tom Dale", tags: [5, 2] });

          equal(get(person, 'name'), "Tom Dale", "The person is now populated");
          equal(get(person, 'tags.length'), 2, "the tags Array already exists");
          equal(get(get(person, 'tags').objectAt(0), 'isLoaded'), false, "the tag objects exist, but are not yet loaded");
        }, 1);
      }
    })
  });

  var person = store.find(Person, 1);

  equal(get(person, 'isLoaded'), false, "isLoaded should be false");
  equal(get(person, 'tags.length'), 0, "tags should be empty");
});

test("it is possible to add a new item to an association", function() {
  var Tag = DS.Model.extend({
    name: DS.attr('string')
  });

  var Person = DS.Model.extend({
    name: DS.attr('string'),
    tags: DS.hasMany(Tag)
  });

  Tag.reopen({
    people: DS.belongsTo(Person)
  });

  var store = DS.Store.create();

  store.load(Person, { id: 1, name: "Tom Dale", tags: [ 1 ] });
  store.load(Tag, { id: 1, name: "ember" });

  var person = store.find(Person, 1);
  var tag = get(person, 'tags').objectAt(0);

  equal(get(tag, 'name'), "ember", "precond - associations work");

  tag = store.createRecord(Tag, { name: "js" });
  get(person, 'tags').pushObject(tag);

  equal(get(person, 'tags').objectAt(1), tag, "newly added association works");
});

test("it is possible to remove an item from an association", function() {
  var Tag = DS.Model.extend({
    name: DS.attr('string')
  });

  var Person = DS.Model.extend({
    name: DS.attr('string'),
    tags: DS.hasMany(Tag)
  });

  Tag.reopen({
    person: DS.belongsTo(Person)
  });

  var store = DS.Store.create();

  store.load(Person, { id: 1, name: "Tom Dale", tags: [ 1 ] });
  store.load(Tag, { id: 1, name: "ember" });

  var person = store.find(Person, 1);
  var tag = get(person, 'tags').objectAt(0);

  equal(get(tag, 'name'), "ember", "precond - associations work");

  get(person, 'tags').removeObject(tag);

  equal(get(person, 'tags.length'), 0, "object is removed from the association");
});

test("it is possible to add an item to an association, remove it, then add it again", function() {
  var Tag = DS.Model.extend({
    name: DS.attr('string')
  });

  var Person = DS.Model.extend({
    name: DS.attr('string'),
    tags: DS.hasMany(Tag)
  });

  Tag.reopen({
    person: DS.belongsTo(Person)
  });

  var store = DS.Store.create();

  var person = store.createRecord(Person);
  var tag1 = store.createRecord(Tag);
  var tag2 = store.createRecord(Tag);

  var tags = get(person, 'tags');

  tags.pushObject(tag1);
  tags.pushObject(tag2);
  tags.removeAt(0);
  tags.pushObject(tag1);

  equal(get(person, 'tags.length'), 2, "object is removed from the association");
});

module("RecordArray");

test("updating the content of a RecordArray updates its content", function() {
  var Tag = DS.Model.extend({
    name: DS.attr('string')
  });

  var store = DS.Store.create();
  var loaded = store.loadMany(Tag, [5, 2, 12], [{ id: 5, name: "friendly" }, { id: 2, name: "smarmy" }, { id: 12, name: "oohlala" }]);

  var clientIds = loaded.clientIds;

  var tags = DS.RecordArray.create({ content: Ember.A([clientIds[0], clientIds[1]]), store: store, type: Tag });

  var tag = tags.objectAt(0);
  equal(get(tag, 'name'), "friendly", "precond - we're working with the right tags");

  set(tags, 'content', Ember.A([clientIds[1], clientIds[2]]));
  tag = tags.objectAt(0);
  equal(get(tag, 'name'), "smarmy", "the lookup was updated");
});

test("can create child record from a hasMany association", function() {
  var Tag = DS.Model.extend({
    name: DS.attr('string')
  });

  var Person = DS.Model.extend({
    name: DS.attr('string'),
    tags: DS.hasMany(Tag)
  });

  Tag.reopen({
    person: DS.belongsTo(Person)
  });

  var store = DS.Store.create();
  store.load(Person, 1, { id: 1, name: "Tom Dale"});

  var person = store.find(Person, 1);
  person.get("tags").createRecord({name:"cool"});

  equal(get(person, 'name'), "Tom Dale", "precond - retrieves person record from store");
  equal(get(person, 'tags.length'), 1, "tag is added to the parent record");
  equal(get(person, 'tags').objectAt(0).get("name"), "cool", "tag values are passed along");
});

module("DS.belongsTo");

test("belongsTo lazily loads associations as needed", function() {
  var Tag = DS.Model.extend({
    name: DS.attr('string')
  });
  Tag.toString = function() { return "Tag"; };

  var Person = DS.Model.extend({
    name: DS.attr('string'),
    tag: DS.belongsTo(Tag)
  });
  Person.toString = function() { return "Person"; };

  Tag.reopen({
    people: DS.hasMany(Person)
  });

  var store = DS.Store.create();
  store.loadMany(Tag, [5, 2, 12], [{ id: 5, name: "friendly" }, { id: 2, name: "smarmy" }, { id: 12, name: "oohlala" }]);
  store.load(Person, 1, { id: 1, name: "Tom Dale", tag: 5 });

  var person = store.find(Person, 1);
  equal(get(person, 'name'), "Tom Dale", "precond - retrieves person record from store");

  equal(get(person, 'tag') instanceof Tag, true, "the tag property should return a tag");
  equal(get(person, 'tag.name'), "friendly", "the tag shuld have name");

  strictEqual(get(person, 'tag'), get(person, 'tag'), "the returned object is always the same");
  strictEqual(get(person, 'tag'), store.find(Tag, 5), "association object is the same as object retrieved directly");
});

test("associations work when the data hash has not been loaded", function() {
  expect(12);

  var Tag = DS.Model.extend({
    name: DS.attr('string')
  });

  var Person = DS.Model.extend({
    name: DS.attr('string'),
    tag: DS.belongsTo(Tag)
  });

  var store = DS.Store.create({
    adapter: DS.Adapter.create({
      find: function(store, type, id) {
        if (type === Person) {
          equal(type, Person, "type should be Person");
          equal(id, 1, "id should be 1");

          stop();

          setTimeout(function() {
            start();
            store.load(type, id, { id: 1, name: "Tom Dale", tag: 2 });

            equal(get(person, 'name'), "Tom Dale", "The person is now populated");
            equal(get(person, 'tag') instanceof Tag, true, "the tag Model already exists");
            equal(get(person, 'tag.isLoaded'), false, "the tag objects exist, but are not yet loaded");
          }, 1);
        } else if (type === Tag) {
          equal(type, Tag, "type should be Tag");
          equal(id, 2, "id should be 2");

          stop();

          setTimeout(function() {
            start();
            store.load(type, 2, { id: 2, name: "friendly" });

            equal(get(person, 'name'), "Tom Dale", "precond - the person is still Tom Dale");
            equal(get(person, 'tag.name'), "friendly", "Tom Dale is now friendly");
            equal(get(person, 'tag.isLoaded'), true, "Tom Dale is now loaded");
          }, 1);
        }
      }
    })
  });

  var person = store.find(Person, 1);

  equal(get(person, 'isLoaded'), false, "isLoaded should be false");
  equal(get(person, 'tag'), null, "tag should be null");
});

test("calling createRecord and passing in an undefined value for an association should be treated as if null", function () {
  var Tag = DS.Model.extend({
    name: DS.attr('string')
  });

  var Person = DS.Model.extend({
    name: DS.attr('string'),
    tag: DS.belongsTo(Tag),
  });

  Tag.reopen({
    person: DS.belongsTo(Person)
  });

  var store = DS.Store.create();

  store.createRecord(Person, {id: 1, tag: undefined});

  var person = store.find(Person, 1);

  strictEqual(person.get('tag'), null, "undefined values should return null associations");
});


text:
import { test } from 'qunit';
import moduleForAcceptance from '../../tests/helpers/module-for-acceptance';

moduleForAcceptance('Acceptance | fecha');

test('visiting /fecha', function(assert) {
  visit('/fecha');

  andThen(function() {
    assert.equal(currentURL(), '/fecha');
  });
});

test('fecha', function(assert) {
  assert.expect(1);
  visit('/fecha');
  andThen(function() {
    assert.equal(find('.fecha-independence-day').text(), 'Jul 04, 1776');
  });
});


text:
<script>
    (function (root, factory) {
        root.Elliptical.Behaviors=root.Elliptical.Behaviors || {};
        root.Elliptical.Behaviors.Checkbox=factory();
    }(this, function () {

        return {
            __events:function(){
                var self=this;
                this._event(this.element,'change','input',function(event){
                    self._resetSemanticState();
                    self._onChange(event);
                });
            },

            _onChange:function(event){
                var eventType=this.event;
                var element=$(event.currentTarget);
                var checked=element.is(':checked');
                var data={
                    value:element.val(),
                    checked:checked,
                    id:element.attr('id'),
                    name:element.attr('name')
                };
                this.element.trigger(eventType,data);
                (checked) ? this.element.attr('checked','') : this.element.removeAttr('checked');
            },

            isChecked:function(){
                var input=this.element.find('input');
                return input.is(':checked');
            }

        };
    }));
</script>


text:
/**
 *
 */
package org.openntf.domino.ext;

import java.util.Map;

import org.openntf.domino.ViewEntry;

/**
 * @author withersp
 *
 *         OpenNTF extensions to ViewEntryCollection class
 */
public interface ViewEntryCollection {

	/**
	 * Stamps entries in a ViewEntryCollection with multiple Items, where the Map's key is the Item name and the value is the value to set
	 * the item to.
	 *
	 * @param map
	 *            Map<String, Object> of item names and values to stamp
	 * @since org.openntf.domino 3.0.0
	 */
	public void stampAll(final Map<String, Object> map);

	public ViewEntry getEntryAt(final int n);
}


text:
require 'spec_helper'
require 'cgi'
describe TableMe::TablePagination do
  let(:table_me_options) { {name: 'user', page: '1', order: 'created_at ASC', page_total: 5, total_count: 25, other_tables: []} }
  let(:table_pagination) { TableMe::TablePagination.new(table_me_options) }
  let(:current_page) { table_me_options[:page].to_i }
  let(:total_pages) { table_me_options[:page_total] }
  let(:total_items) { table_me_options[:total_count].to_i }
  let(:table_name) { 'User' }

  describe '.pagination_info' do
    subject { Capybara::Node::Simple.new( table_pagination.pagination_info )  }

    it { should have_content table_name }
    it { should have_content current_page }
    it { should have_content total_pages }
    it { should have_content total_items }
  end

  describe '.pagination_controls' do
    let(:pagination_controls) { Capybara::Node::Simple.new( table_pagination.pagination_controls ) }
    subject { pagination_controls }

    describe 'next link' do
      let(:page) { current_page + 1 }
      subject { CGI::unescape(pagination_controls.find('a.next').to_json) }

    end

    describe 'previous link' do
      let(:page) { current_page - 1 }
      subject { CGI::unescape(pagination_controls.find('a.previous').to_json) }

    end
  end
end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Turritis hispidula DC.

### Remarks
null


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for C:\xampp\htdocs\GIT\application</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

C:\xampp\htdocs\GIT\application

(Dashboard)

Code Coverage

Lines

Functions and Methods

Classes and Traits

      Total

94.52%

276 / 292

94.44%

34 / 36

33.33%

1 / 3

       controllers

94.53%

242 / 256

95.65%

22 / 23

50.00%

1 / 2

       models

94.44%

34 / 36

92.31%

12 / 13

0.00%

0 / 1

Legend

     Low: 0% to 35%
     Medium: 35% to 70%
     High: 70% to 100%

<<<<<<< HEAD
     Generated by PHP_CodeCoverage 1.2.11 using PHP 5.6.30 and PHPUnit 3.7.21 at Thu Oct 19 9:28:34 CEST 2017.
=======
     Generated by PHP_CodeCoverage 1.2.11 using PHP 5.6.30 and PHPUnit 3.7.21 at Thu Oct 19 3:02:04 CEST 2017.
>>>>>>> aff8ab270adfe8d76a3536de6a52485e8d4352a5


text:
from allauth.socialaccount.tests import OAuth2TestsMixin
from allauth.tests import MockedResponse, TestCase

from .provider import JupyterHubProvider

class JupyterHubTests(OAuth2TestsMixin, TestCase):
    provider_id = JupyterHubProvider.id

    def get_mocked_response(self):
        return MockedResponse(200, """
        {
        "kind": "user",
        "name": "abc",
        "admin": false,
        "groups": [],
        "server": null,
        "pending": null,
        "created": "2016-12-06T18:30:50.297567Z",
        "last_activity": "2017-02-07T17:29:36.470236Z",
        "servers": null}
        """)


text:
package com.alipay.api.domain;

import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;

/**
 * 公安老赖详细失信信息对象
 *
 * @author auto create
 * @since 1.0, 2014-10-28 23:27:54
 */
public class DishonestyDetailInfo extends AlipayObject {

	private static final long serialVersionUID = 6623393897832151778L;

	/**
	 * 被执行人行为具体情况
	 */
	@ApiField("behavior")
	private String behavior;

	/**
	 * 案号
	 */
	@ApiField("case_code")
	private String caseCode;

	/**
	 * 执行法院
	 */
	@ApiField("enforce_court")
	private String enforceCourt;

	/**
	 * 身份证号
	 */
	@ApiField("id_number")
	private String idNumber;

	/**
	 * 用户姓名
	 */
	@ApiField("name")
	private String name;

	/**
	 * 被执行人履行情况
	 */
	@ApiField("performance")
	private String performance;

	/**
	 * 发布日期
	 */
	@ApiField("publish_date")
	private String publishDate;

	/**
	 * 所在区域
	 */
	@ApiField("region")
	private String region;

	public String getBehavior() {
		return this.behavior;
	}
	public void setBehavior(String behavior) {
		this.behavior = behavior;
	}

	public String getCaseCode() {
		return this.caseCode;
	}
	public void setCaseCode(String caseCode) {
		this.caseCode = caseCode;
	}

	public String getEnforceCourt() {
		return this.enforceCourt;
	}
	public void setEnforceCourt(String enforceCourt) {
		this.enforceCourt = enforceCourt;
	}

	public String getIdNumber() {
		return this.idNumber;
	}
	public void setIdNumber(String idNumber) {
		this.idNumber = idNumber;
	}

	public String getName() {
		return this.name;
	}
	public void setName(String name) {
		this.name = name;
	}

	public String getPerformance() {
		return this.performance;
	}
	public void setPerformance(String performance) {
		this.performance = performance;
	}

	public String getPublishDate() {
		return this.publishDate;
	}
	public void setPublishDate(String publishDate) {
		this.publishDate = publishDate;
	}

	public String getRegion() {
		return this.region;
	}
	public void setRegion(String region) {
		this.region = region;
	}

}


text:
package org.killbill.billing.entitlement.dao;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.killbill.billing.callcontext.InternalCallContext;
import org.killbill.billing.callcontext.InternalTenantContext;
import org.killbill.billing.entitlement.api.BlockingState;
import org.killbill.billing.entitlement.api.BlockingStateType;
import org.killbill.billing.util.audit.ChangeType;
import org.killbill.billing.util.entity.dao.Audited;
import org.killbill.billing.util.entity.dao.EntitySqlDao;
import org.killbill.commons.jdbi.binder.SmartBindBean;
import org.killbill.commons.jdbi.template.KillBillSqlDaoStringTemplate;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.SqlUpdate;

@KillBillSqlDaoStringTemplate
public interface BlockingStateSqlDao extends EntitySqlDao<BlockingStateModelDao, BlockingState> {

    @SqlQuery
    public abstract BlockingStateModelDao getBlockingStateForService(@Bind("blockableId") UUID blockableId,
                                                                     @Bind("service") String serviceName,
                                                                     @Bind("effectiveDate") Date effectiveDate,
                                                                     @SmartBindBean final InternalTenantContext context);

    @SqlQuery
    public abstract List<BlockingStateModelDao> getBlockingState(@Bind("blockableId") UUID blockableId,
                                                                 @Bind("type") BlockingStateType blockingStateType,
                                                                 @Bind("effectiveDate") Date effectiveDate,
                                                                 @SmartBindBean final InternalTenantContext context);

    @SqlQuery
    public abstract List<BlockingStateModelDao> getBlockingAllUpToForAccount(@Bind("effectiveDate") Date effectiveDate,
                                                                             @SmartBindBean final InternalTenantContext context);

    @SqlQuery
    public abstract List<BlockingStateModelDao> getBlockingHistoryForService(@Bind("blockableId") UUID blockableId,
                                                                             @Bind("service") String serviceName,
                                                                             @SmartBindBean final InternalTenantContext context);

    @SqlUpdate
    @Audited(ChangeType.DELETE)
    public void unactiveEvent(@Bind("id") String id,
                              @SmartBindBean final InternalCallContext context);
}


text:
package loga

import (
	"fmt"
	"regexp"
	"strings"

	log "github.com/Sirupsen/logrus"
	"github.com/mgutz/ansi"
)

func highlightQuery(line string, query string) {
	// Split query into multiple parts for regex
	q := strings.Split(query, " ")
	// Match the string
	match, err := regexp.Compile(q[0])
	if err != nil {
		panic(err)
	}

	// Split our line into an ary
	lineAry := strings.Split(line, " ")
	// Iterate the ary, finding the string match
	for i, s := range lineAry {
		if match.MatchString(s) {
			// Color just the string which matches
			hlQuery := ansi.Color(s, "yellow:black")
			// Thren break down into three parts
			lpt1 := lineAry[:i]
			lpt2 := lineAry[i:]
			lpt2 = append(lpt2[:0], lpt2[1:]...)
			// Contatenate back together
			part1 := strings.Join(lpt1, " ")
			part2 := strings.Join(lpt2, " ")
			final := []string{part1, hlQuery, part2}
			finalHl := strings.Join(final, " ")
			// Print the final output
			//log.Info(finalHl)
			fmt.Println(finalHl)
		}
	}
}

func setLogger(verbose bool) {
	if verbose {
		log.SetLevel(log.DebugLevel)
		log.Debug("DEBUG Logger")
	} else {
		log.SetLevel(log.InfoLevel)
	}
}


text:
require "spec_helper"
require "codility/sorting/triangle"

module Codility
  module Sorting
    RSpec.describe Triangle do
      context "when array has triangular triplet" do
        it "returns 1" do
          a = [10, 2, 5, 1, 8, 20]
          expect(Triangle.solution(a)).to eql(1)
        end
      end

      context "when array doesn't have a triangular triplet" do
        it "returns 0" do
          a = [10, 50, 5, 1]
          expect(Triangle.solution(a)).to eql(0)
        end
      end

      context "for large data set" do
        it "works fast" do
          a = []
          100000.times { a << rand(1000000) }

          time = Benchmark.realtime do
            expect([0, 1]).to include(Triangle.solution(a))
          end

          puts "Benchmark: #{time}"
        end
      end
    end
  end
end


text:
<?php

/**
 * TimelineDetail block
 *
 * @author Fabrizio Branca
 */
class Aoe_Scheduler_Block_Adminhtml_TimelineDetail extends Mage_Adminhtml_Block_Template
{

    /**
     * @var string path to default template
     */
    protected $_template = 'aoe_scheduler/timeline_detail.phtml';

    /**
     * @var Aoe_Scheduler_Model_Schedule
     */
    protected $schedule;

    /**
     * Set schedule
     *
     * @param Aoe_Scheduler_Model_Schedule $schedule
     * @return Aoe_Scheduler_Block_Adminhtml_TimelineDetail
     */
    public function setSchedule(Aoe_Scheduler_Model_Schedule $schedule)
    {
        $this->schedule = $schedule;
        return $this;
    }

    /**
     * Get schedule
     *
     * @return Aoe_Scheduler_Block_Adminhtml_TimelineDetail
     */
    public function getSchedule()
    {
        return $this->schedule;
    }
}