text:
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';

import ButtonInput from '../src/ButtonInput';

import {shouldWarn} from './helpers';

describe('ButtonInput', () => {
  it('renders an input button element with type=button', () => {
    const instance = ReactTestUtils.renderIntoDocument(
      <ButtonInput value="button" bsStyle="danger" wrapperClassName="test" />
    );

    const node = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'input');
    assert.equal(node.getAttribute('type'), 'button');
    assert.equal(node.getAttribute('class'), 'btn btn-danger');
  });

  it('supports type=reset and type=submit', () => {
    let instance = ReactTestUtils.renderIntoDocument(
      <ButtonInput value="button" type="reset" />
    );

    let node = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'input');
    assert.equal(node.getAttribute('type'), 'reset');

    instance = ReactTestUtils.renderIntoDocument(
      <ButtonInput value="button" type="submit" />
    );

    node = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'input');
    assert.equal(node.getAttribute('type'), 'submit');
  });

  it('throws warning about unsupported type', () => {
    ReactTestUtils.renderIntoDocument(
      <ButtonInput value="button" type="password" />
    );

    shouldWarn('propType: Invalid');
  });

  it('must not throw warning when bsStyle=danger', () => {
    ReactTestUtils.renderIntoDocument(
      <ButtonInput value="button" bsStyle="danger" />
    );
  });

  it('throws warning about wrong type for bsStyle=error', () => {
    ReactTestUtils.renderIntoDocument(
      <ButtonInput value="button" bsStyle="submit" />
    );

    shouldWarn('propType: Invalid');
  });

  it('throws a warning if given both children and a value property', () => {
    const testData = { value: 5, children: 'button' };
    const result = ButtonInput.propTypes.value(testData, 'value', 'ButtonInput');

    result.should.be.instanceOf(Error);
    result.message.should.have.string('value and children');
  });

  it('does not throw an error for strings and numbers', () => {
    let testData = { children: 'EUREKA' };
    let result = ButtonInput.propTypes.children(testData, 'children', 'ButtonInput');
    assert.notInstanceOf(result, Error);

    testData = { value: 4 };
    result = ButtonInput.propTypes.value(testData, 'children', 'ButtonInput');
    assert.notInstanceOf(result, Error);
  });

  it('allows elements as children', () => {
    ReactTestUtils.renderIntoDocument(
      <ButtonInput>blah</ButtonInput>
    );
  });
});


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { Comp3098Component } from './comp-3098.component';

describe('Comp3098Component', () => {
  let component: Comp3098Component;
  let fixture: ComponentFixture<Comp3098Component>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ Comp3098Component ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(Comp3098Component);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

redpajama_set_name: RedPajamaGithub


text:
package net.liftweb
package util

import scala.language.implicitConversions

trait ValueHolder {
  type ValueType

  /**
   * get the value
   */
  def get: ValueType
}

/**
 * A value that can be set
 */
trait Settable extends ValueHolder {
  def set(in: ValueType): ValueType

  /**
   * Perform an atomic update of this Settable.
   * The current value is passed to the function and the ValueHolder
   * is set to the result of the function.  This is enclosed in the
   * performAtomicOperation method which will, by default, synchronize
   * this instance
   */
  def atomicUpdate(f: ValueType => ValueType): ValueType =
    performAtomicOperation(set(f(get)))

  /**
   * Perform an atomic operation on the Settable. By default
   * synchronizes the instance, but it could use other mechanisms
   */
  def performAtomicOperation[T](f: => T): T = synchronized {
    f
  }
}

trait SettableValueHolder extends Settable

trait PValueHolder[T] extends ValueHolder {
 type ValueType = T
}

object PValueHolder {
  implicit def tToVHT[T](in: T): PValueHolder[T] = new PValueHolder[T] {def get = in; def is = get}
  def apply[T](in: T) = tToVHT(in)
}

object ValueHolder {
  implicit def tToVHT[T](in: T): ValueHolder = new PValueHolder[T] {def get = in; def is = get}
  def apply[T](in: T) = tToVHT(in)
}

trait PSettableValueHolder[T] extends PValueHolder[T] with SettableValueHolder

/**
 * Kinda like a JavaBean property.  It's something that can
 * be set and retrieved
 */
trait LiftValue[T] extends PSettableValueHolder[T] {
  def is: T = get
}


text:
""" Support for mapping python types to proto Schemas and back again.

Python              Schema
np.int8     <-----> BYTE
np.int16    <-----> INT16
np.int32    <-----> INT32
np.int64    <-----> INT64
int         ---/
np.float32  <-----> FLOAT
np.float64  <-----> DOUBLE
float       ---/
bool        <-----> BOOLEAN

The mappings for STRING and BYTES are different between python 2 and python 3,
because of the changes to str:
py3:
str/unicode <-----> STRING
bytes       <-----> BYTES
ByteString  ---/

py2:
str will be rejected since it is ambiguous.
unicode     <-----> STRING
ByteString  <-----> BYTES
"""

from __future__ import absolute_import

import sys
from typing import ByteString
from typing import Mapping
from typing import NamedTuple
from typing import Optional
from typing import Sequence
from uuid import uuid4

import numpy as np
from past.builtins import unicode

from apache_beam.portability.api import schema_pb2
from apache_beam.typehints.native_type_compatibility import _get_args
from apache_beam.typehints.native_type_compatibility import _match_is_exactly_mapping
from apache_beam.typehints.native_type_compatibility import _match_is_named_tuple
from apache_beam.typehints.native_type_compatibility import _match_is_optional
from apache_beam.typehints.native_type_compatibility import _safe_issubclass
from apache_beam.typehints.native_type_compatibility import extract_optional_type

# Registry of typings for a schema by UUID
class SchemaTypeRegistry(object):
  def __init__(self):
    self.by_id = {}
    self.by_typing = {}

  def add(self, typing, schema):
    self.by_id[schema.id] = (typing, schema)

  def get_typing_by_id(self, unique_id):
    result = self.by_id.get(unique_id, None)
    return result[0] if result is not None else None

  def get_schema_by_id(self, unique_id):
    result = self.by_id.get(unique_id, None)
    return result[1] if result is not None else None

SCHEMA_REGISTRY = SchemaTypeRegistry()

# Bi-directional mappings
_PRIMITIVES = (
    (np.int8, schema_pb2.BYTE),
    (np.int16, schema_pb2.INT16),
    (np.int32, schema_pb2.INT32),
    (np.int64, schema_pb2.INT64),
    (np.float32, schema_pb2.FLOAT),
    (np.float64, schema_pb2.DOUBLE),
    (unicode, schema_pb2.STRING),
    (bool, schema_pb2.BOOLEAN),
    (bytes if sys.version_info.major >= 3 else ByteString,
     schema_pb2.BYTES),
)

PRIMITIVE_TO_ATOMIC_TYPE = dict((typ, atomic) for typ, atomic in _PRIMITIVES)
ATOMIC_TYPE_TO_PRIMITIVE = dict((atomic, typ) for typ, atomic in _PRIMITIVES)

# One-way mappings
PRIMITIVE_TO_ATOMIC_TYPE.update({
    # In python 2, this is a no-op because we define it as the bi-directional
    # mapping above. This just ensures the one-way mapping is defined in python
    # 3.
    ByteString: schema_pb2.BYTES,
    # Allow users to specify a native int, and use INT64 as the cross-language
    # representation. Technically ints have unlimited precision, but RowCoder
    # should throw an error if it sees one with a bit width > 64 when encoding.
    int: schema_pb2.INT64,
    float: schema_pb2.DOUBLE,
})

def typing_to_runner_api(type_):
  if _match_is_named_tuple(type_):
    schema = None
    if hasattr(type_, 'id'):
      schema = SCHEMA_REGISTRY.get_schema_by_id(type_.id)
    if schema is None:
      fields = [
          schema_pb2.Field(
              name=name, type=typing_to_runner_api(type_._field_types[name]))
          for name in type_._fields
      ]
      type_id = str(uuid4())
      schema = schema_pb2.Schema(fields=fields, id=type_id)
      SCHEMA_REGISTRY.add(type_, schema)

    return schema_pb2.FieldType(
        row_type=schema_pb2.RowType(
            schema=schema))

  # All concrete types (other than NamedTuple sub-classes) should map to
  # a supported primitive type.
  elif type_ in PRIMITIVE_TO_ATOMIC_TYPE:
    return schema_pb2.FieldType(atomic_type=PRIMITIVE_TO_ATOMIC_TYPE[type_])

  elif sys.version_info.major == 2 and type_ == str:
    raise ValueError(
        "type 'str' is not supported in python 2. Please use 'unicode' or "
        "'typing.ByteString' instead to unambiguously indicate if this is a "
        "UTF-8 string or a byte array."
    )

  elif _match_is_exactly_mapping(type_):
    key_type, value_type = map(typing_to_runner_api, _get_args(type_))
    return schema_pb2.FieldType(
        map_type=schema_pb2.MapType(key_type=key_type, value_type=value_type))

  elif _match_is_optional(type_):
    # It's possible that a user passes us Optional[Optional[T]], but in python
    # typing this is indistinguishable from Optional[T] - both resolve to
    # Union[T, None] - so there's no need to check for that case here.
    result = typing_to_runner_api(extract_optional_type(type_))
    result.nullable = True
    return result

  elif _safe_issubclass(type_, Sequence):
    element_type = typing_to_runner_api(_get_args(type_)[0])
    return schema_pb2.FieldType(
        array_type=schema_pb2.ArrayType(element_type=element_type))

  raise ValueError("Unsupported type: %s" % type_)

def typing_from_runner_api(fieldtype_proto):
  if fieldtype_proto.nullable:
    # In order to determine the inner type, create a copy of fieldtype_proto
    # with nullable=False and pass back to typing_from_runner_api
    base_type = schema_pb2.FieldType()
    base_type.CopyFrom(fieldtype_proto)
    base_type.nullable = False
    return Optional[typing_from_runner_api(base_type)]

  type_info = fieldtype_proto.WhichOneof("type_info")
  if type_info == "atomic_type":
    try:
      return ATOMIC_TYPE_TO_PRIMITIVE[fieldtype_proto.atomic_type]
    except KeyError:
      raise ValueError("Unsupported atomic type: {0}".format(
          fieldtype_proto.atomic_type))
  elif type_info == "array_type":
    return Sequence[typing_from_runner_api(
        fieldtype_proto.array_type.element_type)]
  elif type_info == "map_type":
    return Mapping[
        typing_from_runner_api(fieldtype_proto.map_type.key_type),
        typing_from_runner_api(fieldtype_proto.map_type.value_type)
    ]
  elif type_info == "row_type":
    schema = fieldtype_proto.row_type.schema
    user_type = SCHEMA_REGISTRY.get_typing_by_id(schema.id)
    if user_type is None:
      from apache_beam import coders
      type_name = 'BeamSchema_{}'.format(schema.id.replace('-', '_'))
      user_type = NamedTuple(type_name,
                             [(field.name, typing_from_runner_api(field.type))
                              for field in schema.fields])
      user_type.id = schema.id
      SCHEMA_REGISTRY.add(user_type, schema)
      coders.registry.register_coder(user_type, coders.RowCoder)
    return user_type

  elif type_info == "logical_type":
    pass  # TODO

def named_tuple_from_schema(schema):
  return typing_from_runner_api(
      schema_pb2.FieldType(row_type=schema_pb2.RowType(schema=schema)))

def named_tuple_to_schema(named_tuple):
  return typing_to_runner_api(named_tuple).row_type.schema


text:
describe('Matsu Mitsuko', function() {
    integration(function() {
        describe('Matsu Mitsuko\'s ability', function() {
            beforeEach(function() {
                this.setupTest({
                    phase: 'conflict',
                    player1: {
                        inPlay: ['matsu-mitsuko','matsu-berserker','venerable-historian'],
                        honor: 11
                    },
                    player2: {
                        inPlay: ['eager-scout'],
                        honor: 10
                    }
                });

                this.mitsuko = this.player1.findCardByName('matsu-mitsuko');
                this.berzerker = this.player1.findCardByName('matsu-berserker');
                this.historian = this.player1.findCardByName('venerable-historian');

                this.scout = this.player2.findCardByName('eager-scout');
                this.noMoreActions();
            });

            it('should not work during a political conflict', function() {
                this.initiateConflict({
                    type: 'political',
                    attackers: [this.historian],
                    defenders: []
                });
                this.player2.pass();
                this.player1.clickCard(this.mitsuko);
                expect(this.player1).toHavePromptButton('Pass');
            });

            it('should work during a military conflict', function() {
                this.initiateConflict({
                    type: 'military',
                    attackers: [this.berzerker],
                    defenders: []
                });
                this.player2.pass();
                this.player1.clickCard(this.mitsuko);
                expect(this.player1).toHavePrompt('Choose a character');
            });

            it('should not work if lower honor', function() {
                this.player1.player.honor = 9;
                this.initiateConflict({
                    type: 'military',
                    attackers: [this.berzerker],
                    defenders: []
                });
                this.player2.pass();
                this.player1.clickCard(this.mitsuko);
                expect(this.player1).toHavePromptButton('Pass');
            });

            it('should not work if even honor', function() {
                this.player1.player.honor = 10;
                this.initiateConflict({
                    type: 'military',
                    attackers: [this.berzerker],
                    defenders: []
                });
                this.player2.pass();
                this.player1.clickCard(this.mitsuko);
                expect(this.player1).toHavePromptButton('Pass');
            });

            it('should correctly move the chosen character to the conflict', function() {
                this.initiateConflict({
                    type: 'military',
                    attackers: [this.berzerker],
                    defenders: []
                });
                this.player2.pass();
                this.player1.clickCard(this.mitsuko);
                expect(this.player1).toBeAbleToSelect(this.mitsuko);
                expect(this.player1).not.toBeAbleToSelect(this.berzerker);
                expect(this.player1).not.toBeAbleToSelect(this.historian);
                this.player1.clickCard(this.mitsuko);
                expect(this.mitsuko.isParticipating()).toBe(true);
            });
        });
    });
});


text:
package gov.nih.nci.system.query.hql;

import java.util.List;

import gov.nih.nci.system.query.SDKQuery;
import gov.nih.nci.system.query.hibernate.HQLCriteria;

public class DeleteHQLQuery extends HQLCriteria implements HQLManipulationQuery,SDKQuery
{
	private static final long serialVersionUID = 1L;

	public DeleteHQLQuery(String hql, List<Object> parameters) {
		super(hql, parameters);
	}

	public DeleteHQLQuery(String hql) {
		super(hql);
	}

}


text:
@interface THCameraView : UIView

@end


text:
package org.sozluk.parser

import dispatch._, Defaults._
import org.jsoup.select.Elements
import scala.collection.JavaConversions._

trait TbdParser {

  val harfs = ('A' to 'Z') :+ '1'

  private def request(harf: Char) =
    url("http://www.tbd.org.tr/index.php").GET <<? Map(
      "sayfa" -> "sozluk",
      "tipi" -> "entr",
      "harf" -> s"$harf")

  private def processResponse(response: Elements): List[(String, String)] = {
    response.map { tr =>
      val tds = tr.select("td")
      (tds(0).text.trim, tds(1).text.trim)
    }.filter {
      case (word, meaning) =>
        word.nonEmpty && meaning.nonEmpty
    }.toList
  }

  def parse(harf: Char): Future[Either[Throwable, List[(String, String)]]] =
    Http(request(harf) OK as.jsoup.Query("tr.sozlukSatir")).either.right.map(processResponse)
}


text:
{{pageTitle}}

{{if:!hasPage}}

	<form action="{{fullPath}}{{queryString}}" method="post" id="pageUpdateSelect">
		<fieldset>
			Edit Page
			<select name="pageId" id="pageId" require>
				<option value="0">Select a page</option>
				{{pages}}
			</select>
			<button type="submit" value="Edit" id="editButton" class="submit">

				Edit
			</button>
		</fieldset>
	</form>

{{/if:!hasPage}}

	<form action="{{fullPath}}{{queryString}}" method="post" id="pageUpdate">
		<fieldset>
			<legend>{{formLabel}}</legend>
			{{formFeedback}}
			{{if:!isWriteable}}

				Notice: Unable to save or edit page contents in
				{{contentPath}}, please make this directory writeable.

			{{/if:!isWriteable}}

				Title
				<input name="title" type="text" id="title" class="text required" tabindex="1" value="{{title}}">

				URI
				<input name="uri" type="text" id="uri" class="text required {{readOnly}}" {{readOnly}} tabindex="2" value="{{uri}}">
				{{if:readOnly}}
					<input name="uri" type="hidden" value="{{uri}}">
				{{/if:readOnly}}

			{{if:isWriteable}}

				Content
				<textarea name="content" id="pageContent" tabindex="3" class="editable large">{{pageContent}}</textarea>

			{{/if:isWriteable}}

				Keywords
				<textarea name="keywords" id="keywords" tabindex="4">{{keywords}}</textarea>

				Description
				<textarea name="description" id="description" tabindex="5">{{description}}</textarea>

				Privilege
				<select id="privilege" name="privilege" class="required {{readOnly}}" {{readOnly}} tabindex="6">
					{{privileges}}
				</select>

				Is Dynamic
				<input name="isDynamic" type="checkbox" class="checkbox" value="1" id="isDynamic" {{isDynamic}} tabindex="7">
				Page location can have appending URI elements

				Cache
				<input name="cache" type="checkbox" class="checkbox" value="1" id="cache" {{cache}} tabindex="8">
				Always cache the page

			{{if:!readOnly}}

				Parent
				<select name="parentId" id="parentId" tabindex="9">
					<option value="0">No Parent</option>
					{{parentId}}
				</select>

				Redirect
				<select name="redirectId" id="redirectId" tabindex="10">
					<option value="0">Don't Redirect</option>
					{{redirectId}}
				</select>

			{{/if:!readOnly}}

				{{if:!hasPage}}
					<button type="submit" value="add" class="submit" name="action" tabindex="11">

						Add
					</button>
				{{/if:!hasPage}}
				{{if:hasPage}}
					<button type="submit" value="update" class="submit" name="action" tabindex="11">

						Update
					</button>

						Cancel

				{{/if:hasPage}}
				{{if:showDelete}}
					<button type="submit" value="remove" class="submit confirm" name="action" tabindex="12">

						Delete
					</button>
				{{/if:showDelete}}
				<input type="hidden" name="id" value="{{id}}">
				<input type="hidden" name="form" value="Canteen\Forms\PageUpdate">
				<input type="hidden" name="formSession" value="{{formSession}}">

		</fieldset>
	</form>


text:
<?php

namespace OjUserRbacDoctrineORM\Entity;

use ZfcUser\Entity\UserInterface;

trait UserRoleLinkerTrait
{
    /**
     * @var UserInterface
     */
    protected $user;

    /**
     * @var string $roleId    Role
     */
    protected $roleId;

    /**
     * Constructor
     *
     * @param UserInterface|null $user
     * @param string|null        $roleId
     */
    public function __construct(UserInterface $user = null, $roleId = null)
    {
        if ($user) {
            $this->setUser($user);
        }
        if ($roleId) {
            $this->setRoleId($roleId);
        }
    }

    /**
     * Sets user
     *
     * @param  UserInterface $user
     * @return self
     */
    public function setUser(UserInterface $user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Gets user
     *
     * @return UserInterface
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * Sets role
     *
     * @param  string $roleId
     * @return self
     */
    public function setRoleId($roleId)
    {
        $this->roleId = $roleId;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function getRoleId()
    {
        return $this->roleId;
    }
}


text:
{%extends 'product/base.html' %}

{% load crispy_forms_tags i18n %}

{% block breadcrumbs_rows %}
    {% if object %}

{{ object }}

{% trans 'Zmień' %}

    {% else %}

{% trans 'Dodaj' %}

    {% endif %}
{% endblock %}

{% block content %}
    {% crispy form %}
{% endblock content %}

{% block javascript %}
    {{ form.media }}

{% endblock javascript %}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>QUnit Testing</title>
  <link rel="stylesheet" href="css/qunit-1.18.0.css">


text:
require 'memoist'
require 'ancestry'

module RelationshipMixin
  extend ActiveSupport::Concern

  MEMOIZED_METHODS = [
    :relationships_of,
    :parents,              :parent_rels,
    :root,                 :root_rel,
    :ancestors,            :ancestor_rels,
    :path,                 :path_rels,
    :siblings,             :sibling_rels,
    :has_siblings?,        :is_only_child?,
    :children,             :child_rels,
    :has_children?,        :is_childless?,
    :descendants,          :descendant_rels,
    :descendants_arranged, :descendant_rels_arranged,
    :subtree,              :subtree_rels,
    :subtree_arranged,     :subtree_rels_arranged,
    :fulltree,             :fulltree_rels,
    :fulltree_arranged,    :fulltree_rels_arranged,
    :parent_rel_ids,
  ]

  included do
    extend Memoist

    class_attribute :default_relationship_type
    class_attribute :skip_relationships, :default => []

    has_many :all_relationships, :class_name => "Relationship", :dependent => :destroy, :as => :resource

    memoize(*MEMOIZED_METHODS)
  end

  module ClassMethods
    def alias_with_relationship_type(m_new, m_old, rel_type = nil)
      define_method(m_new) do |*args|
        with_relationship_type(rel_type || default_relationship_type) { send(m_old, *args) }
      end
    end
  end

  def reload(*args)
    clear_relationships_cache
    super
  end

  # only used from specs
  def clear_relationships_cache(*args)
    options = args.extract_options!
    to_clear = RelationshipMixin::MEMOIZED_METHODS - Array.wrap(options[:except])
    flush_cache(*to_clear) unless to_clear.empty?

    @association_cache.delete(:all_relationships)
  end

  def use_ancestry?
    skip_relationships.include?(relationship_type)
  end

  #
  # relationship_type scoping methods
  #

  def relationship_types
    @relationship_types ||= []
  end

  def relationship_type
    relationship_types.blank? ? default_relationship_type : relationship_types.last
  end

  def relationship_type=(rel)
    unless relationship_type == rel
      relationship_types.push(rel)
      clear_relationships_cache(:except => :relationships_of)
    end
    rel
  end

  def with_relationship_type(rel)
    raise _("no block given") unless block_given?

    rel = rel.to_s
    rel_changed = rel && (relationship_type != rel)
    self.relationship_type = rel unless rel.nil?

    begin
      yield(self)
    ensure
      if rel_changed
        relationship_types.pop
        clear_relationships_cache(:except => :relationships_of)
      end
    end
  end

  def relationships_of(rel_type)
    if @association_cache.include?(:all_relationships)
      all_relationships.select { |r| r.relationship == rel_type }
    else
      all_relationships.in_relationship(rel_type)
    end
  end

  def relationships
    relationships_of(relationship_type)
  end

  def relationship_ids
    relationships.collect(&:id)
  end

  #
  # has_ancestry methods
  #

  # Returns the id in the relationship table for this record's parents
  # from this id, relationship records can be brought back and mapped to the resource of interest
  # NOTE: parent_id is read from ancestry field, while parent is a db hit (N+1)
  # NOTE: relationships can be an array (from all_relationships cache) - so handle both Array and association
  def parent_rel_ids
    rel = relationships
    if rel.kind_of?(Array) || rel.try(:loaded?)
      rel.reject { |x| x.ancestry.blank? }.collect(&:parent_id)
    else
      rel.where.not(:ancestry => [nil, ""]).select(:ancestry).collect(&:parent_id)
    end
  end

  # Returns all of the relationships of the parents of the record, [] for a root node
  def parent_rels(*args)
    options = args.extract_options!
    pri = parent_rel_ids
    rels = pri.kind_of?(Array) && pri.empty? ? Relationship.none : Relationship.where(:id => pri)
    Relationship.filter_by_resource_type(rels, options)
  end

  # Returns all of the parents of the record, [] for a root node
  def parents(*args)
    Relationship.resources(parent_rels(*args))
  end

  # Returns all of the class/id pairs of the parents of the record, [] for a root node
  def parent_ids(*args)
    return Array.wrap(parent_id(*args)) if use_ancestry?

    Relationship.resource_pairs(parent_rels(*args))
  end

  # Returns the number of parents of the record
  def parent_count(*args)
    parent_rels(*args).size
  end

  # Returns the relationship of the parent of the record, nil for a root node
  def parent_rel(*args)
    rels = parent_rels(*args).take(2)
    raise _("Multiple parents found.") if rels.length > 1
    rels.first
  end

  # Returns the parent of the record, nil for a root node
  def parent(*args)
    return call_ancestry_method(:parent) if use_ancestry?

    rels = parent_rels(*args).take(2)
    raise _("Multiple parents found.") if rels.length > 1
    rels.first.try(:resource)
  end

  # Returns the class/id pair of the parent of the record, nil for a root node
  def parent_id(*args)
    return call_ancestry_method(:parent_id) if use_ancestry?

    rels = parent_ids(*args).take(2)
    raise _("Multiple parents found.") if rels.length > 1
    rels.first
  end

  # Returns the relationship of the root of the tree the record is in
  def root_rel
    rel = relationship.try!(:root)
    # micro-optimization: if the relationship is us, "load" the resource
    rel.resource = self if rel && rel.resource_id == id && rel.resource_type == self.class.base_class.name.to_s
    rel || relationship_for_isolated_root
  end

  # Returns the root of the tree the record is in, self for a root node
  def root(*args)
    return call_ancestry_method(:root) if use_ancestry?

    Relationship.resource(root_rel(*args))
  end

  # Returns the id of the root of the tree the record is in
  def root_id(*args)
    return call_ancestry_method(:root_id) if use_ancestry?

    Relationship.resource_pair(root_rel(*args))
  end

  # Returns true if the record is a root node, false otherwise
  def is_root?
    return call_ancestry_method(:is_root?) if use_ancestry?

    rel = relationship # TODO: Handle a node that is a root and a node at the same time
    rel.nil? ? true : rel.is_root?
  end

  # Returns a relationship for a record that is a root node with no corresponding
  #   relationship record, meaning it is an isolated root node
  def relationship_for_isolated_root
    Relationship.new(:resource => self)
  end
  private :relationship_for_isolated_root

  # Returns a list of ancestor relationships, starting with the root relationship
  #   and ending with the parent relationship
  def ancestor_rels(*args)
    options = args.extract_options!
    rel = relationship(:raise_on_multiple => true) # TODO: Handle multiple nodes with a way to detect which node you want
    rels = rel.nil? ? [] : rel.ancestors
    Relationship.filter_by_resource_type(rels, options)
  end

  # Returns a list of ancestor records, starting with the root record and ending
  #   with the parent record
  def ancestors(*args)
    return call_ancestry_method(:ancestors) if use_ancestry?

    Relationship.resources(ancestor_rels(*args))
  end

  # Returns a list of ancestor class/id pairs, starting with the root class/id
  #   and ending with the parent class/id
  def ancestor_ids(*args)
    return call_ancestry_method(:ancestor_ids) if use_ancestry?

    Relationship.resource_pairs(ancestor_rels(*args))
  end

  # Returns the number of ancestor records
  def ancestors_count(*args)
    ancestor_rels(*args).size
  end

  # Returns a list of the path relationships, starting with the root relationship
  #   and ending with the node's own relationship
  def path_rels(*args)
    options = args.extract_options!
    rel = relationship(:raise_on_multiple => true) # TODO: Handle multiple nodes with a way to detect which node you want
    rels = rel.nil? ? [relationship_for_isolated_root] : rel.path
    Relationship.filter_by_resource_type(rels, options)
  end

  # Returns a list of the path records, starting with the root record and ending
  #   with the node's own record
  def path(*args)
    return call_ancestry_method(:path) if use_ancestry?

    Relationship.resources(path_rels(*args)) # TODO: Prevent preload of self which is in the list
  end

  # Returns a list of the path class/id pairs, starting with the root class/id
  #   and ending with the node's own class/id
  def path_ids(*args)
    return call_ancestry_method(:path_ids) if use_ancestry?

    Relationship.resource_pairs(path_rels(*args))
  end

  # Returns the number of records in the path
  def path_count(*args)
    path_rels(*args).size
  end

  # Returns a list of child relationships
  def child_rels(*args)
    options = args.extract_options!
    rels = relationships.flat_map(&:children).uniq
    Relationship.filter_by_resource_type(rels, options)
  end

  # Returns a list of child records
  def children(*args)
    return call_ancestry_method(:children) if use_ancestry?

    Relationship.resources(child_rels(*args))
  end

  # Returns a list of child class/id pairs
  def child_ids(*args)
    return call_ancestry_method(:child_ids) if use_ancestry?

    Relationship.resource_pairs(child_rels(*args))
  end

  # Returns the number of child records
  def child_count(*args)
    child_rels(*args).size
  end

  # Returns true if the record has any children, false otherwise
  def has_children?
    return call_ancestry_method(:has_children?) if use_ancestry?

    relationships.any?(&:has_children?)
  end

  # Returns true if the record has no children, false otherwise
  def is_childless?
    return call_ancestry_method(:is_childless?) if use_ancestry?

    relationships.all?(&:is_childless?)
  end

  # Returns a list of sibling relationships
  def sibling_rels(*args)
    options = args.extract_options!
    rels = relationships.flat_map(&:siblings).uniq
    Relationship.filter_by_resource_type(rels, options)
  end

  # Returns a list of sibling records
  def siblings(*args)
    return call_ancestry_method(:siblings) if use_ancestry?

    Relationship.resources(sibling_rels(*args))
  end

  # Returns a list of sibling class/id pairs
  def sibling_ids(*args)
    return call_ancestry_method(:sibling_ids) if use_ancestry?

    Relationship.resource_pairs(sibling_rels(*args))
  end

  # Returns the number of sibling records
  def sibling_count(*args)
    sibling_rels(*args).size
  end

  # Returns true if the record's parent has more than one child
  def has_siblings?
    return call_ancestry_method(:has_siblings?) if use_ancestry?

    relationships.any?(&:has_siblings?)
  end

  # Returns true if the record is the only child of its parent
  def is_only_child?
    return call_ancestry_method(:is_only_child?) if use_ancestry?

    relationships.all?(&:is_only_child?)
  end

  # Returns a list of descendant relationships
  def descendant_rels(*args)
    options = args.extract_options!
    rels = relationships.flat_map(&:descendants).uniq
    Relationship.filter_by_resource_type(rels, options)
  end

  # Returns a list of descendant records
  def descendants(*args)
    return call_ancestry_method(:descendants) if use_ancestry?

    Relationship.resources(descendant_rels(*args))
  end

  # Returns a list of descendant class/id pairs
  def descendant_ids(*args)
    return call_ancestry_method(:descendant_ids) if use_ancestry?

    Relationship.resource_pairs(descendant_rels(*args))
  end

  # Returns the number of descendant records
  def descendant_count(*args)
    descendant_rels(*args).size
  end

  # Returns the descendant relationships arranged in a tree
  def descendant_rels_arranged(*args)
    options = args.extract_options!
    rel = relationship(:raise_on_multiple => true)
    return {} if rel.nil?  # TODO: Should this return nil or init_relationship or Relationship.new in a Hash?
    Relationship.filter_by_resource_type(rel.descendants, options).arrange
  end

  # Returns the descendant class/id pairs arranged in a tree
  def descendant_ids_arranged(*args)
    Relationship.arranged_rels_to_resource_pairs(descendant_rels_arranged(*args))
  end

  # Returns the descendant records arranged in a tree
  def descendants_arranged(*args)
    Relationship.arranged_rels_to_resources(descendant_rels_arranged(*args))
  end

  # Returns a list of all relationships in the record's subtree
  def subtree_rels(*args)
    options = args.extract_options!
    # TODO: make this a single query (vs 3)
    # thus making filter_by_resource_type into a query
    rels = relationships.flat_map(&:subtree).uniq
    rels = [relationship_for_isolated_root] if rels.empty?
    Relationship.filter_by_resource_type(rels, options)
  end

  # Returns a list of all records in the record's subtree
  def subtree(*args)
    return call_ancestry_method(:subtree) if use_ancestry?

    Relationship.resources(subtree_rels(*args)) # TODO: Prevent preload of self which is in the list
  end

  # Returns a list of all class/id pairs in the record's subtree
  def subtree_ids(*args)
    return call_ancestry_method(:subtree_ids) if use_ancestry?

    Relationship.resource_pairs(subtree_rels(*args))
  end

  # Returns the number of records in the record's subtree
  def subtree_count(*args)
    subtree_rels(*args).size
  end

  # Returns the subtree relationships arranged in a tree
  def subtree_rels_arranged(*args)
    options = args.extract_options!
    rel = relationship(:raise_on_multiple => true)
    return {relationship_for_isolated_root => {}} if rel.nil?
    Relationship.filter_by_resource_type(rel.subtree, options).arrange
  end

  # Returns the subtree class/id pairs arranged in a tree
  def subtree_ids_arranged(*args)
    Relationship.arranged_rels_to_resource_pairs(subtree_rels_arranged(*args))
  end

  # Returns the subtree records arranged in a tree
  def subtree_arranged(*args)
    Relationship.arranged_rels_to_resources(subtree_rels_arranged(*args))
  end

  def grandchild_rels(*args)
    options = args.extract_options!
    rels = relationships.inject(Relationship.none) do |stmt, r|
      stmt.or(r.grandchildren)
    end
    Relationship.filter_by_resource_type(rels, options)
  end

  def grandchildren(*args)
    Relationship.resources(grandchild_rels(*args))
  end

  def child_and_grandchild_rels(*args)
    options = args.extract_options!
    rels = relationships.inject(Relationship.none) do |stmt, r|
      stmt.or(r.child_and_grandchildren)
    end
    Relationship.filter_by_resource_type(rels, options)
  end

  # Return the depth of the node, root nodes are at depth 0
  def depth
    return call_ancestry_method(:depth) if use_ancestry?

    rel = relationship(:raise_on_multiple => true) # TODO: Handle multiple nodes with a way to detect which node you want
    rel.nil? ? 0 : rel.depth
  end

  #
  # Other methods
  #

  # Returns the relationship node for this record.  If there are multiple nodes,
  #   the first is returned, unless :raise_on_multiple is passed as true.
  def relationship(*args)
    options = args.extract_options!
    if options[:raise_on_multiple]
      rels = relationships.take(2)
      raise _("Multiple relationships found") if rels.length > 1
      rels.first
    else
      relationships.first
    end
  end

  # Adds a new relationship for this node
  def add_relationship(parent_rel = nil)
    clear_relationships_cache
    all_relationships.create!(
      :relationship => (parent_rel.nil? ? relationship_type : parent_rel.relationship),
      :parent       => parent_rel
    )
  end

  # Returns an existing relationship if found, otherwise creates a new one
  #   If parent_rel is passed, also connects the returned relationship to the
  #   parent, possibly delinking from an existing parent.
  def init_relationship(parent_rel = nil)
    rel = relationship
    if rel.nil?
      rel = add_relationship(parent_rel)
    elsif !parent_rel.nil?
      rel.update_attribute(:parent, parent_rel)
    end
    rel
  end

  # Returns a String form of the ancestor class/id pairs of the record
  #   Accepts the usual options, plus the options for Relationship.stringify_*,
  #   as well as :include_self which defaults to false.
  def relationship_ancestry(*args)
    stringify_options = args.extract_options!
    options = stringify_options.slice!(:field_delimiter, :record_delimiter, :exclude_class, :field_method, :include_self)

    include_self = stringify_options.delete(:include_self)
    field_method = stringify_options[:field_method] || :id

    meth = include_self ? :path : :ancestors
    meth = :"#{meth.to_s.singularize}_ids" if field_method == :id
    rels = send(meth, options)

    rels_meth = :"stringify_#{field_method == :id ? "resource_pairs" : "rels"}"
    Relationship.send(rels_meth, rels, stringify_options)
  end

  # Returns a list of all relationships in the tree from the root
  def fulltree_rels(*args)
    options = args.extract_options!
    root_id = relationship.try(:root_id)
    rels = root_id ? Relationship.subtree_of(root_id).uniq : [relationship_for_isolated_root]
    Relationship.filter_by_resource_type(rels, options)
  end

  # Returns a list of all records in the tree from the root
  def fulltree(*args)
    Relationship.resources(fulltree_rels(*args)) # TODO: Prevent preload of self which is in the list
  end

  # Returns a list of all class/id pairs in the tree from the root
  def fulltree_ids(*args)
    Relationship.resource_pairs(fulltree_rels(*args))
  end

  # Returns the number of records in the tree from the root
  def fulltree_count(*args)
    fulltree_rels(*args).size
  end

  # Returns the relationships in the tree from the root arranged in a tree
  def fulltree_rels_arranged(*args)
    options = args.extract_options!
    root_id = relationship.try(:root_id)
    return {relationship_for_isolated_root => {}} if root_id.nil?
    Relationship.filter_by_resource_type(Relationship.subtree_of(root_id), options).arrange
  end

  # Returns the class/id pairs in the tree from the root arranged in a tree
  def fulltree_ids_arranged(*args)
    Relationship.arranged_rels_to_resource_pairs(fulltree_rels_arranged(*args))
  end

  # Returns the records in the tree from the root arranged in a tree
  def fulltree_arranged(*args)
    Relationship.arranged_rels_to_resources(fulltree_rels_arranged(*args))
  end

  # Returns a list of all unique child types
  def child_types(*args)
    Relationship.resource_types(child_rels(*args))
  end

  def add_parent(parent)
    return update(:parent => parent) if use_ancestry?

    parent.with_relationship_type(relationship_type) { parent.add_child(self) }
  end

  def add_children(*child_objs)
    return child_objs.each { |child| child.with_relationship_type(relationship_type) { child.update!(:parent => self) } } if use_ancestry?

    options = child_objs.extract_options!
    child_objs = child_objs.flatten

    # Determine which child relationships already exist
    unless options[:skip_check] || (child_ids = self.child_ids).empty?
      child_objs = child_objs.reject { |c| child_ids.include?([c.class.base_class.name, c.id]) }
    end

    return child_objs if child_objs.empty?

    # Add the child relationships that do not already exist
    Relationship.transaction do
      parent_rel = init_relationship
      child_objs.each do |c|
        c.with_relationship_type(relationship_type) do
          # init_relationship will de-link from an existing parent, so if the
          #   child is already connected to a parent, we just want add a new
          #   child relationship, creating a duplicate node in the tree.  However,
          #   if the child is a root, we want to use init_relationship to link
          #   to the new parent directly to avoid creating multiple roots in the
          #   tree.
          c.send(c.is_root? ? :init_relationship : :add_relationship, parent_rel)
        end
      end
    end

    child_objs.each(&:clear_relationships_cache)
    clear_relationships_cache

    child_objs
  end
  alias_method :add_child, :add_children

  def parent=(parent)
    if use_ancestry?
      call_ancestry_method(:parent=, parent)
      return
    end

    if parent.nil?
      remove_all_parents
    else
      parent.with_relationship_type(relationship_type) do
        parent_rel = parent.init_relationship
        init_relationship(parent_rel)  # TODO: Deal with any multi-instances

        parent.clear_relationships_cache
      end
    end

    clear_relationships_cache
  end
  alias_method :replace_parent, :parent=

  #
  # Backward compatibility methods
  #

  alias_method :set_parent, :parent=
  alias_method :set_child,  :add_children

  def replace_children(*child_objs)
    child_objs = child_objs.flatten
    return remove_all_children if child_objs.empty?

    # Determine which child relationships should be destroyed, already exist, or should be added
    child_rels = self.child_rels

    child_rel_ids = child_rels.collect(&:resource_pair)
    child_obj_ids = child_objs.collect { |c| [c.class.base_class.name, c.id] }

    to_del = child_rel_ids - child_obj_ids
    to_del = child_rels.select { |r| to_del.include?(r.resource_pair) }

    to_add = child_obj_ids - child_rel_ids
    to_add, to_keep = child_objs.partition { |c| to_add.include?([c.class.base_class.name, c.id]) }

    Relationship.transaction do
      to_keep.each(&:clear_relationships_cache)
      remove_all_relationships(to_del)
      add_children(to_add, :skip_check => true)
    end
  end

  def remove_parent(parent)
    return update!(:parent => nil) if use_ancestry?

    parent.with_relationship_type(relationship_type) { parent.remove_child(self) }
  end

  def remove_children(*child_objs)
    child_objs = child_objs.flatten.compact
    return child_objs if child_objs.empty?

    return child_objs.each { |child| child.with_relationship_type(relationship_type) { child.update!(:parent => nil) } } if use_ancestry?

    child_rels = self.child_rels

    # Determine which child relationships should be destroyed or already exist
    child_obj_ids = child_objs.collect { |c| [c.class.base_class.name, c.id] }
    to_del, to_keep = child_rels.partition { |r| child_obj_ids.include?(r.resource_pair) }

    child_objs.each(&:clear_relationships_cache)
    if to_keep.empty?
      remove_all_children
    else
      remove_all_relationships(to_del)
    end
  end
  alias_method :remove_child, :remove_children

  def remove_all_parents(*args)
    return update!(:parent => nil) if use_ancestry?

    parents(*args).collect { |p| remove_parent(p) }
  end

  def remove_all_children(*args)
    # Determine if we are removing all or some children
    options = args.last.kind_of?(Hash) ? args.last : {}
    of_type = Array.wrap(options[:of_type])
    all_children_removed = of_type.empty? || (child_types - of_type).empty?

    if self.is_root? && all_children_removed
      remove_all_relationships
    else
      remove_all_relationships(child_rels(*args))
    end
  end

  def remove_all_relationships(*rels)
    rels = relationships if rels.empty?
    rels = rels.first if rels.length == 1 && rels.first.kind_of?(Array)

    unless rels.empty?
      Relationship.transaction do
        rels.each(&:destroy)
      end
      clear_relationships_cache
    end
    rels
  end

  def is_descendant_of?(obj)
    return call_ancestry_method(:descendant_of?, obj) if use_ancestry?

    ancestor_ids.include?([obj.class.base_class.name, obj.id])
  end

  def is_ancestor_of?(obj)
    return obj.with_relationship_type(relationship_type) { obj.descendant_of?(self) } if use_ancestry?

    descendant_ids.include?([obj.class.base_class.name, obj.id])
  end

  def detect_ancestor(*args, &block)
    ancestors(*args).reverse.detect(&block)
  end

  #
  # Diagnostic methods
  #

  def puts_relationship_tree
    Relationship.puts_arranged_resources(subtree_arranged)
  end

  private

  # this allows us to call similarly named ancestry or mixin methods
  def call_ancestry_method(method_name, *args)
    bound_method = ((@ancestry_method ||= {})[method_name] ||= ::Ancestry::InstanceMethods.instance_method(method_name)).bind(self)
    args.empty? ? bound_method.call : bound_method.call(*args)
  end
end


text:
//
//  NSError+RFWebService.h
//  ROADWebService
//
//  Copyright (c) 2014 EPAM Systems, Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//  Redistributions of source code must retain the above copyright notice, this
//  list of conditions and the following disclaimer.
//  Redistributions in binary form must reproduce the above copyright notice, this
//  list of conditions and the following disclaimer in the documentation and/or
//  other materials provided with the distribution.
//  Neither the name of the EPAM Systems, Inc.  nor the names of its contributors
//  may be used to endorse or promote products derived from this software without
//  specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
//  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
//  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
//  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
//  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//  See the NOTICE file and the LICENSE file distributed with this work
//  for additional information regarding copyright ownership and licensing

extern NSString * const kRFWebServiceErrorDomain;
extern NSString * const kRFWebServiceRecievedDataKey;
extern NSString * const kRFWebServiceCancellationReason;

extern const NSInteger kRFWebServiceErrorCodeSerialization;
extern const NSInteger kRFWebServiceErrorCodeCancel;

@interface NSError (RFWebService)
/**
 * Create deserialization error, and insert the original data into the error userinfo.
 * @param data The original data.
 * @return The error with deserialization code and received data.
 */
+ (NSError *)RFWS_deserializationErrorWithData:(NSData *)data;

/**
 * Create cancel error for cancelled web service calls.
 * @return The error with cancellation code.
 */
+ (NSError *)RFWS_cancelError;

/**
 * Create cancel error for cancelled web service calls with reason.
 * @param reason An any reason why web service call will be cancelled. Will be passed to user in userInfo dictionary with kRFWebServiceCancellationReason key.
 * @return The error with cancellation reason.
 */
+ (NSError *)RFWS_cancelErrorWithReason:(id)reason;

@end


text:
package org.tuxdevelop.spring.batch.lightmin.event;

import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.StepExecution;
import org.tuxdevelop.spring.batch.lightmin.api.resource.monitoring.JobExecutionEventInfo;
import org.tuxdevelop.spring.batch.lightmin.api.resource.monitoring.StepExecutionEventInfo;
import org.tuxdevelop.spring.batch.lightmin.client.api.BatchToResourceMapper;

public final class EventTransformer {

    private EventTransformer() {
    }

    public static JobExecutionEventInfo transformToJobExecutionEventInfo(final JobExecution jobExecution, final String applicationName) {
        final JobExecutionEventInfo jobExecutionEventInfo = new JobExecutionEventInfo();
        jobExecutionEventInfo.setApplicationName(applicationName);
        jobExecutionEventInfo.setExitStatus(BatchToResourceMapper.map(jobExecution.getExitStatus()));
        jobExecutionEventInfo.setStartDate(jobExecution.getStartTime());
        jobExecutionEventInfo.setEndDate(jobExecution.getEndTime());
        jobExecutionEventInfo.setJobExecutionId(jobExecution.getId());
        jobExecutionEventInfo.setJobName(jobExecution.getJobInstance().getJobName());
        return jobExecutionEventInfo;
    }

    public static StepExecutionEventInfo transformToStepExecutionEventInfo(final StepExecution stepExecution, final String applicationName) {
        final StepExecutionEventInfo stepExecutionEventInfo = new StepExecutionEventInfo();
        stepExecutionEventInfo.setApplicationName(applicationName);

        stepExecutionEventInfo.setJobName(stepExecution.getJobExecution().getJobInstance().getJobName());
        stepExecutionEventInfo.setStepName(stepExecution.getStepName());
        stepExecutionEventInfo.setExitStatus(BatchToResourceMapper.map(stepExecution.getExitStatus()));

        stepExecutionEventInfo.setReadCount(stepExecution.getReadCount());
        stepExecutionEventInfo.setWriteCount(stepExecution.getWriteCount());
        stepExecutionEventInfo.setCommitCount(stepExecution.getCommitCount());
        stepExecutionEventInfo.setRollbackCount(stepExecution.getRollbackCount());
        stepExecutionEventInfo.setReadSkipCount(stepExecution.getReadSkipCount());
        stepExecutionEventInfo.setProcessSkipCount(stepExecution.getProcessSkipCount());
        stepExecutionEventInfo.setWriteSkipCount(stepExecution.getWriteSkipCount());
        return stepExecutionEventInfo;
    }
}


text:
from __future__ import unicode_literals, division, absolute_import
from builtins import *  # pylint: disable=unused-import, redefined-builtin

import hashlib
import logging
import random
import socket
import threading

import cherrypy
import safe
from flask import Flask, abort, redirect
from flask_login import UserMixin
from sqlalchemy import Column, Integer, Unicode
from werkzeug.security import generate_password_hash

from flexget.config_schema import register_config_key
from flexget.event import event
from flexget.manager import Base
from flexget.utils.database import with_session
from flexget.utils.tools import singleton

log = logging.getLogger('web_server')

_home = None
_app_register = {}
_default_app = Flask(__name__)

random = random.SystemRandom()

web_config_schema = {
    'oneOf': [
        {'type': 'boolean'},
        {
            'type': 'object',
            'properties': {
                'bind': {'type': 'string', 'format': 'ipv4', 'default': '0.0.0.0'},
                'port': {'type': 'integer', 'default': 3539},
                'ssl_certificate': {'type': 'string', 'format': 'string', 'default': ''},
                'ssl_private_key': {'type': 'string', 'format': 'string', 'default': ''},
            },
            'additionalProperties': False,
            'dependencies': {
                'ssl_certificate': ['ssl_private_key'],
                'ssl_private_key': ['ssl_certificate'],
            }
        }
    ]
}

def generate_key():
    """ Generate key for use to authentication """
    return str(hashlib.sha224(str(random.getrandbits(128)).encode('utf-8')).hexdigest())

def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits.

    Taken from the django.utils.crypto module.
    """
    return ''.join(random.choice(allowed_chars) for __ in range(length))

@with_session
def get_secret(session=None):
    """ Generate a secret key for flask applications and store it in the database. """
    web_secret = session.query(WebSecret).first()
    if not web_secret:
        web_secret = WebSecret(id=1, value=get_random_string(50, 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'))
        session.add(web_secret)
        session.commit()

    return web_secret.value

class WeakPassword(Exception):
    def __init__(self, value, logger=log, **kwargs):
        super(WeakPassword, self).__init__()
        # Value is expected to be a string
        if not isinstance(value, str):
            value = str(value)
        self.value = value
        self.log = logger
        self.kwargs = kwargs

    def __str__(self):
        return str(self).encode('utf-8')

    def __unicode__(self):
        return str(self.value)

class User(Base, UserMixin):
    """ User class available for flask apps to handle authentication using flask_login """
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(Unicode(50), unique=True)
    token = Column(Unicode, default=generate_key)
    password = Column(Unicode)

    def __repr__(self):
        return '<User %r>' % self.name

    def get_id(self):
        return self.name

class WebSecret(Base):
    """ Store flask secret in the database """
    __tablename__ = 'secret'

    id = Column(Unicode, primary_key=True)
    value = Column(Unicode)

@event('config.register')
def register_config():
    register_config_key('web_server', web_config_schema)

def register_app(path, application):
    if path in _app_register:
        raise ValueError('path %s already registered')
    _app_register[path] = application

def register_home(route):
    """Registers UI home page"""
    global _home
    _home = route

@_default_app.route('/')
def start_page():
    """ Redirect user to registered UI home """
    if not _home:
        abort(404)
    return redirect(_home)

@event('manager.daemon.started', -255)  # Low priority so plugins can register apps
@with_session
def setup_server(manager, session=None):
    """ Sets up and starts/restarts the web service. """
    if not manager.is_daemon:
        return

    web_server_config = manager.config.get('web_server')

    if not web_server_config:
        return

    web_server = WebServer(
        bind=web_server_config['bind'],
        port=web_server_config['port'],
        ssl_certificate=web_server_config['ssl_certificate'],
        ssl_private_key=web_server_config['ssl_private_key'],
    )

    _default_app.secret_key = get_secret()

    user = get_user()
    if not user or not user.password:
        log.warning('No password set for web server, create one by using'
                    ' `flexget web passwd <password>`')

    if web_server.is_alive():
        web_server.stop()

    if _app_register:
        web_server.start()

@event('manager.shutdown')
def stop_server(manager):
    """ Sets up and starts/restarts the webui. """
    if not manager.is_daemon:
        return
    web_server = WebServer()
    if web_server.is_alive():
        web_server.stop()

@singleton
class WebServer(threading.Thread):
    # We use a regular list for periodic jobs, so you must hold this lock while using it
    triggers_lock = threading.Lock()

    def __init__(self, bind='0.0.0.0', port=5050, ssl_certificate=None, ssl_private_key=None):
        threading.Thread.__init__(self, name='web_server')
        self.bind = str(bind)  # String to remove unicode warning from cherrypy startup
        self.port = port
        self.ssl_certificate = ssl_certificate
        self.ssl_private_key = ssl_private_key

    def start(self):
        # If we have already started and stopped a thread, we need to reinitialize it to create a new one
        if not self.is_alive():
            self.__init__(bind=self.bind, port=self.port, ssl_certificate=self.ssl_certificate, ssl_private_key=self.ssl_private_key)
        threading.Thread.start(self)

    def _start_server(self):
        # Mount the WSGI callable object (app) on the root directory
        cherrypy.tree.graft(_default_app, '/')
        for path, registered_app in _app_register.items():
            cherrypy.tree.graft(registered_app, path)

        cherrypy.log.error_log.propagate = False
        cherrypy.log.access_log.propagate = False

        # Set the configuration of the web server
        cherrypy.config.update({
            'engine.autoreload.on': False,
            'server.socket_port': self.port,
            'server.socket_host': self.bind,
            'log.screen': False,
        })

        if self.ssl_certificate and self.ssl_private_key:
            cherrypy.config.update({
                'server.ssl_module': 'builtin',
                'server.ssl_certificate': self.ssl_certificate,
                'server.ssl_private_key': self.ssl_private_key,
            })

        try:
            host = self.bind if self.bind != "0.0.0.0" else socket.gethostbyname(socket.gethostname())
        except socket.gaierror:
            host = '127.0.0.1'

        if self.ssl_certificate and self.ssl_private_key:
            protocol = 'https'
        else:
            protocol = 'http'

        log.info('Web interface available at %s://%s:%s', protocol, host, self.port)

        # Start the CherryPy WSGI web server
        cherrypy.engine.start()
        cherrypy.engine.block()

    def run(self):
        self._start_server()

    def stop(self):
        log.info('Shutting down web server')
        cherrypy.engine.exit()

@with_session
def get_user(username='flexget', session=None):
    user = session.query(User).filter(User.name == username).first()
    if not user:
        user = User()
        user.name = username
        session.add(user)
    return user

@with_session
def change_password(username='flexget', password='', session=None):
    check = safe.check(password)
    if check.strength not in ['medium', 'strong']:
        raise WeakPassword('Password {0} is not strong enough'.format(password))

    user = get_user(username=username, session=session)
    user.password = str(generate_password_hash(password))
    session.commit()

@with_session
def generate_token(username='flexget', session=None):
    user = get_user(username=username, session=session)
    user.token = generate_key()
    session.commit()
    return user.token


text:
NSString* kRequestMatchTitle = @"Request a Match!";
int kRequestMatchTag = 1;
int kTimeRemainingTag = 2;

@implementation TTTStatusMenuController
{
    NSMenu *statusMenu;
    id<NSMenuDelegate> menuDelegate;
    NSStatusItem* statusItem;
    TTTRestClient* restClient;
    TTTMatchRequest* matchRequest;
    TTTMatch* match;

    TTTPreferencesController* preferencesController;
    TTTMatchRequestController* matchRequestController;
    TTTMatchFoundController* matchFoundController;
}

- (id) initWithUserSettings:(NSUserDefaults *)userSettings {
    self = [super init];
    if(self) {
        restClient = [[TTTRestClient alloc] initWithSettings: userSettings];
        match = [[TTTMatch alloc] initWithRestClient:restClient];
        matchRequest = [[TTTMatchRequest alloc] initWithSettings:userSettings andRestClient:restClient andMatch:match];

        matchFoundController = [[TTTMatchFoundController alloc] initWithMatch: match];

        statusMenu = self.createStatusMenu;
        statusItem = self.createStatusItem;

        [restClient targetValid:^(BOOL valid){
            if(!valid) {
                [self openPreferences:self];
            }
        }];
    }

    return self;
}

- (NSMenu *)createStatusMenu {
    NSMenu* menu = [[NSMenu alloc] init];
    menu.autoenablesItems = NO;

    NSMenuItem *menuItem;
    menuItem = [menu addItemWithTitle:@"Preferences" action:@selector(openPreferences:) keyEquivalent:@""];
    menuItem.target = self;

    menuItem = [menu addItemWithTitle:kRequestMatchTitle action:@selector(createMatch:) keyEquivalent:@""];
    menuItem.tag = kRequestMatchTag;
    menuItem.target = self;

    menuItem = [menu addItemWithTitle:@"" action:nil keyEquivalent:@""];
    menuItem.tag = kTimeRemainingTag;
    menuItem.enabled = NO;
    menuItem.indentationLevel = 1;
    menuItem.hidden = YES;

    [menu addItem:[NSMenuItem separatorItem]];

    menuItem = [menu addItemWithTitle:@"Quit" action:@selector(closeApplication:) keyEquivalent:@""];
    menuItem.target = self;

    menuDelegate = [[TTTStatusMenuDelegate alloc] initWithMatchRequest:matchRequest];
    menu.delegate = menuDelegate;

    return menu;
}

- (NSStatusItem *)createStatusItem {
    NSStatusItem* item = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];

    [item setMenu:statusMenu];
    [item setTitle:@"TTT"];
    [item setHighlightMode:YES];

    return item;
}

- (void)openPreferences:(id)sender
{
    if(!preferencesController) {
        preferencesController = [[TTTPreferencesController alloc] initWithRestClient: restClient];
        [[preferencesController window] setLevel: NSPopUpMenuWindowLevel];
        [preferencesController showWindow:self];
        [[NSNotificationCenter defaultCenter] addObserverForName:NSWindowWillCloseNotification
                                                          object:[preferencesController window]
                                                           queue:nil
                                                      usingBlock:^(NSNotification *notification) {
                                                          preferencesController = nil;
                                                      }];
    }
}

- (void)createMatch:(id)sender
{
    if(!matchRequestController) {
        matchRequestController = [[TTTMatchRequestController alloc] initWithMatchRequest: matchRequest];
        [[matchRequestController window] setLevel: NSPopUpMenuWindowLevel];
        [matchRequestController showWindow:self];
        [[NSNotificationCenter defaultCenter] addObserverForName:NSWindowWillCloseNotification
                                                          object:[matchRequestController window]
                                                           queue:nil
                                                      usingBlock:^(NSNotification *notification) {
                                                          matchRequestController = nil;
                                                      }];
    }
}

- (void)closeApplication:(id)sender {
    [NSApp terminate:self];
}

@end


text:
package org.springframework.security.cas.jackson2;

import java.util.Date;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.jasig.cas.client.authentication.AttributePrincipal;

/**
 * Helps in jackson deserialization of class
 * {@link org.jasig.cas.client.validation.AssertionImpl}, which is used with
 * {@link org.springframework.security.cas.authentication.CasAuthenticationToken}. To use
 * this class we need to register with
 * {@link com.fasterxml.jackson.databind.ObjectMapper}. Type information will be stored
 * in @class property.
 *

 *

 *     ObjectMapper mapper = new ObjectMapper();
 *     mapper.registerModule(new CasJackson2Module());
 *

 *
 * @author Jitendra Singh
 * @see CasJackson2Module
 * @see org.springframework.security.jackson2.SecurityJackson2Modules
 * @since 4.2
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
		isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
class AssertionImplMixin {

	/**
	 * Mixin Constructor helps in deserialize
	 * {@link org.jasig.cas.client.validation.AssertionImpl}
	 * @param principal the Principal to associate with the Assertion.
	 * @param validFromDate when the assertion is valid from.
	 * @param validUntilDate when the assertion is valid to.
	 * @param authenticationDate when the assertion is authenticated.
	 * @param attributes the key/value pairs for this attribute.
	 */
	@JsonCreator
	AssertionImplMixin(@JsonProperty("principal") AttributePrincipal principal,
			@JsonProperty("validFromDate") Date validFromDate, @JsonProperty("validUntilDate") Date validUntilDate,
			@JsonProperty("authenticationDate") Date authenticationDate,
			@JsonProperty("attributes") Map<String, Object> attributes) {
	}

}


text:
<!doctype html>

		<title>Zabuun - Learn Egyptian Arabic for English speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

Essays > Increasing the Home Value

						Expand All | Collapse All

Increasing the Home Value

Within two years, all the changes Bob made to the house totaled more than $20,000. In that time the value of his home rose almost $100,000. Bob felt he made a good investment. He knew when he sold the home, he would get more money than he paid.

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
'use strict';

/**
 * Represents a class that owns a sprite. Extend this class.
 *
 * @constructor
 * @param {Phaser.game} game - The game instance
 * @param {int} [x] - x coordinate.
 * @param {int} [y] - y coordinate.
 * @param {string} key - sprite graphics key
 */

function Sprite(game, x, y, key) {
  this.x = (typeof x === 'undefined') ? 0 : x;
  this.y = (typeof y === 'undefined') ? 0 : y;
  this.game = game;
  if (typeof game === 'undefined') {
    return;
  }
  this.phSprite = game.add.sprite(this.x, this.y, key);
  this.phSprite.anchor.setTo(0.5, 0.5);
}

module.exports = Sprite;


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

<title>PixelController.Screen</title>
<meta name="date" content="2016-03-01">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

se.mah.k3.klara

Enum PixelController.Screen

java.lang.Object

java.lang.Enum<PixelController.Screen>

se.mah.k3.klara.PixelController.Screen

All Implemented Interfaces:

java.io.Serializable, java.lang.Comparable<PixelController.Screen>

Enclosing class:

PixelController

public static enum PixelController.Screen
extends java.lang.Enum<PixelController.Screen>

With this enumerated type you select which screen to control

Enum Constant Summary

Enum Constants

Enum Constant and Description

ASSIGNMENT_7

Used only for debugging doesn't control anything in this world

FLOOR_5

Screen to the left of Elevator C on fifth floor in Niagara

MEDEA_1

Probably the leftmost screen in the MEDEA space on ground floor in Niagara

MEDEA_2

Probably the middle screen in the MEDEA space on ground floor in Niagara

MEDEA_3

Probably the leftmost screen in the MEDEA space on ground floor in Niagara

Method Summary

Methods

Modifier and Type
Method and Description

static PixelController.Screen
valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static PixelController.Screen[]
values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

compareTo, equals, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

MEDEA_1

public static final PixelController.Screen MEDEA_1

Probably the leftmost screen in the MEDEA space on ground floor in Niagara

MEDEA_2

public static final PixelController.Screen MEDEA_2

Probably the middle screen in the MEDEA space on ground floor in Niagara

MEDEA_3

public static final PixelController.Screen MEDEA_3

Probably the leftmost screen in the MEDEA space on ground floor in Niagara

FLOOR_5

public static final PixelController.Screen FLOOR_5

Screen to the left of Elevator C on fifth floor in Niagara

ASSIGNMENT_7

public static final PixelController.Screen ASSIGNMENT_7

Used only for debugging doesn't control anything in this world

Method Detail

values

public static PixelController.Screen[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (PixelController.Screen c : PixelController.Screen.values())
    System.out.println(c);

Returns:

an array containing the constants of this enum type, in the order they are declared

valueOf

public static PixelController.Screen valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:

name - the name of the enum constant to be returned.

Returns:

the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant with the specified name

java.lang.NullPointerException - if the argument is null

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method


text:
/**
 */
package org.xtext.example.mydsl.myDsl.impl;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;

import org.xtext.example.mydsl.myDsl.LogicExpression;
import org.xtext.example.mydsl.myDsl.MyDslPackage;
import org.xtext.example.mydsl.myDsl.TransitionConstraintDeclaration;

/**
 *
 * An implementation of the model object 'Transition Constraint Declaration'.
 *
 *

 * The following features are implemented:
 *

 *
{@link org.xtext.example.mydsl.myDsl.impl.TransitionConstraintDeclarationImpl#getName Name}

 *
{@link org.xtext.example.mydsl.myDsl.impl.TransitionConstraintDeclarationImpl#getLeft Left}

 *
{@link org.xtext.example.mydsl.myDsl.impl.TransitionConstraintDeclarationImpl#getRight Right}

 *

 *

 *
 * @generated
 */
public class TransitionConstraintDeclarationImpl extends MinimalEObjectImpl.Container implements TransitionConstraintDeclaration
{
  /**
   * The default value of the '{@link #getName() Name}' attribute.
   *
   *
   * @see #getName()
   * @generated
   * @ordered
   */
  protected static final String NAME_EDEFAULT = null;

  /**
   * The cached value of the '{@link #getName() Name}' attribute.
   *
   *
   * @see #getName()
   * @generated
   * @ordered
   */
  protected String name = NAME_EDEFAULT;

  /**
   * The cached value of the '{@link #getLeft() Left}' containment reference.
   *
   *
   * @see #getLeft()
   * @generated
   * @ordered
   */
  protected LogicExpression left;

  /**
   * The cached value of the '{@link #getRight() Right}' containment reference.
   *
   *
   * @see #getRight()
   * @generated
   * @ordered
   */
  protected LogicExpression right;

  /**
   *
   *
   * @generated
   */
  protected TransitionConstraintDeclarationImpl()
  {
    super();
  }

  /**
   *
   *
   * @generated
   */
  @Override
  protected EClass eStaticClass()
  {
    return MyDslPackage.Literals.TRANSITION_CONSTRAINT_DECLARATION;
  }

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

  /**
   *
   *
   * @generated
   */
  public void setName(String newName)
  {
    String oldName = name;
    name = newName;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__NAME, oldName, name));
  }

  /**
   *
   *
   * @generated
   */
  public LogicExpression getLeft()
  {
    return left;
  }

  /**
   *
   *
   * @generated
   */
  public NotificationChain basicSetLeft(LogicExpression newLeft, NotificationChain msgs)
  {
    LogicExpression oldLeft = left;
    left = newLeft;
    if (eNotificationRequired())
    {
      ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__LEFT, oldLeft, newLeft);
      if (msgs == null) msgs = notification; else msgs.add(notification);
    }
    return msgs;
  }

  /**
   *
   *
   * @generated
   */
  public void setLeft(LogicExpression newLeft)
  {
    if (newLeft != left)
    {
      NotificationChain msgs = null;
      if (left != null)
        msgs = ((InternalEObject)left).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__LEFT, null, msgs);
      if (newLeft != null)
        msgs = ((InternalEObject)newLeft).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__LEFT, null, msgs);
      msgs = basicSetLeft(newLeft, msgs);
      if (msgs != null) msgs.dispatch();
    }
    else if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__LEFT, newLeft, newLeft));
  }

  /**
   *
   *
   * @generated
   */
  public LogicExpression getRight()
  {
    return right;
  }

  /**
   *
   *
   * @generated
   */
  public NotificationChain basicSetRight(LogicExpression newRight, NotificationChain msgs)
  {
    LogicExpression oldRight = right;
    right = newRight;
    if (eNotificationRequired())
    {
      ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__RIGHT, oldRight, newRight);
      if (msgs == null) msgs = notification; else msgs.add(notification);
    }
    return msgs;
  }

  /**
   *
   *
   * @generated
   */
  public void setRight(LogicExpression newRight)
  {
    if (newRight != right)
    {
      NotificationChain msgs = null;
      if (right != null)
        msgs = ((InternalEObject)right).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__RIGHT, null, msgs);
      if (newRight != null)
        msgs = ((InternalEObject)newRight).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__RIGHT, null, msgs);
      msgs = basicSetRight(newRight, msgs);
      if (msgs != null) msgs.dispatch();
    }
    else if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__RIGHT, newRight, newRight));
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
  {
    switch (featureID)
    {
      case MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__LEFT:
        return basicSetLeft(null, msgs);
      case MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__RIGHT:
        return basicSetRight(null, msgs);
    }
    return super.eInverseRemove(otherEnd, featureID, msgs);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public Object eGet(int featureID, boolean resolve, boolean coreType)
  {
    switch (featureID)
    {
      case MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__NAME:
        return getName();
      case MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__LEFT:
        return getLeft();
      case MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__RIGHT:
        return getRight();
    }
    return super.eGet(featureID, resolve, coreType);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eSet(int featureID, Object newValue)
  {
    switch (featureID)
    {
      case MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__NAME:
        setName((String)newValue);
        return;
      case MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__LEFT:
        setLeft((LogicExpression)newValue);
        return;
      case MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__RIGHT:
        setRight((LogicExpression)newValue);
        return;
    }
    super.eSet(featureID, newValue);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eUnset(int featureID)
  {
    switch (featureID)
    {
      case MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__NAME:
        setName(NAME_EDEFAULT);
        return;
      case MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__LEFT:
        setLeft((LogicExpression)null);
        return;
      case MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__RIGHT:
        setRight((LogicExpression)null);
        return;
    }
    super.eUnset(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public boolean eIsSet(int featureID)
  {
    switch (featureID)
    {
      case MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__NAME:
        return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
      case MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__LEFT:
        return left != null;
      case MyDslPackage.TRANSITION_CONSTRAINT_DECLARATION__RIGHT:
        return right != null;
    }
    return super.eIsSet(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public String toString()
  {
    if (eIsProxy()) return super.toString();

    StringBuffer result = new StringBuffer(super.toString());
    result.append(" (name: ");
    result.append(name);
    result.append(')');
    return result.toString();
  }

} //TransitionConstraintDeclarationImpl


text:
<?php
class OpcionesController extends FrageAppController {
	var $name = 'Opciones';

	function index() {
		$this->Opcion->recursive = 0;
		$ops = $this->Opcion->find('all');
		$opciones = array();
		foreach ($ops as $k => $v) {
			$opciones[$v['Opcion']['tipo']][] = $v;
		}
		$this->set(compact('opciones'));
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid fr opcion', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('opcion', $this->Opcion->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Opcion->create();
			if ($this->Opcion->save($this->data)) {
				$this->Session->setFlash(__('The fr opcion has been saved', true));
				$this->redirect(array('controller' => 'encuestas'));
			} else {
				$this->Session->setFlash(__('The fr opcion could not be saved. Please, try again.', true));
			}
		}
		$this->set('frEncuestas', $this->Opcion->Encuesta->find('list'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid fr opcion', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Opcion->save($this->data)) {
				$this->Session->setFlash(__('The fr opcion has been saved', true));
				$this->redirect(array('controller' => 'encuestas'));
			} else {
				$this->Session->setFlash(__('The fr opcion could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Opcion->read(null, $id);
		}
		$this->set('frEncuestas', $this->Opcion->Encuesta->find('list'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for fr opcion', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Opcion->delete($id)) {
			$this->Session->setFlash(__('Fr opcion deleted', true));
			$this->redirect(array('controller' => 'encuestas'));
		}
		$this->Session->setFlash(__('Fr opcion was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
}
?>


text:
//
//  ZHLabel.h
//  ZHUIKit
//
//  Created by 君赏 on 16/5/1.
//  Copyright © 2016年 君赏. All rights reserved.
//

#import "ZHView.h"
#import "ZHFont.h"
@class ZHFont,ZHColor;

NS_ASSUME_NONNULL_BEGIN

@interface ZHLabel : ZHView
/*!
 *  @brief  default is nil
 */
@property (nonatomic, copy,nullable) NSString *text;

/*!
 *  @brief default is nil (system font 17 plain)
 */
@property (nonatomic, strong) ZHFont * font;

/*!
 *  @brief default is black color
 */
@property (nonatomic, strong) ZHColor *textColor;

@end

NS_ASSUME_NONNULL_END


text:
package security

import authentikat.jwt.{JsonWebToken, JwtClaimsSet, JwtClaimsSetJValue, JwtHeader}
import cmwell.ws.Settings
import com.typesafe.config.ConfigFactory
import org.joda.time.DateTime

import scala.util.Try

class Token(jwt: String, authCache: EagerAuthCache) {
  private val requiredClaims = Set("sub", "exp")

  private val claimsSet = jwt match {
    case JsonWebToken(_, cs, _) if requiredClaims.map(cs.getClaimValue).forall(_.isDefined) => cs
    case _ =>
      throw new IllegalArgumentException("Given string was not in JWT format, or there are mandatory claims missing")
  }

  val username = claimsSet.getClaimValue("sub").get
  val expiry = new DateTime(claimsSet.getClaimValue("exp").map(_.toLong).get)

  def isValid = {
    (JsonWebToken.validate(jwt, Token.secret) || JsonWebToken.validate(jwt, Token.secret2)) &&
    expiry.isAfterNow &&
    (claimsSet
      .getClaimValue("rev")
      .map(_.toInt)
      .getOrElse(0) >= Token.getUserRevNum(username, authCache) || username == "root") // root has immunity to revision revoking
  }

  implicit class JwtClaimsSetJValueExtensions(cs: JwtClaimsSetJValue) {
    def getClaimValue(key: String): Option[String] = cs.asSimpleMap.toOption.getOrElse(Map()).get(key)
  }

  override def toString = s"Token(${claimsSet.asJsonString})"
}

object Token {
  def apply(jwt: String, authCache: EagerAuthCache) = Try(new Token(jwt, authCache)).toOption

  // not using ws.Settings, so it'd be available from `sbt ws/console`
  private lazy val secret = ConfigFactory.load().getString("play.http.secret.key")
  // not using ws.Settings, so it'd be available from `sbt ws/console`
  private lazy val secret2 = ConfigFactory.load().getString("cmwell.ws.additionalSecret.key")
  private val jwtHeader = JwtHeader("HS256")

  private def getUserRevNum(username: String, authCache: EagerAuthCache) =
    authCache.getUserInfoton(username).flatMap(u => (u \ "rev").asOpt[Int]).getOrElse(0)

  def generate(authCache: EagerAuthCache,
               username: String,
               expiry: Option[DateTime] = None,
               rev: Option[Int] = None,
               isAdmin: Boolean = false): String = {
    val maxDays = Settings.maxDaysToAllowGenerateTokenFor
    if (!isAdmin && expiry.isDefined && expiry.get.isAfter(DateTime.now.plusDays(maxDays))) {
      throw new IllegalArgumentException(s"Token expiry must be less than $maxDays days")
    }
    if (!isAdmin && rev.isDefined) {
      throw new IllegalArgumentException("rev should only be supplied in Admin mode (i.e. manually via console)")
    }
    val claims = Map("sub" -> username,
                     "exp" -> expiry.getOrElse(DateTime.now.plusDays(1)).getMillis,
                     "rev" -> rev.getOrElse(getUserRevNum(username, authCache)))
    JsonWebToken(jwtHeader, JwtClaimsSet(claims), secret)
  }
}


text:
package com.tle.web.sections.equella;

import com.tle.core.guice.Bind;
import com.tle.web.DebugSettings;
import com.tle.web.sections.SectionInfo;
import com.tle.web.sections.registry.SectionsServlet;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Bind
@MultipartConfig
public class MultipartSectionsServlet extends SectionsServlet {
  private final Map<Object, Object> attribs;

  public MultipartSectionsServlet() {
    super();
    attribs = new HashMap<>();
    attribs.putAll(super.defaultAttributes());
    attribs.put(SectionInfo.KEY_MINIFIED, !DebugSettings.isDebuggingMode());
  }

  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    super.service(request, response);
  }

  @Override
  protected Map<Object, Object> defaultAttributes() {
    return attribs;
  }
}


text:
from collections import defaultdict
from copy import copy
from strips import *

class S(State):
    def __init__(self, n):
        self.n = n

    @Action
    def incr(self):
        self.n += 1

    @Action
    def double(self):
        self.n *= 2

s = S(0)
goal = lambda s: s.n == 123


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Cats.Models.Hubs;

namespace Cats.Services.Hub
{
    public interface IPeriodService
    {

        bool AddPeriod(Period entity);
        bool DeletePeriod(Period entity);
        bool DeleteById(int id);
        bool EditPeriod(Period entity);
        Period FindById(int id);
        List<Period> GetAllPeriod();
        List<Period> FindBy(Expression<Func<Period, bool>> predicate);
         List<int?> GetYears();
         List<int?> GetMonths(int year);
        Period GetPeriod(int year, int month);

    }
}


text:
PhusionPassenger.require_passenger_lib 'platform_info'
PhusionPassenger.require_passenger_lib 'platform_info/operating_system'

module PhusionPassenger

module PlatformInfo
	# An identifier for the current Linux distribution. nil if the operating system is not Linux.
	def self.linux_distro
		tags = linux_distro_tags
		if tags
			return tags.first
		else
			return nil
		end
	end

	# Autodetects the current Linux distribution and return a number of identifier tags.
	# The first tag identifies the distribution while the other tags indicate which
	# distributions it is likely compatible with.
	# Returns nil if the operating system is not Linux.
	def self.linux_distro_tags
		if os_name != "linux"
			return nil
		end
		lsb_release = read_file("/etc/lsb-release")
		if lsb_release =~ /Ubuntu/
			return [:ubuntu, :debian]
		elsif File.exist?("/etc/debian_version")
			return [:debian]
		elsif File.exist?("/etc/redhat-release")
			redhat_release = read_file("/etc/redhat-release")
			if redhat_release =~ /CentOS/
				return [:centos, :redhat]
			elsif redhat_release =~ /Fedora/
				return [:fedora, :redhat]
			elsif redhat_release =~ /Mandriva/
				return [:mandriva, :redhat]
			else
				# On official RHEL distros, the content is in the form of
				# "Red Hat Enterprise Linux Server release 5.1 (Tikanga)"
				return [:rhel, :redhat]
			end
		elsif File.exist?("/etc/system-release")
			system_release = read_file("/etc/system-release")
			if system_release =~ /Amazon Linux/
				return [:amazon, :redhat]
			else
				return [:unknown]
			end
		elsif File.exist?("/etc/suse-release")
			return [:suse]
		elsif File.exist?("/etc/gentoo-release")
			return [:gentoo]
		else
			return [:unknown]
		end
		# TODO: Slackware
	end
	memoize :linux_distro_tags
end

end # PhusionPassenger


text:
package globant.svp.core.dao;

import globant.svp.core.domain.Customer;
import globant.svp.core.domain.Entity;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository("CustomerDAOJDBC")
public class CustomerDAOJDBC implements GenericDAO {

	@Autowired
	private Customer entity;

	public void addEntity(Entity entity) {
		Connection conn;
		try {
			conn = DataBaseUtil.createConnection();
			Statement stmt = conn.createStatement();

			StringBuffer sqlQuery = new StringBuffer(
					"INSERT INTO CUSTOMER (ECN, ACCOUNT, FIRSTNAME, MIDDLEINITIAL, LASTNAME, PHONE, CITY, STATE, ZIP) VALUES("
							+ "'"
							+ ((Customer) entity).getEcn()
							+ "',"
							+ ((Customer) entity).getAccount()
							+ ","
							+ "'"
							+ ((Customer) entity).getFirstName()
							+ "',"
							+ "'"
							+ ((Customer) entity).getMiddleInitial()
							+ "',"
							+ "'"
							+ ((Customer) entity).getLastName()
							+ "',"
							+ "'"
							+ ((Customer) entity).getPhone()
							+ "',"
							+ "'"
							+ ((Customer) entity).getCity()
							+ "',"
							+ "'"
							+ ((Customer) entity).getState()
							+ "',"
							+ ((Customer) entity).getZip() + ")");

			System.out.println("__________________________________");

			System.out.println(sqlQuery.toString());

			@SuppressWarnings("unused")
			int count = stmt.executeUpdate(sqlQuery.toString());

			stmt.close();
			conn.close();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<? extends Entity> getAllEntity() {
		Connection conn;
		List<Customer> list = new ArrayList<Customer>();
		try {
			conn = DataBaseUtil.createConnection();
			Statement stmt = conn.createStatement();

			ResultSet rs;
			rs = stmt.executeQuery("SELECT * FROM CUSTOMER");
			while (rs.next()) {
				entity = new Customer();
				entity.setEcn(rs.getString("ECN"));
				entity.setAccount(rs.getLong("Account"));
				entity.setFirstName(rs.getString("FIRSTNAME"));
				entity.setMiddleInitial(rs.getString("MIDDLEINITIAL"));
				entity.setLastName(rs.getString("LASTNAME"));
				entity.setDob(rs.getDate("DOB"));
				entity.setPhone(rs.getString("PHONE"));
				entity.setCity(rs.getString("CITY"));
				entity.setState(rs.getString("STATE"));
				entity.setZip(rs.getLong("ZIP"));
				list.add(entity);
			}
			stmt.close();
			conn.close();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return list;
	}

	@Override
	public void deleteEntityById(String id, String value) {
		Connection conn;
		try {
			conn = DataBaseUtil.createConnection();
			Statement stmt = conn.createStatement();

			String sqlQuery = new String("DELETE FROM CUSTOMER WHERE " + id
					+ "=" + (value instanceof String ? "'" : "") + value
					+ (value instanceof String ? "'" : ""));

			stmt.executeUpdate(sqlQuery);

			stmt.close();
			conn.close();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	@Override
	public List<? extends Entity> getAllEntityByRequestParam(
			Map<String, String> requestParam) {
		Connection conn;
		List<Customer> list = new ArrayList<Customer>();
		try {
			conn = DataBaseUtil.createConnection();
			Statement stmt = conn.createStatement();

			ResultSet rs;
			StringBuffer sqlQuery = new StringBuffer(
					"SELECT * FROM CUSTOMER WHERE ");
			boolean firstTime = true;
			if (!requestParam.isEmpty()) {
				Iterator<String> keyIter = requestParam.keySet().iterator();
				while (keyIter.hasNext()) {
					String key = keyIter.next();
					String value = requestParam.get(key);
					if (!firstTime) {
						sqlQuery.append(" or ");
					} else {
						firstTime = false;
					}
					sqlQuery.append(key.toUpperCase() + " like '%" + value
							+ "%'");
				}
			}

			rs = stmt.executeQuery(sqlQuery.toString());
			while (rs.next()) {
				entity = new Customer();

				entity.setEcn(rs.getString("ECN"));
				entity.setAccount(rs.getLong("Account"));
				entity.setFirstName(rs.getString("FIRSTNAME"));
				entity.setMiddleInitial(rs.getString("MIDDLEINITIAL"));
				entity.setLastName(rs.getString("LASTNAME"));
				entity.setDob(rs.getDate("DOB"));
				entity.setPhone(rs.getString("PHONE"));
				entity.setCity(rs.getString("CITY"));
				entity.setState(rs.getString("STATE"));
				entity.setZip(rs.getLong("ZIP"));
				list.add(entity);
			}
			stmt.close();
			conn.close();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return list;
	}

	@Override
	public void deleteEntity(Entity entity) {
		// TODO Auto-generated method stub
	}

}


text:
import os, sys
import inspect
import textwrap

class PCSEFileReader(dict):
    """Reader for parameter files in the PCSE format.

    This class is a replacement for the `CABOFileReader`. The latter can be
    used for reading parameter files in the CABO format, however this format
    has rather severe limitations: it only supports string, integer, float
    and array parameters. There is no support for specifying parameters with
    dates for example (other then specifying them as a string).

    The `PCSEFileReader` is a much more versatile tool for creating parameter
    files because it leverages the power of the python interpreter for
    processing parameter files through the `execfile` functionality in python.
    This means that anything that can be done in a python script can also be
    done in a PCSE parameter file.

    :param fname: parameter file to read and parse
    :returns: dictionary object with parameter key/value pairs.

    *Example*

    Below is an example of a parameter file 'parfile.pcse'. Parameters can
    be defined the 'CABO'-way, but also advanced functionality can be used by
    importing modules, defining parameters as dates or numpy arrays and even
    applying function on arrays (in this case `np.sin`)::

        \"\"\"This is the header of my parameter file.

        This file is derived from the following sources
        * dummy file for demonstrating the PCSEFileReader
        * contains examples how to leverage dates, arrays and functions, etc.
        \"\"\"

        import numpy as np
        import datetime as dt

        TSUM1 = 1100
        TSUM2 = 900
        DTSMTB = [ 0., 0.,
                   5., 5.,
                  20., 25.,
                  30., 25.]
        AMAXTB = np.sin(np.arange(12))
        cropname = "alfalfa"
        CROP_START_DATE = dt.date(2010,5,14)

    Can be read with the following statements::

        >>>fileparameters = PCSEFileReader('parfile.pcse')
        >>>print fileparameters['TSUM1']
        1100
        >>>print fileparameters['CROP_START_DATE']
        2010-05-14
        >>>print fileparameters
        PCSE parameter file contents loaded from:
        D:\UserData\pcse_examples\parfile.pw

        This is the header of my parameter file.

        This file is derived from the following sources
        * dummy file for demonstrating the PCSEFileReader
        * contains examples how to leverage dates, arrays and functions, etc.
        DTSMTB: [0.0, 0.0, 5.0, 5.0, 20.0, 25.0, 30.0, 25.0] (<type 'list'>)
        CROP_START_DATE: 2010-05-14 (<type 'datetime.date'>)
        TSUM2: 900 (<type 'int'>)
        cropname: alfalfa (<type 'str'>)
        AMAXTB: [ 0.          0.84147098  0.90929743  0.14112001 -0.7568025
          -0.95892427  -0.2794155   0.6569866   0.98935825  0.41211849
          -0.54402111 -0.99999021] (<type 'numpy.ndarray'>)
        TSUM1: 1100 (<type 'int'>)
    """

    def __init__(self, fname):
        dict.__init__(self)

        # Construct full path to parameter file and check file existence
        cwd = os.getcwd()
        self.fname_fp = os.path.normpath(os.path.join(cwd, fname))
        if not os.path.exists(self.fname_fp):
            msg = "Could not find parameter file '%s'" % self.fname_fp
            raise RuntimeError(msg)

        # compile and execute the contents of the file
        bytecode = compile(open(self.fname_fp).read(), self.fname_fp, 'exec')
        exec(bytecode, {}, self)

        # Remove any members in self that are python modules
        keys = list(self.keys())
        for k in keys:
            if inspect.ismodule(self[k]):
                self.pop(k)

        # If the file has a header (e.g. __doc__) store it.
        if "__doc__" in self:
            header = self.pop("__doc__")
            if len(header) > 0:
                self.header = header
                if self.header[-1] != "\n":
                    self.header += "\n"
        else:
            self.header = None

    def __str__(self):
        printstr = "PCSE parameter file contents loaded from:\n"
        printstr += "%s\n\n" % self.fname_fp
        if self.header is not None:
            printstr += self.header
        for k in self:
             r = "%s: %s (%s)" % (k, self[k], type(self[k]))
             printstr += (textwrap.fill(r, subsequent_indent="  ") + "\n")
        return printstr


text:
package metrics

import (
	"github.com/prometheus/client_golang/prometheus"

	dto "github.com/prometheus/client_model/go"
)

// This file contains a series of interfaces which we explicitly define for
// integrating with prometheus. We redefine the interfaces explicitly here
// so that we can prevent breakage if methods are ever added to prometheus
// variants of them.

// Collector defines a subset of prometheus.Collector interface methods
type Collector interface {
	Describe(chan<- *prometheus.Desc)
	Collect(chan<- prometheus.Metric)
}

// Metric defines a subset of prometheus.Metric interface methods
type Metric interface {
	Desc() *prometheus.Desc
	Write(*dto.Metric) error
}

// CounterMetric is a Metric that represents a single numerical value that only ever
// goes up. That implies that it cannot be used to count items whose number can
// also go down, e.g. the number of currently running goroutines. Those
// "counters" are represented by Gauges.

// CounterMetric is an interface which defines a subset of the interface provided by prometheus.Counter
type CounterMetric interface {
	Inc()
	Add(float64)
}

// CounterVecMetric is an interface which prometheus.CounterVec satisfies.
type CounterVecMetric interface {
	WithLabelValues(...string) CounterMetric
	With(prometheus.Labels) CounterMetric
}

// GaugeMetric is an interface which defines a subset of the interface provided by prometheus.Gauge
type GaugeMetric interface {
	Set(float64)
}

// ObserverMetric captures individual observations.
type ObserverMetric interface {
	Observe(float64)
}

// PromRegistry is an interface which implements a subset of prometheus.Registerer and
// prometheus.Gatherer interfaces
type PromRegistry interface {
	Register(prometheus.Collector) error
	MustRegister(...prometheus.Collector)
	Unregister(prometheus.Collector) bool
	Gather() ([]*dto.MetricFamily, error)
}


text:
package com.frame.mvp.ui.common;

/**
 *
 */
public class WebActivity {

}