text:
import visa
import sys
import time
import os

import numpy as np

# Timestamp to make things easier
def timeStampYMDH():
    # -> 'YYYY_MM_DD_HHMM' as a time stamp
    return time.strftime('%Y_%m_%d_%H%M')

# Path to save the file
# Modify the C:\Users\... part only
# the rest is to timestamp your data :)
def download_data(
        path="C:\Users\cleanroom.STAFF\Desktop\Leo\\test",
        filename="COL111_device1_testing.txt",
        values=['VG', 'VDS', 'ID', 'IG'],
        skip=1):

    # adds a timestamp to the beginning of the filename

    # Define the Matrix
    matrix = []
    # Obtain the data from the parameter analyser
    # No error checking
    device = visa.instrument("GPIB::02")
    try:
        print("Parameter Analyser ID: %s" % (device.ask("ID")))
    except:
        print("Could not connect to Parameter Analyser, sorry")
        sys.exit()
    print("Obtaining %s parameters." % len(values))

    for x in range(0, len(values)):
        try:
            print("DO '%s'" % (values[x]))
            # Change this depending on the  value to download
            device.write("DO '%s'" % (values[x]))
        except:
            print("Command Timeout!")
        data = device.read_values()
        print("Obtained %d Data Values!" % (len(data)))
        #Makes the headers for the data
        data.insert(0, "%s" % values[x])
        # Adds timestamp to the start of the file

        if(matrix == []):
            for i in xrange(len(data)):
                matrix.append
        matrix.append(data)

    matrix = zip(*matrix)

    # Save the data to disk
    PATH_FILENAME = os.path.join(path,filename)

    if os.path.isfile(PATH_FILENAME):
        print "that filename already exists, please check directory and try again"
    else:
        with open(PATH_FILENAME, "w") as f:

            for i in range(0, len(matrix)):
                for j in range(0, len(matrix[i])):
                    f.write(", %s" % matrix[i][j])
                f.write('\n')
        f.close()
        print("Data saved to: " + PATH_FILENAME)

    device.close

    #cleans the raw data from the pull section of the script
    try:
        lines = []
        with open(PATH_FILENAME, "r") as f:
            for line in f:
                # removes extra ',' at the start of each data row
                lines.append(line[2:-1])

        with open(PATH_FILENAME, 'w') as g:

            for line in lines:
                # checks for 9.91e+99
                # which is what is appended after compliance is hit
                if line.startswith('9.91e+99') == False:
                    g.write(line + "\n")
    except Exception as e:
        print('there was an error with cleaning: ' + PATH_FILENAME)
        print(e)

    try:
        np.loadtxt(PATH_FILENAME, skiprows=skip,
                   delimiter=",", dtype=float)
    except Exception as e:
        print('there was an error with np.loadtxt after cleaning for:\n ' + PATH_FILENAME)
        print(e)

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace imnotjames\Syndicator;

use DateTime;
use imnotjames\Syndicator\Exceptions\InvalidURIException;

/**
 * An article in a syndication feed
 *
 * @package imnotjames\Syndicator
 */
class Article {
	/**
	 * @var string
	 */
	private $id;

	/**
	 * @var string
	 */
	private $title;

	/**
	 * @var string
	 */
	private $description;

	/**
	 * @var string
	 */
	private $uri;

	/**
	 * @var string
	 */
	private $copyright;

	/**
	 * @var array
	 */
	private $attachments = array();

	/**
	 * @var \DateTime
	 */
	private $datePublished;

	/**
	 * @var Contact
	 */
	private $author;

	/**
	 * @var array
	 */
	private $categories = array();

	/**
	 * @var Article
	 */
	private $source;

	/**
	 * @param string $id
	 *
	 * @throws Exceptions\InvalidURIException
	 */
	public function __construct($id = null) {
		$this->id = $id;
	}

	/**
	 * @return string
	 */
	public function getID() {
		return $this->id;
	}

	/**
	 * @return string
	 */
	public function getTitle() {
		return $this->title;
	}

	/**
	 * @return string
	 */
	public function getDescription() {
		return $this->description;
	}

	/**
	 * @return string
	 */
	public function getURI() {
		return $this->uri;
	}

	/**
	 * @return \DateTime
	 */
	public function getDatePublished() {
		return $this->datePublished;
	}

	/**
	 * @return string
	 */
	public function getCopyright() {
		return $this->copyright;
	}

	/**
	 * @return Contact
	 */
	public function getAuthor() {
		return $this->author;
	}

	/**
	 * @return Article
	 */
	public function getSource() {
		return $this->source;
	}

	/**
	 * @return array
	 */
	public function getAttachments() {
		return $this->attachments;
	}

	/**
	 * @return array
	 */
	public function getCategories() {
		return $this->categories;
	}

	/**
	 * @param string $id
	 */
	public function setID($id) {
		$this->id = $id;
	}

	/**
	 * @param string $title
	 */
	public function setTitle($title) {
		$this->title = $title;
	}

	/**
	 * @param string $description
	 */
	public function setDescription($description) {
		$this->description = $description;
	}

	/**
	 * @param string $uri
	 *
	 * @throws Exceptions\InvalidURIException
	 */
	public function setURI($uri) {
		$uri = filter_Var($uri, FILTER_VALIDATE_URL);
		if ($uri === false) {
			throw new InvalidURIException();
		}

		$this->uri = $uri;
	}

	/**
	 * @param DateTime $datePublished
	 */
	public function setDatePublished(DateTime $datePublished) {
		$this->datePublished = $datePublished;
	}

	/**
	 * @param Contact $author
	 */
	public function setAuthor(Contact $author) {
		$this->author = $author;
	}

	/**
	 * @param Article $source
	 */
	public function setSource(Article $source) {
		$this->source = $source;
	}

	/**
	 * @param Attachment $attachment
	 */
	public function addAttachment(Attachment $attachment) {
		$this->attachments[] = $attachment;
	}

	/**
	 * @param Category $category
	 */
	public function addCategory(Category $category) {
		$this->categories[] = $category;
	}

	/**
	 *
	 */
	public function clearCategories() {
		$this->categories = array();
	}
}


text:
package com.sksamuel.elastic4s.testkit

import com.sksamuel.elastic4s.ElasticClient
import org.scalatest.matchers.should.Matchers
import org.scalatest.matchers.{MatchResult, Matcher}

trait IndexMatchers extends Matchers {

  import com.sksamuel.elastic4s.ElasticDsl._

  import scala.concurrent.duration._

  def haveCount(expectedCount: Int)(implicit client: ElasticClient,
                                    timeout: FiniteDuration = 10.seconds): Matcher[String] =
    new Matcher[String] {

      def apply(left: String): MatchResult = {
        val count = client.execute(search(left).size(0)).await(timeout).result.totalHits
        MatchResult(
          count == expectedCount,
          s"Index $left had count $count but expected $expectedCount",
          s"Index $left had document count $expectedCount"
        )
      }
    }

  def containDoc(expectedId: Any)(implicit client: ElasticClient,
                                  timeout: FiniteDuration = 10.seconds): Matcher[String] =
    new Matcher[String] {

      override def apply(left: String): MatchResult = {
        val exists = client.execute(get(expectedId.toString).from(left)).await(timeout).result.exists
        MatchResult(
          exists,
          s"Index $left did not contain expected document $expectedId",
          s"Index $left contained document $expectedId"
        )
      }
    }

  def beCreated(implicit client: ElasticClient, timeout: FiniteDuration = 10.seconds): Matcher[String] =
    new Matcher[String] {

      override def apply(left: String): MatchResult = {
        val exists = client.execute(indexExists(left)).await(timeout).result.isExists
        MatchResult(
          exists,
          s"Index $left did not exist",
          s"Index $left exists"
        )
      }
    }

  def beEmpty(implicit client: ElasticClient, timeout: FiniteDuration = 10.seconds): Matcher[String] =
    new Matcher[String] {

      override def apply(left: String): MatchResult = {
        val count = client.execute(search(left).size(0)).await(timeout).result.totalHits
        MatchResult(
          count == 0,
          s"Index $left was not empty",
          s"Index $left was empty"
        )
      }
    }
}


text:
'use strict';

//
var rooms = require('../controllers/rooms');

//Room authorization methods
var canUpdateRoom = function(req, res, next) {

	//Can update if user is admin or the room creator
	if (!req.user.isAdmin && req.room.user.id !== req.user.id) {
    return res.send(401, 'User is not authorized');
  }
  next();
};

//for now update permission = delete permission
var canDeleteRoom = canUpdateRoom;

// The Package is past automatically as first parameter
module.exports = function(Webconference, app, auth, database) {

  app.route('/rooms')
    .get(rooms.all)
    .post(auth.requiresLogin, rooms.create);
  app.route('/rooms/:roomId')
    .get(rooms.show)
    .put(auth.requiresLogin, canUpdateRoom, rooms.update)
    .delete(auth.requiresLogin, canDeleteRoom, rooms.destroy);

  // Finish with setting up the roomId param
  app.param('roomId', rooms.room);
};


text:
"""Classes to build sanitized HTML."""

__author__ = 'John Orr (jorr@google.com)'

import cgi
import re

def escape(strg):
    return cgi.escape(strg, quote=1).replace("'", ''').replace('`', '`')

class SafeDom(object):
    """Base class for the sanitizing module."""

    def __init__(self):
        self._parent = None

    def _set_parent(self, parent):
        assert self != parent
        self._parent = parent

    @property
    def parent(self):
        return self._parent

    @property
    def sanitized(self):
        raise NotImplementedError()

    def __str__(self):
        return self.sanitized

class Node(SafeDom):
    """Represents a single node in the DOM."""

# pylint: disable=incomplete-protocol
class NodeList(SafeDom):
    """Holds a list of Nodes and can bulk sanitize them."""

    def __init__(self):
        self.list = []
        super(NodeList, self).__init__()

    def __len__(self):
        return len(self.list)

    def append(self, node):
        assert node is not None, 'Cannot add an empty value to the node list'
        self.list.append(node)
        node._set_parent(self)  # pylint: disable=protected-access
        return self

    @property
    def children(self):
        return [] + self.list

    def empty(self):
        self.list = []
        return self

    def delete(self, node):
        _list = []
        for child in self.list:
            if child != node:
                _list.append(child)
        self.list = _list

    def insert(self, index, node):
        assert node is not None, 'Cannot add an empty value to the node list'
        self.list.insert(index, node)
        node._set_parent(self)  # pylint: disable=protected-access
        return self

    @property
    def sanitized(self):
        sanitized_list = []
        for node in self.list:
            sanitized_list.append(node.sanitized)
        return ''.join(sanitized_list)

class Text(Node):
    """Holds untrusted text which will be sanitized when accessed."""

    def __init__(self, unsafe_string):
        super(Text, self).__init__()
        self._value = unicode(unsafe_string)

    @property
    def sanitized(self):
        return escape(self._value)

class Comment(Node):
    """An HTML comment."""

    def __init__(self, unsafe_string=''):
        super(Comment, self).__init__()
        self._value = unicode(unsafe_string)

    def get_value(self):
        return self._value

    @property
    def sanitized(self):
        return '<!--%s-->' % escape(self._value)

    def add_attribute(self, **attr):
        pass

    def add_text(self, unsafe_string):
        self._value += unicode(unsafe_string)

class Element(Node):
    """Embodies an HTML element which will be sanitized when accessed."""

    _ALLOWED_NAME_PATTERN = re.compile(r'^[a-zA-Z][_\-a-zA-Z0-9]*$')

    _VOID_ELEMENTS = frozenset([
        'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen',
        'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'])

    def __init__(self, tag_name, **attr):
        """Initializes an element with given tag name and attributes.

        Tag name will be restricted to alpha chars, attribute names
        will be quote-escaped.

        Args:
            tag_name: the name of the element, which must match
                _ALLOWED_NAME_PATTERN.
            **attr: the names and value of the attributes. Names must match
                _ALLOWED_NAME_PATTERN and values will be quote-escaped.
        """
        assert Element._ALLOWED_NAME_PATTERN.match(tag_name), (
            'tag name %s is not allowed' % tag_name)
        for attr_name in attr:
            assert Element._ALLOWED_NAME_PATTERN.match(attr_name), (
                'attribute name %s is not allowed' % attr_name)
        super(Element, self).__init__()
        self._tag_name = tag_name
        self._children = []
        self._attr = {}
        for _name, _value in attr.items():
            self._attr[_name.lower()] = _value

    def has_attribute(self, name):
        return name.lower() in self._attr

    @property
    def attributes(self):
        return self._attr.keys()

    def set_attribute(self, name, value):
        self._attr[name.lower()] = value
        return self

    def get_escaped_attribute(self, name):
        return escape(self._attr[name.lower()])

    def add_attribute(self, **attr):
        for attr_name, value in attr.items():
            assert Element._ALLOWED_NAME_PATTERN.match(attr_name), (
                'attribute name %s is not allowed' % attr_name)
            self._attr[attr_name.lower()] = value
        return self

    def add_child(self, node):
        node._set_parent(self)  # pylint: disable=protected-access
        self._children.append(node)
        return self

    def append(self, node):
        return self.add_child(node)

    def add_children(self, node_list):
        for child in node_list.list:
            self.add_child(child)
        return self

    def empty(self):
        self._children = []
        return self

    def add_text(self, text):
        return self.add_child(Text(text))

    def can_have_children(self):
        return True

    @property
    def children(self):
        return [] + self._children

    @property
    def tag_name(self):
        return self._tag_name

    @property
    def sanitized(self):
        """Santize the element and its descendants."""
        assert Element._ALLOWED_NAME_PATTERN.match(self._tag_name), (
            'tag name %s is not allowed' % self._tag_name)
        buff = '<' + self._tag_name
        for attr_name, value in sorted(self._attr.items()):
            if attr_name == 'classname':
                attr_name = 'class'
            elif attr_name.startswith('data_'):
                attr_name = attr_name.replace('_', '-')
            if value is None:
                value = ''
            buff += ' %s="%s"' % (
                attr_name, escape(value))

        if self._children:
            buff += '>'
            for child in self._children:
                buff += child.sanitized
            buff += '</%s>' % self._tag_name
        elif self._tag_name.lower() in Element._VOID_ELEMENTS:
            buff += '/>'
        else:
            buff += '></%s>' % self._tag_name

        return buff

class A(Element):
    """Embodies an 'a' tag.  Just a conveniece wrapper on Element."""

    def __init__(self, href, **attr):
        """Initialize an 'a' tag to a given target.

        Args:
            href: The value to put in the 'href' tag of the 'a' element.
            **attr: the names and value of the attributes. Names must match
                _ALLOWED_NAME_PATTERN and values will be quote-escaped.
        """

        super(A, self).__init__('a', **attr)
        self.add_attribute(href=href)

class ScriptElement(Element):
    """Represents an HTML <script> element."""

    def __init__(self, **attr):
        super(ScriptElement, self).__init__('script', **attr)

    def can_have_children(self):
        return False

    def add_child(self, unused_node):
        raise ValueError()

    def add_children(self, unused_nodes):
        raise ValueError()

    def empty(self):
        raise ValueError()

    def add_text(self, text):
        """Add the script body."""

        class Script(Text):

            def __init__(self, script):
                # Pylint is just plain wrong about warning here; suppressing.
                # pylint: disable=bad-super-call
                super(Script, self).__init__(None)
                self._script = script

            @property
            def sanitized(self):
                if '</script>' in self._script:
                    raise ValueError('End script tag forbidden')
                return self._script

        self._children.append(Script(text))

class Entity(Node):
    """Holds an XML entity."""

    ENTITY_PATTERN = re.compile('^&([a-zA-Z]+|#[0-9]+|#x[0-9a-fA-F]+);$')

    def __init__(self, entity):
        assert Entity.ENTITY_PATTERN.match(entity)
        super(Entity, self).__init__()
        self._entity = entity

    @property
    def sanitized(self):
        assert Entity.ENTITY_PATTERN.match(self._entity)
        return self._entity

def assemble_text_message(text, link):
    node_list = NodeList()
    if text:
        node_list.append(Text(text))
        node_list.append(Entity(' '))
    if link:
        node_list.append(Element(
            'a', href=link, target='_blank').add_text('Learn more...'))
    return node_list

class Template(Node):
    """Enables a Jinja template to be included in a safe_dom.NodeList."""

    def __init__(self, template, **kwargs):
        self.template = template
        self.kwargs = kwargs
        super(Template, self).__init__()

    @property
    def sanitized(self):
        return self.template.render(**self.kwargs)


text:
package org.apache.flink.table.plan.nodes.dataset

import org.apache.calcite.plan._
import org.apache.calcite.prepare.RelOptTableImpl
import org.apache.calcite.rel.`type`.RelDataType
import org.apache.calcite.rel.core.TableScan
import org.apache.calcite.rel.metadata.RelMetadataQuery
import org.apache.calcite.rel.{RelNode, RelWriter}
import org.apache.flink.api.java.DataSet
import org.apache.flink.table.api.BatchQueryConfig
import org.apache.flink.table.api.internal.BatchTableEnvImpl
import org.apache.flink.table.plan.schema.RowSchema
import org.apache.flink.types.Row

import scala.collection.JavaConverters._

/**
  * Flink RelNode which matches along with DataSource.
  * It ensures that types without deterministic field order (e.g. POJOs) are not part of
  * the plan translation.
  *
  * This may read only part, or change the order of the fields available in a
  * [[org.apache.flink.api.common.typeutils.CompositeType]] of the underlying [[DataSet]].
  * The fieldIdxs describe the indices of the fields in the
  * [[org.apache.flink.api.common.typeinfo.TypeInformation]]
  */
class DataSetScan(
    cluster: RelOptCluster,
    traitSet: RelTraitSet,
    catalog: RelOptSchema,
    inputDataSet: DataSet[_],
    fieldIdxs: Array[Int],
    rowRelDataType: RelDataType)
  extends TableScan(
    cluster,
    traitSet,
    RelOptTableImpl.create(catalog, rowRelDataType, List[String]().asJava, null))
  with BatchScan {

  override def deriveRowType(): RelDataType = rowRelDataType

  override def estimateRowCount(mq: RelMetadataQuery): Double = 1000L

  override def computeSelfCost(planner: RelOptPlanner, metadata: RelMetadataQuery): RelOptCost = {
    val rowCnt = metadata.getRowCount(this)
    planner.getCostFactory.makeCost(rowCnt, rowCnt, 0)
  }

  override def copy(traitSet: RelTraitSet, inputs: java.util.List[RelNode]): RelNode = {
    new DataSetScan(
      cluster,
      traitSet,
      catalog,
      inputDataSet,
      fieldIdxs,
      getRowType
    )
  }

  override def translateToPlan(
      tableEnv: BatchTableEnvImpl,
      queryConfig: BatchQueryConfig): DataSet[Row] = {
    val schema = new RowSchema(rowRelDataType)
    val config = tableEnv.getConfig
    convertToInternalRow(schema, inputDataSet.asInstanceOf[DataSet[Any]], fieldIdxs, config, None)
  }

  override def explainTerms(pw: RelWriter): RelWriter = pw
    .item("ref", System.identityHashCode(inputDataSet))
    .item("fields", String.join(", ", rowRelDataType.getFieldNames))
}


text:
package com.opengamma.bbg.livedata.faketicks;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import com.google.common.collect.Sets;
import com.opengamma.id.ExternalScheme;
import com.opengamma.livedata.LiveDataSpecification;
import com.opengamma.util.tuple.ObjectsPair;

/**
 * Decides based of scheme which subscriptions to fake.
 * Fakes iff any of the identifiers in the bundle has one of these schemes
 */
public class BySchemeFakeSubscriptionSelector implements FakeSubscriptionSelector {

  private final Set<ExternalScheme> _toFake;

  public BySchemeFakeSubscriptionSelector(String... toFakes) {
    this(getSchemes(toFakes));
  }

  public BySchemeFakeSubscriptionSelector(ExternalScheme... toFakes) {
    this(Sets.newHashSet(toFakes));
  }

  public BySchemeFakeSubscriptionSelector(Set<ExternalScheme> toFake) {
    _toFake = toFake;
  }

  @Override
  public ObjectsPair<Collection<LiveDataSpecification>, Collection<LiveDataSpecification>> splitShouldFake(
      FakeSubscriptionBloombergLiveDataServer server, Collection<LiveDataSpecification> specs) {
    if (specs.isEmpty()) {
      return ObjectsPair.of((Collection<LiveDataSpecification>) new ArrayList<LiveDataSpecification>(), (Collection<LiveDataSpecification>) new ArrayList<LiveDataSpecification>());
    }

    Set<LiveDataSpecification> fakes = new HashSet<LiveDataSpecification>();
    Set<LiveDataSpecification> underlyings = new HashSet<LiveDataSpecification>();

    for (LiveDataSpecification liveDataSpecification : specs) {
      if (shouldFake(liveDataSpecification)) {
        fakes.add(liveDataSpecification);
      } else {
        underlyings.add(liveDataSpecification);
      }
    }

    return ObjectsPair.of((Collection<LiveDataSpecification>) underlyings, (Collection<LiveDataSpecification>) fakes);
  }

  private boolean shouldFake(LiveDataSpecification liveDataSpecification) {
    for (ExternalScheme scheme : _toFake) {
      if (liveDataSpecification.getIdentifier(scheme) != null) {
        return true;
      }
    }
    return false;
  }

  private static Set<ExternalScheme> getSchemes(String[] schemes) {
    HashSet<ExternalScheme> ret = new HashSet<ExternalScheme>();
    for (String scheme : schemes) {
      ret.add(ExternalScheme.of(scheme));
    }
    return ret;
  }
}


text:
package org.aries.launcher;

import java.util.ArrayList;
import java.util.List;

import junit.framework.TestCase;

import org.aries.launcher.ProcessLauncher;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class ProcessLauncherIT extends TestCase {

	private ProcessLauncher fixture;

	@Before
	public void setUp() throws Exception {
		super.setUp();
		fixture = new ProcessLauncher();
	}

	@After
	public void tearDown() throws Exception {
		fixture = null;
		super.tearDown();
	}

	protected String createCommandForTest() {
		return "java ";
	}

	@Test
	public void testProcessLauncher() throws Exception {
		assertNotNull("ObjectName should be set", fixture.getObjectName());
	}

	@Test
	public void testGetUserDirectory() throws Exception {
		assertNotNull("ObjectName should be set", fixture.getUserDirectory());
		String userDir = System.getProperty("user.dir");
		assertEquals("UserDirectory should be correct", userDir, fixture.getUserDirectory());
	}

	@Test
	@Ignore //needs a real command
	public void testGetRunnable() throws Exception {
		fixture.setRunner(null);
		Runnable runnable = fixture.getRunner();
		assertNotNull("Runnable should be set", runnable);
		assertEquals("Runnable should be same", runnable, fixture.getRunner());
		MockProcessExecuter mockExecuter = new MockProcessExecuter();
		fixture.setExecuter(mockExecuter);
		List<String> command = new ArrayList<String>();
		command.add("command");
		fixture.setCommand(command);
		runnable.run();
		assertTrue("ProcessExecuter should have been run", mockExecuter.wasRun());
	}

	@Test
	public void testStart() throws Exception {
		MockRunnable mockRunnable = new MockRunnable();
		fixture.setRunner(mockRunnable);
		fixture.setThread(null);
		fixture.start();
		assertTrue("Thread should be alive", fixture.getThread().isAlive());
		assertFalse("Thread should not be interrupted", fixture.getThread().isInterrupted());
		fixture.getThread().join();
		assertTrue("Runnable should have been run", mockRunnable.wasRun());
	}

	@Test
	public void testDestroy() throws Exception {
		MockProcess mockProcess = new MockProcess();
		fixture.setProcess(mockProcess);
		fixture.destroy();
		assertTrue("Process should have been destroyed", mockProcess.wasDestroyed());
		assertNull("Process should now be null", fixture.getProcess());
	}

}


text:
export default loadFn => {
    const proto = {
        load(loaders) {
            loaders.push(loadFn)
        }
    };

    return Object.assign(Object.create(proto), {});
}


text:
<?php

error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_WARNING);

class main extends spController
{
    //------------------  后台页面请求---------------------------------
    function index()
    {
        $this->display('home/index.html');
    }

    function login()
    {
        $this->display('login/login.html');
    }

    function admin() {

        session_start();
        if(!isset($_GET['sid']) || is_null($_GET['sid']) || $_SESSION[$_GET['sid']] != true) {
            $this->display('login/login.html');
            return;
        }

        $this->display('index/admin.html');
    }

    function allworks(){
        $this->display('index/allworks.html');
    }

    function addwork() {
        $this->display('index/addwork.html');
    }

    function viewschema() {
        $this->display('index/viewschema.html');
    }

    function setschema() {
        $this->display('index/setschema.html');
    }

    function update_account_view() {
        $this->display('index/update_account.html');
    }

    function result_set() {
        $this->display('index/result_set.html');
    }

    function result_view() {
        $this->display('index/result_view.html');
    }

    function reward_item() {
        $this->display('index/reward_item.html');
    }

    // ------------投票页面请求--------------------------
    function vote_notice() {
        $this->display('home/entries.html');
    }

    function vote_result() {
        $this->display('home/results.html');
    }

    function work_vote() {
        $this->display('home/shortlisted.html');
    }

    function dep_intro() {
        $this->display('home/into.html');
    }

}


text:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace AgeRanger.Entities
{
    [Table("AgeGroup")]
    public class AgeGroup
    {
        [Key]
        public long Id { get; set; }

        public int? MinAge { get; set; }

        public int? MaxAge { get; set; }

        public string Description { get; set; }
    }
}


text:
You are given an ecosystem simulation API that gives the base for creating organisms, moving organisms and handling encounters between organisms. The API includes an engine, which controls the simulation world and executes commands on the objects within it. You are also given a C# file, which has a Main method and uses the API for processing commands from the input.

There are some simple rules the simulation API supports:

*	Objects can be created anywhere
*	There are 3 major types of objects – carnivores (meat-eaters), herbivores (plant-eaters) and plants
	o	carnivores can eat herbivores and other carnivores
	o	herbivores can eat plants
*	Objects can go anywhere if they support the "go" command
	o	Only one object can move at a time
	o	When one object moves, all objects (including the moving one) get "updated" with the time required for the moving object to travel (the time is determined by the Manhattan distance between the start and end positions).
	o	When the moved object gets to a position where other objects are located, it "encounters" all of them – it tries to eat them, according to the rules above
*	Objects can sleep
*	Some objects change their size when eating or sleeping

The following lines will help you better understand the API.

###Important Classes and Interfaces

These are the API's interfaces:

*	IOrganism – provides base properties and methods, supported by all organisms – IsAlive, Location, Size
*	IHerbivore – represents a plant-eater and provides a method EatPlant(Plant), which is called when the object encounters other objects. Eating a plant could reduce its size or kill it. Note: The proper way to implement the EatPlant method is to call the passed plant's GetEatenQuantity(int). EatPlant must also return the eaten quantity.
*	ICarnivore – represents a meat-eater and provides a method TryEatAnimal(Animal), which is called when the object encounters other objects. The carnivore could fail in eating the animal, but if it succeeds, the animal dies. Note: The proper way to implement the TryEatAnimal method is to call the passed animal's GetMeatFromKillQuantity(). The TryEatAnimal method must return the quantity of meat eaten.

These are the API's classes and structures:

*	Point – struct, represents a two-dimensional point with integer coordinates and provides a Parse(string) and overloaded ToString() method, along with a GetManhattanDistance(Point, Point) static method
*	Organism – abstract implementation of the IOrganism interface. Has an overloaded ToString() method
*	Animal – abstract base for all animals (organisms which can move), which can execute "go" and "sleep" commands. Provides the respective GoTo(Point) and Sleep(int) commands. Also provides an implementation of the GetMeatFromKillQuantity() method, which kills the animal and returns its meat value. Also has a State property, indicating whether the animal is sleeping or awake. Has a Name and an overloaded ToString() method
*	Plant – abstract base for organisms that never change their position. Has a GetEatenQuantity(int) method, which takes a "bite size" and reduces the size of the plant by that bite size (if the plant is bigger), or kills the plant and sets its size to 0, if the bite is larger than the plant's size. The method returns the change in size of the plant (i.e. the "eaten" quantity). Has an overloaded ToString() method
*	Tree and Bush – plants with a predefined size
*	Deer – animal class, implementation of the IHerbivore interface. Does not change in any way when eating.
*	Engine – handles commands and executes them on the simulation world, keeps several lists of the objects in it, provides methods for adding objects and removes dead objects after each "go" command

###Commands

There are two types of commands the Engine supports:

*	Organism birth command – creates an object in the world
	o	Format: birth <object-type-name> <object-parameters…>
	o	Example: birth tree (0,0) – creates a tree at the position (0, 0)
	o	Example: birth deer Rudolf (0,0) – creates a deer with the name Rudolf at position (0,0)
*	Object instance command – orders an object to execute a command. If the object executes the command, a string is printed.
	o	Format: <command-name> <object-name> <command-parameters>
	o	Commands:
			sleep <object-name> <time>
			go <object-name> <position>
	o	Example: sleep Rudolf 10 – puts the animal with the name Rudolf to sleep for 10 time units
	o	Example: go Rudolf (5,5) – sends the animal with the name Rudolf to position (5,5), updates all objects with the elapsed time and checks for possible encounters with other organisms

Here is a list of all commands the Engine supports currently:

*	birth tree <position> - creates a tree at the specified coordinates
*	birth bush <position> - creates a bush at the specified coordinates
*	birth deer <name> <coordinates> - creates a deer with the specified name at the specified coordinates
*	sleep <name> <time> - puts the animal with the specified name to sleep for the specified time
*	go <name> coordinates – moves the animal with the specified name to the specified coordinates, updates all objects with the elapsed time (calculated by Manhattan distance from the object position to the object destination) and checks for encounters

The Engine handles all listed commands and you shouldn't write your own parsing code for these commands.

Study the aforementioned classes to get a better understanding of how they work and how the Engine class handles the listed commands.

###Tasks

You are tasked with extending the API by implementing several commands and object types. You are not allowed to edit any existing class from the original code of the API. You are not allowed to edit the Main method. You are allowed to edit the GetEngineInstance() method.

*	Implement a command to create a Wolf. The Wolf should be an animal and should have a Size of 4. The Wolf should be able to eat any animal smaller than or as big as him, or any animal which is sleeping.
	o	Format: birth wolf <name> <position> - creates a Wolf at the specified position with the specified name
	o	Example: birth wolf Joro (1,1) – creates a Wolf with the name Joro, at coordinates (1, 1)
*	Implement a command to create a Lion. The Lion should be an animal and should have a Size of 6. The Lion should be able to eat any animal, which is at most twice larger than him (inclusive). Also, the Lion should grow by 1 with each animal it eats.
	o	Format: birth lion <name> <position> - creates a Lion at the specified position with the specified name
*	Implement a command to create Grass. The Grass should be a plant and should have a Size of 2. The Grass should grow by 1 at each time unit (i.e. by as much as the timeElapsed parameter is in the Update method), if it IsAlive.
	o	Format: birth grass <position> - creates grass at the specified position
	o	Example: birth grass (1,2) – creates grass at coordinates (1,2)
*	Implement a command to create a Boar. The Boar should be an animal and should have a Size of 4. The Boar should be able to eat any animal, which is smaller than him or as big as him. The Boar should be able to eat from any plant. The Boar always has a bite size of 2. When eating from a plant, the Boar increases its size by 1.
	o	Format: birth boar <name> <position> - creates a boar at the specified position, with the specified name
	o	Example: birth boar Gruhcho (7,-3) – creates a boar at the coordinates (7,-3), with the name Gruhcho
*	Implement a command to create a Zombie. The Zombie should be an animal and should not be able to eat. When a carnivore (of the so-far existing) tries to eat a Zombie, it should always succeed and receive 10 meat from the Zombie. However, the Zombie should never die.
	o	Format: birth zombie <name> <position> - creates a zombie with the specified name at the specified position
	o	Example: birth zombie Joro (0,0) – creates a zombie named Joro at the coordinates (0,0)

###Input and Output Data

You should not concern yourself with handling input and output data – the engine does it for you. You should only consider how to implement the required creation commands. See the existing Engine code for hints. Also:

*	The names in the commands will always consist of upper and lowercase English letters only. The numbers in the commands will always be 32-bit signed integers (System.Int32).
*	There will never be two plants at the same position, nor two organisms with the same names.


text:
<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "sys_list_apprever".
 *
 * @property integer $id
 * @property integer $document_id
 * @property string $table_name
 * @property integer $table_key
 * @property string $title
 * @property string $option
 * @property integer $user_id
 * @property integer $user_apprever_id
 * @property string $user_apprever_name
 * @property string $link
 * @property string $description
 * @property integer $app_status
 * @property integer $status
 * @property integer $company_id
 * @property integer $site_id
 * @property string $color_code
 */
class ListMessage extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'sys_list_message';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['document_id', 'table_key', 'user_id', 'user_approver_id', 'app_status', 'status', 'company_id', 'site_id'], 'integer'],
            [['title', 'option', 'link', 'description'], 'string'],
            [['table_name'], 'string', 'max' => 100],
            [['user_approver_name'], 'string', 'max' => 255],
            [['color_code'], 'string', 'max' => 20],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'document_id' => 'Document ID',
            'table_name' => 'Table Name',
            'table_key' => 'Table Key',
            'table_key2' => 'Table Key2',
            'title' => 'Title',
            'option' => 'Option',
            'user_id' => 'User ID',
            'user_approver_id' => 'User Approver ID',
            'user_approver_name' => 'User Approver Name',
            'link' => 'Link',
            'description' => 'Description',
            'app_status' => 'สถานะ',
            'status' => 'Status',
            'company_id' => 'Company ID',
            'site_id' => 'Site ID',
            'color_code' => 'Color Code',
        ];
    }

    public function getDocuments()
    {
        return $this->hasOne(SysDocument::className(), ['document_id' => 'document_id']);
    }
}


text:
/** api: example[wms-capabilities]
 *  WMS Capabilities Store
 *  ----------------------
 *  Create layer records from WMS capabilities documents.
 */

var store;
Ext.onReady(function() {

    // create a new WMS capabilities store
    store = new GeoExt.data.WMSCapabilitiesStore({
        url: "data/wmscap.xml"
    });
    // load the store with records derived from the doc at the above url
    store.load();

    // create a grid to display records from the store
    var grid = new Ext.grid.GridPanel({
        title: "WMS Capabilities",
        store: store,
        columns: [
            {header: "Title", dataIndex: "title", sortable: true},
            {header: "Name", dataIndex: "name", sortable: true},
            {header: "Queryable", dataIndex: "queryable", sortable: true, width: 70},
            {id: "description", header: "Description", dataIndex: "abstract"}
        ],
        autoExpandColumn: "description",
        renderTo: "capgrid",
        height: 300,
        width: 650,
        listeners: {
            rowdblclick: mapPreview
        }
    });

    function mapPreview(grid, index) {
        var record = grid.getStore().getAt(index);
        var layer = record.getLayer().clone();

        var win = new Ext.Window({
            title: "Preview: " + record.get("title"),
            width: 512,
            height: 256,
            layout: "fit",
            items: [{
                xtype: "gx_mappanel",
                layers: [layer],
                extent: record.get("llbbox")
            }]
        });
        win.show();
    }

});


text:
'''
Web scraping using BeautifulSoup. Extracts blog title and list of blog posts linked from homepage.

Uses BeautifulSoup, install it with sudo pip install beautifulsoup4 or
[http://www.crummy.com/software/BeautifulSoup/] for more info
'''

import urllib2
import urllib
import re
from bs4 import BeautifulSoup

page = urllib.urlopen("http://www.techzilo.com/").read()
count = 5       #no of post links to scrap

soup = BeautifulSoup(page)

print soup.title.string

print "\nBlog posts:"

i = 0

for title in soup.findAll("h1", {"class": "entry-title"}):
    print title.a.string
    print title.a.get('href'), "\n"
    i = i+1
    if i == count:
        break

'''
for title in soup.findAll("h1", {"class": "entry-title"}):
    print title.findChildren()[0].renderContents()
    print title.findChildren()[0].get("href"), "\n"
    i = i+1
    if i == count:
        break
'''


text:
// Copyright 2014 Cubane Canada, Inc.  All rights reserved.
// See LICENSE for details.

/*---
es6id: S25.4.4.3_A7.1_T3
author: Sam Mikes
description: Promise.race([p1, p2]) settles when first settles
includes: [PromiseHelper.js]
---*/

var sequence = [];

var p1 = new Promise(function () {}),
    p2 = Promise.resolve(2),
    p = Promise.race([p1, p2]);

sequence.push(1);

p.then(function (arg) {
    if (arg !== 2) {
        $ERROR("Expected promise to be fulfilled with 2, got " + arg);
    }

    sequence.push(4);
    checkSequence(sequence, "This happens second");
}).catch($DONE);

Promise.resolve().then(function () {
    sequence.push(3);
    checkSequence(sequence, "This happens first");
}).then(function () {
    sequence.push(5);
    checkSequence(sequence, "This happens third");
}).then($DONE, $DONE);

sequence.push(2);


text:
export { Benchmark } from './benchmark';
export { BenchmarkService } from './benchmark.service';
export { BenchmarkComponent } from './benchmark.component';


text:
using SurgSim::Math::BoxShape;
using SurgSim::Math::SphereShape;

namespace SurgSim
{
namespace Collision
{

void doBoxSphereTest(std::shared_ptr<BoxShape> box,
					 const Quaterniond& boxQuat,
					 const Vector3d& boxTrans,
					 std::shared_ptr<SphereShape> sphere,
					 const Quaterniond& sphereQuat,
					 const Vector3d& sphereTrans,
					 bool hasContacts = false,
					 double expectedDepth = 0.0,
					 Vector3d expectedNormal = Vector3d::UnitX(),
					 Vector3d expectedPenetrationPoint0 = Vector3d::Zero(),
					 Vector3d expectedPenetrationPoint1 = Vector3d::Zero())
{
	using SurgSim::Math::Geometry::DistanceEpsilon;
	using SurgSim::Math::Geometry::ScalarEpsilon;

	std::shared_ptr<ShapeCollisionRepresentation> boxRep =
		std::make_shared<ShapeCollisionRepresentation>("Collision Box 0");
	boxRep->setShape(box);
	boxRep->setLocalPose(SurgSim::Math::makeRigidTransform(boxQuat, boxTrans));

	std::shared_ptr<ShapeCollisionRepresentation> sphereRep =
		std::make_shared<ShapeCollisionRepresentation>("Collision Sphere 0");
	sphereRep->setShape(sphere);
	sphereRep->setLocalPose(SurgSim::Math::makeRigidTransform(sphereQuat, sphereTrans));

	// Perform collision detection.
	BoxSphereContact calcContact;
	std::shared_ptr<CollisionPair> pair = std::make_shared<CollisionPair>(boxRep, sphereRep);
	calcContact.calculateContact(pair);

	// Compare contact info.
	EXPECT_EQ(hasContacts, pair->hasContacts());
	if (pair->hasContacts())
	{
		std::shared_ptr<Contact> contact = pair->getContacts().front();
		EXPECT_TRUE(eigenEqual(expectedNormal, contact->normal));
		EXPECT_NEAR(expectedDepth, contact->depth, DistanceEpsilon);
		EXPECT_TRUE(contact->penetrationPoints.first.rigidLocalPosition.hasValue());
		EXPECT_TRUE(contact->penetrationPoints.second.rigidLocalPosition.hasValue());

		EXPECT_TRUE(eigenEqual(expectedPenetrationPoint0,
							   contact->penetrationPoints.first.rigidLocalPosition.getValue()));
		EXPECT_TRUE(eigenEqual(expectedPenetrationPoint1,
							   contact->penetrationPoints.second.rigidLocalPosition.getValue()));
	}
}

TEST(BoxSphereContactCalculationTests, UnitTests)
{
	std::shared_ptr<BoxShape> box = std::make_shared<BoxShape>(1.0, 1.0, 1.0);
	std::shared_ptr<SphereShape> sphere = std::make_shared<SphereShape>(1.0);
	SurgSim::Math::Quaterniond boxQuat;
	SurgSim::Math::Vector3d boxTrans;
	SurgSim::Math::Quaterniond sphereQuat;
	SurgSim::Math::Vector3d sphereTrans;
	SurgSim::Math::Quaterniond globalQuat;
	SurgSim::Math::Vector3d globalTrans;

	{
		SCOPED_TRACE("No Intersection");
		boxQuat.setIdentity();
		boxTrans = Vector3d(100.0,0.0,0.0);
		sphereQuat.setIdentity();
		sphereTrans = Vector3d(0.0,0.0,0.0);
		doBoxSphereTest(box, boxQuat, boxTrans, sphere, sphereQuat, sphereTrans, false);
	}

	{
		SCOPED_TRACE("Intersection on top face");
		boxQuat.setIdentity();
		boxTrans = Vector3d(0.0,0.0,0.0);
		sphereQuat.setIdentity();
		sphereTrans = Vector3d(0.0,1.0,0.0);
		globalQuat = SurgSim::Math::makeRotationQuaternion(0.35465, Vector3d(0.3454, 0.78567, 0.234346).normalized());
		globalTrans = Vector3d(24.6,-32.67,87.53);
		boxQuat = globalQuat * boxQuat;
		boxTrans = globalQuat * boxTrans + globalTrans;
		sphereQuat = globalQuat * sphereQuat;
		sphereTrans = globalQuat * sphereTrans + globalTrans;
		doBoxSphereTest(box, boxQuat, boxTrans, sphere, sphereQuat, sphereTrans, true,
						0.5, // depth
						boxQuat * Vector3d(0.0,-1.0,0.0), // normal points into first representation of CollisionPair
						Vector3d(0.0,0.5,0.0), // box penetration point
						Vector3d(0.0,-1.0,0.0)); // sphere penetration point
	}

	{
		SCOPED_TRACE("Sphere center inside box, intersection on top face");
		boxQuat.setIdentity();
		boxTrans = Vector3d(0.0,0.0,0.0);
		sphereQuat.setIdentity();
		sphereTrans = Vector3d(0.0,0.05,0.0);
		globalQuat = SurgSim::Math::makeRotationQuaternion(0.35465, Vector3d(0.3454, 0.78567, 0.234346).normalized());
		globalTrans = Vector3d(24.6,-32.67,87.53);
		boxQuat = globalQuat * boxQuat;
		boxTrans = globalQuat * boxTrans + globalTrans;
		sphereQuat = globalQuat * sphereQuat;
		sphereTrans = globalQuat * sphereTrans + globalTrans;
		doBoxSphereTest(box, boxQuat, boxTrans, sphere, sphereQuat, sphereTrans, true,
			1.45, // depth
			boxQuat * Vector3d(0.0,-1.0,0.0), // normal points into first representation of CollisionPair
			Vector3d(0.0,0.5,0.0), // box penetration point
			Vector3d(0.0,-1.0,0.0)); // sphere penetration point
	}

	{
		SCOPED_TRACE("Intersection on bottom face");
		boxQuat.setIdentity();
		boxTrans = Vector3d(0.0,0.0,0.0);
		sphereQuat.setIdentity();
		sphereTrans = Vector3d(0.3345,-1.2,0.1234);
		globalQuat = SurgSim::Math::makeRotationQuaternion(-0.35465,
														   Vector3d(18.3454, -27.78567, 23.234346).normalized());
		globalTrans = Vector3d(234.6,326.67,987.53);
		boxQuat = globalQuat * boxQuat;
		boxTrans = globalQuat * boxTrans + globalTrans;
		sphereQuat = globalQuat * sphereQuat;
		sphereTrans = globalQuat * sphereTrans + globalTrans;
		doBoxSphereTest(box, boxQuat, boxTrans, sphere, sphereQuat, sphereTrans, true,
						0.3, // depth
						boxQuat * Vector3d(0.0,1.0,0.0), // normal points into first representation of CollisionPair
						Vector3d(0.3345,-0.5,0.1234), // box penetration point
						Vector3d(0.0,1.0,0.0)); // sphere penetration point
	}

	{
		SCOPED_TRACE("Sphere center inside box, intersection on bottom face");
		boxQuat.setIdentity();
		boxTrans = Vector3d(0.0,0.0,0.0);
		sphereQuat.setIdentity();
		sphereTrans = Vector3d(0.3345,-0.4,0.1234);
		globalQuat = SurgSim::Math::makeRotationQuaternion(-0.35465,
			Vector3d(18.3454, -27.78567, 23.234346).normalized());
		globalTrans = Vector3d(234.6,326.67,987.53);
		boxQuat = globalQuat * boxQuat;
		boxTrans = globalQuat * boxTrans + globalTrans;
		sphereQuat = globalQuat * sphereQuat;
		sphereTrans = globalQuat * sphereTrans + globalTrans;
		doBoxSphereTest(box, boxQuat, boxTrans, sphere, sphereQuat, sphereTrans, true,
			1.1, // depth
			boxQuat * Vector3d(0.0,1.0,0.0), // normal points into first representation of CollisionPair
			Vector3d(0.3345,-0.5,0.1234), // box penetration point
			Vector3d(0.0,1.0,0.0)); // sphere penetration point
	}

	{
		SCOPED_TRACE("Intersection on right face");
		boxQuat.setIdentity();
		boxTrans = Vector3d(23.545,3.4321,5.3421);
		sphereQuat.setIdentity();
		sphereTrans = boxTrans + Vector3d(1.2324,-0.2354,0.412);
		globalQuat = SurgSim::Math::makeRotationQuaternion(1.285, Vector3d(23.446, 13.786, 32.254).normalized());
		globalTrans = Vector3d(-249.6,532.67,977.53);
		boxQuat = globalQuat * boxQuat;
		boxTrans = globalQuat * boxTrans + globalTrans;
		sphereQuat = globalQuat * sphereQuat;
		sphereTrans = globalQuat * sphereTrans + globalTrans;
		doBoxSphereTest(box, boxQuat, boxTrans, sphere, sphereQuat, sphereTrans, true,
						0.2676, // depth
						boxQuat * Vector3d(-1.0,0.0,0.0), // normal points into first representation of CollisionPair
						Vector3d(0.5,-0.2354,0.412), // box penetration point
						Vector3d(-1.0,0.0,0.0)); // sphere penetration point
	}

	{
		SCOPED_TRACE("Sphere center inside box, intersection on right face");
		boxQuat.setIdentity();
		boxTrans = Vector3d(23.545,3.4321,5.3421);
		sphereQuat.setIdentity();
		sphereTrans = boxTrans + Vector3d(0.45,-0.2354,0.412);
		globalQuat = SurgSim::Math::makeRotationQuaternion(1.285, Vector3d(23.446, 13.786, 32.254).normalized());
		globalTrans = Vector3d(-249.6,532.67,977.53);
		boxQuat = globalQuat * boxQuat;
		boxTrans = globalQuat * boxTrans + globalTrans;
		sphereQuat = globalQuat * sphereQuat;
		sphereTrans = globalQuat * sphereTrans + globalTrans;
		doBoxSphereTest(box, boxQuat, boxTrans, sphere, sphereQuat, sphereTrans, true,
			1.05, // depth
			boxQuat * Vector3d(-1.0,0.0,0.0), // normal points into first representation of CollisionPair
			Vector3d(0.5,-0.2354,0.412), // box penetration point
			Vector3d(-1.0,0.0,0.0)); // sphere penetration point
	}

	{
		SCOPED_TRACE("Intersection on left face");
		boxQuat.setIdentity();
		boxTrans = Vector3d(876.324,6754.23,7343.76);
		sphereQuat.setIdentity();
		sphereTrans = boxTrans + Vector3d(-1.1223,0.2354,-0.412);
		globalQuat = SurgSim::Math::makeRotationQuaternion(0.276, Vector3d(0.945, 1.532, 0.896).normalized());
		globalTrans = Vector3d(-24.6,32.67,97.53);
		boxQuat = globalQuat * boxQuat;
		boxTrans = globalQuat * boxTrans + globalTrans;
		sphereQuat = globalQuat * sphereQuat;
		sphereTrans = globalQuat * sphereTrans + globalTrans;
		doBoxSphereTest(box, boxQuat, boxTrans, sphere, sphereQuat, sphereTrans, true,
						0.3777, // depth
						boxQuat * Vector3d(1.0,0.0,0.0), // normal points into first representation of CollisionPair
						Vector3d(-0.5,0.2354,-0.412), // box penetration point
						Vector3d(1.0,0.0,0.0)); // sphere penetration point
	}

	{
		SCOPED_TRACE("Sphere center inside box, intersection on left face");
		boxQuat.setIdentity();
		boxTrans = Vector3d(876.324,6754.23,7343.76);
		sphereQuat.setIdentity();
		sphereTrans = boxTrans + Vector3d(-0.3,0.2354,-0.012);
		globalQuat = SurgSim::Math::makeRotationQuaternion(0.276, Vector3d(0.945, 1.532, 0.896).normalized());
		globalTrans = Vector3d(-24.6,32.67,97.53);
		boxQuat = globalQuat * boxQuat;
		boxTrans = globalQuat * boxTrans + globalTrans;
		sphereQuat = globalQuat * sphereQuat;
		sphereTrans = globalQuat * sphereTrans + globalTrans;
		doBoxSphereTest(box, boxQuat, boxTrans, sphere, sphereQuat, sphereTrans, true,
			1.2, // depth
			boxQuat * Vector3d(1.0,0.0,0.0), // normal points into first representation of CollisionPair
			Vector3d(-0.5,0.2354,-0.012), // box penetration point
			Vector3d(1.0,0.0,0.0)); // sphere penetration point
	}

	{
		SCOPED_TRACE("Intersection on front face");
		boxQuat.setIdentity();
		boxTrans = Vector3d(0.3252,-0.64564,0.12345);
		sphereQuat.setIdentity();
		sphereTrans = boxTrans + Vector3d(0.1564,-0.2987,-0.8986);
		globalQuat = SurgSim::Math::makeRotationQuaternion(-1.32, Vector3d(235.67, 215.567, 146.345).normalized());
		globalTrans = Vector3d(224.6,132.67,27.53);
		boxQuat = globalQuat * boxQuat;
		boxTrans = globalQuat * boxTrans + globalTrans;
		sphereQuat = globalQuat * sphereQuat;
		sphereTrans = globalQuat * sphereTrans + globalTrans;
		doBoxSphereTest(box, boxQuat, boxTrans, sphere, sphereQuat, sphereTrans, true,
						0.6014, // depth
						boxQuat * Vector3d(0.0,0.0,1.0), // normal points into first representation of CollisionPair
						Vector3d(0.1564,-0.2987,-0.5), // box penetration point
						Vector3d(0.0,0.0,1.0)); // sphere penetration point
	}

	{
		SCOPED_TRACE("Sphere center inside box, intersection on front face");
		boxQuat.setIdentity();
		boxTrans = Vector3d(0.3252,-0.64564,0.12345);
		sphereQuat.setIdentity();
		sphereTrans = boxTrans + Vector3d(0.1564,-0.2987,-0.3986);
		globalQuat = SurgSim::Math::makeRotationQuaternion(-1.32, Vector3d(235.67, 215.567, 146.345).normalized());
		globalTrans = Vector3d(224.6,132.67,27.53);
		boxQuat = globalQuat * boxQuat;
		boxTrans = globalQuat * boxTrans + globalTrans;
		sphereQuat = globalQuat * sphereQuat;
		sphereTrans = globalQuat * sphereTrans + globalTrans;
		doBoxSphereTest(box, boxQuat, boxTrans, sphere, sphereQuat, sphereTrans, true,
			1.1014, // depth
			boxQuat * Vector3d(0.0,0.0,1.0), // normal points into first representation of CollisionPair
			Vector3d(0.1564,-0.2987,-0.5), // box penetration point
			Vector3d(0.0,0.0,1.0)); // sphere penetration point
	}

	{
		SCOPED_TRACE("Intersection on back face");
		boxQuat.setIdentity();
		boxTrans = Vector3d(24.345,-865.325,46.345);
		sphereQuat.setIdentity();
		sphereTrans = boxTrans + Vector3d(-0.2564,-0.4987,0.7986);
		globalQuat = SurgSim::Math::makeRotationQuaternion(1.2, Vector3d(25.67, -25.567, 16.345).normalized());
		globalTrans = Vector3d(24.6,3243.67,9762.53);
		boxQuat = globalQuat * boxQuat;
		boxTrans = globalQuat * boxTrans + globalTrans;
		sphereQuat = globalQuat * sphereQuat;
		sphereTrans = globalQuat * sphereTrans + globalTrans;
		doBoxSphereTest(box, boxQuat, boxTrans, sphere, sphereQuat, sphereTrans, true,
						0.7014, // depth
						boxQuat * Vector3d(0.0,0.0,-1.0), // normal points into first representation of CollisionPair
						Vector3d(-0.2564,-0.4987,0.5), // box penetration point
						Vector3d(0.0,0.0,-1.0)); // sphere penetration point
	}

	{
		SCOPED_TRACE("Sphere center inside box, intersection on back face");
		boxQuat.setIdentity();
		boxTrans = Vector3d(24.345,-865.325,46.345);
		sphereQuat.setIdentity();
		sphereTrans = boxTrans + Vector3d(-0.2564,-0.3987,0.48);
		globalQuat = SurgSim::Math::makeRotationQuaternion(1.2, Vector3d(25.67, -25.567, 16.345).normalized());
		globalTrans = Vector3d(24.6,3243.67,9762.53);
		boxQuat = globalQuat * boxQuat;
		boxTrans = globalQuat * boxTrans + globalTrans;
		sphereQuat = globalQuat * sphereQuat;
		sphereTrans = globalQuat * sphereTrans + globalTrans;
		doBoxSphereTest(box, boxQuat, boxTrans, sphere, sphereQuat, sphereTrans, true,
			1.02, // depth
			boxQuat * Vector3d(0.0,0.0,-1.0), // normal points into first representation of CollisionPair
			Vector3d(-0.2564,-0.3987,0.5), // box penetration point
			Vector3d(0.0,0.0,-1.0)); // sphere penetration point
	}
}

}; // namespace Collision
}; // namespace SurgSim


text:
package com.dremio.plugins.elastic;

import static java.lang.String.format;

/**
 * Indicates a data type mapping was encountered in an elasticsearch index that
 * is not supported in the Dremio elasticsearch storage plugin.
 */
public class UnsupportedTypeException extends Exception {

  private final String field;
  private final String type;

  public UnsupportedTypeException(final String field, final String type) {
    this.field = field;
    this.type = type;
  }

  @Override
  public String getMessage() {
    return format("Field [%s] declares an unsupported data type: [%s]", field, type);
  }
}


text:
<?php

namespace Yandex\Tests\Metrica\Models\Management;

use Yandex\Metrica\Management\Models;
use Yandex\Tests\TestCase;
use Yandex\Tests\Metrica\Fixtures\Operations;

class OperationResponseTest extends TestCase
{
    public function testAddOperationResponse()
    {
        $fixtures  = Operations::$operationFixtures;
        $response  = new Models\AddOperationResponse();
        $operation = new Models\Operation($fixtures['operation']);
        $response->setOperation($operation);
        $this->assertTrue($response->getOperation() instanceof Models\Operation);
    }

    public function testGetOperationResponse()
    {
        $fixtures  = Operations::$operationFixtures;
        $response  = new Models\GetOperationResponse();
        $operation = new Models\Operation($fixtures['operation']);
        $response->setOperation($operation);
        $this->assertTrue($response->getOperation() instanceof Models\Operation);
    }

    public function testGetOperationsResponse()
    {
        $fixtures   = Operations::$operationsFixtures;
        $response   = new Models\GetOperationsResponse();
        $operations = new Models\Operations($fixtures['operations']);
        $response->setOperations($operations);
        $this->assertTrue($response->getOperations() instanceof Models\Operations);
    }

    public function testUpdateOperationResponse()
    {
        $fixtures  = Operations::$operationFixtures;
        $response  = new Models\UpdateOperationResponse();
        $operation = new Models\Operation($fixtures['operation']);
        $response->setOperation($operation);
        $this->assertTrue($response->getOperation() instanceof Models\Operation);
    }
}


text:
notescript
==========

This is the scripting language for PeerTrader.


text:
from calendarserver.tools.wiki import migrateWiki
from twisted.internet.defer import inlineCallbacks
from twistedcaldav.test.util import StoreTestCase
from txdav.who.delegates import Delegates
from txdav.who.idirectory import RecordType as CalRecordType
from txdav.who.wiki import DirectoryService as WikiDirectoryService

class MigrateWikiTest(StoreTestCase):

    def configure(self):
        super(MigrateWikiTest, self).configure()
        self.patch(self.config.Authentication.Wiki, "Enabled", False)

    @inlineCallbacks
    def test_migrateWiki(self):

        # Ensure the two records do not exist yet
        record = yield self.directory.recordWithUID(u"wiki-xyzzy")
        self.assertEquals(record, None)
        record = yield self.directory.recordWithUID(u"wiki-plugh")
        self.assertEquals(record, None)

        # We need to create the calendar homes, but we can't unless there are
        # records for these uids.  Since we've disabled the wiki service above,
        # we're temporarily going to substitute a wiki directory service while
        # we create the calendar homes:
        realDirectory = self.store.directoryService()
        tmpWikiService = WikiDirectoryService("test", None)
        tmpWikiService.serversDB = lambda : None
        self.store._directoryService = tmpWikiService
        txn = self.store.newTransaction()
        yield txn.calendarHomeWithUID(u"wiki-xyzzy", create=True)
        yield txn.calendarHomeWithUID(u"wiki-plugh", create=True)
        yield txn.commit()
        self.store._directoryService = realDirectory

        # Migrate wiki principals to resources
        yield migrateWiki(self.store, "users:admin")

        txn = self.store.newTransaction()
        record = yield self.directory.recordWithUID(u"wiki-xyzzy")
        self.assertEquals(record.shortNames, [u"xyzzy"])
        self.assertEquals(record.recordType, CalRecordType.resource)
        delegates = (yield Delegates.delegatesOf(txn, record, True))
        self.assertEquals([u"admin"], [d.shortNames[0] for d in delegates])
        record = yield self.directory.recordWithUID(u"wiki-plugh")
        self.assertEquals(record.shortNames, [u"plugh"])
        self.assertEquals(record.recordType, CalRecordType.resource)
        delegates = (yield Delegates.delegatesOf(txn, record, True))
        self.assertEquals([u"admin"], [d.shortNames[0] for d in delegates])
        yield txn.commit()


text:
package org.apache.nifi.stateless.bootstrap;

import org.apache.nifi.bundle.Bundle;
import org.apache.nifi.bundle.BundleCoordinate;
import org.apache.nifi.nar.NarClassLoaders;
import org.apache.nifi.nar.NarUnpacker;
import org.apache.nifi.nar.SystemBundle;
import org.apache.nifi.stateless.config.ParameterOverride;
import org.apache.nifi.stateless.config.StatelessConfigurationException;
import org.apache.nifi.stateless.engine.NarUnpackLock;
import org.apache.nifi.stateless.engine.StatelessEngineConfiguration;
import org.apache.nifi.stateless.flow.DataflowDefinition;
import org.apache.nifi.stateless.flow.DataflowDefinitionParser;
import org.apache.nifi.stateless.flow.StatelessDataflow;
import org.apache.nifi.stateless.flow.StatelessDataflowFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.function.Predicate;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;

public class StatelessBootstrap {
    private static final Logger logger = LoggerFactory.getLogger(StatelessBootstrap.class);
    private static final Pattern STATELESS_NAR_PATTERN = Pattern.compile("nifi-stateless-nar-.*\\.nar-unpacked");
    private final ClassLoader engineClassLoader;
    private final ClassLoader extensionClassLoader;
    private final StatelessEngineConfiguration engineConfiguration;

    private StatelessBootstrap(final ClassLoader engineClassLoader, final ClassLoader extensionClassLoader, final StatelessEngineConfiguration engineConfiguration) {
        this.engineClassLoader = engineClassLoader;
        this.extensionClassLoader = extensionClassLoader;
        this.engineConfiguration = engineConfiguration;
    }

    public <T> StatelessDataflow createDataflow(final DataflowDefinition<T> dataflowDefinition)
                throws IOException, StatelessConfigurationException {
        final StatelessDataflowFactory<T> dataflowFactory = getSingleInstance(engineClassLoader, StatelessDataflowFactory.class);
        final StatelessDataflow dataflow = dataflowFactory.createDataflow(engineConfiguration, dataflowDefinition, extensionClassLoader);
        return dataflow;
    }

    public DataflowDefinition<?> parseDataflowDefinition(final File flowDefinitionFile, final List<ParameterOverride> parameterOverrides)
                throws StatelessConfigurationException, IOException {
        final DataflowDefinitionParser dataflowDefinitionParser = getSingleInstance(engineClassLoader, DataflowDefinitionParser.class);
        final DataflowDefinition<?> dataflowDefinition = dataflowDefinitionParser.parseFlowDefinition(flowDefinitionFile, engineConfiguration, parameterOverrides);
        return dataflowDefinition;
    }

    public DataflowDefinition<?> parseDataflowDefinition(final Map<String, String> flowDefinitionProperties, final List<ParameterOverride> parameterOverrides)
                throws StatelessConfigurationException, IOException {
        final DataflowDefinitionParser dataflowDefinitionParser = getSingleInstance(engineClassLoader, DataflowDefinitionParser.class);
        final DataflowDefinition<?> dataflowDefinition = dataflowDefinitionParser.parseFlowDefinition(flowDefinitionProperties, engineConfiguration, parameterOverrides);
        return dataflowDefinition;
    }

    public static StatelessBootstrap bootstrap(final StatelessEngineConfiguration engineConfiguration) throws IOException {
        return bootstrap(engineConfiguration, ClassLoader.getSystemClassLoader());
    }

    public static StatelessBootstrap bootstrap(final StatelessEngineConfiguration engineConfiguration, final ClassLoader rootClassLoader) throws IOException {
        final File narDirectory = engineConfiguration.getNarDirectory();
        final File workingDirectory = engineConfiguration.getWorkingDirectory();
        final File narExpansionDirectory = new File(workingDirectory, "nar");

        // Ensure working directory exists, creating it if necessary
        if (!narExpansionDirectory.exists() && !narExpansionDirectory.mkdirs()) {
            throw new IOException("Working Directory " + narExpansionDirectory + " does not exist and could not be created");
        }

        final Bundle systemBundle = SystemBundle.create(narDirectory.getAbsolutePath(), ClassLoader.getSystemClassLoader());
        final File frameworkWorkingDir = new File(narExpansionDirectory, "framework");
        final File extensionsWorkingDir = new File(narExpansionDirectory, "extensions");
        final List<Path> narDirectories = Collections.singletonList(narDirectory.toPath());

        // Unpack NARs
        final long unpackStart = System.currentTimeMillis();
        final Predicate<BundleCoordinate> narFilter = coordinate -> true;
        NarUnpackLock.lock();
        try {
            NarUnpacker.unpackNars(systemBundle, frameworkWorkingDir, extensionsWorkingDir, null, narDirectories, false, NarClassLoaders.FRAMEWORK_NAR_ID, false, false, narFilter);
        } finally {
            NarUnpackLock.unlock();
        }
        final long unpackMillis = System.currentTimeMillis() - unpackStart;
        logger.info("Unpacked NAR files in {} millis", unpackMillis);

        final File statelessNarWorkingDir = locateStatelessNarWorkingDirectory(extensionsWorkingDir);
        final File statelessNarInf = new File(statelessNarWorkingDir, "NAR-INF");
        final File statelessNarDependencies = new File(statelessNarInf, "bundled-dependencies");
        final File[] statelessNarContents = statelessNarDependencies.listFiles();
        if (statelessNarContents == null || statelessNarContents.length == 0) {
            throw new IOException("Could not access contents of Stateless NAR dependencies at " + statelessNarDependencies);
        }

        final List<URL> urls = new ArrayList<>();
        final List<String> filenames = new ArrayList<>();
        for (final File dependency : statelessNarContents) {
            final URL url = dependency.toURI().toURL();
            urls.add(url);
            filenames.add(dependency.getName());
        }

        logger.info("Creating Stateless Bootstrap with the following files in the classpath: {}", filenames);

        final URL[] urlArray = urls.toArray(new URL[0]);
        final BlockListClassLoader extensionClassLoader = createExtensionRootClassLoader(narDirectory, rootClassLoader);

        final Set<String> classesBlockedExtensions = extensionClassLoader.getClassesBlocked();

        // For the engine ClassLoader, we also want to block everything that we block for extensions except for the classes
        // that the engine needs specifically (i.e., the classes in the stateless engine nar). We do this because there are some
        // classes that may need to be shared between the bootstrap and the caller. For example, VersionedFlowSnapshot.
        final URLClassLoader engineUrlClassLoader = new URLClassLoader(urlArray, rootClassLoader);
        final Set<String> engineSpecificClassNames = new HashSet<>();
        final Set<String> engineSpecificFiles = new HashSet<>();
        findClassNamesInJars(urls, engineSpecificClassNames, engineSpecificFiles);

        final Set<String> classesBlockedEngine = new HashSet<>(classesBlockedExtensions);
        classesBlockedEngine.removeAll(engineSpecificClassNames);

        logger.debug("Blocking the following classes from being loaded from parent {} for Engine by Stateless ClassLoaders: {}", engineUrlClassLoader, classesBlockedEngine);
        logger.debug("Blocking the following files from being loaded from parent {} for Engine by Stateless ClassLoaders: {}", engineUrlClassLoader, engineSpecificFiles);

        final BlockListClassLoader engineClassLoader = new BlockListClassLoader(engineUrlClassLoader, classesBlockedEngine);

        Thread.currentThread().setContextClassLoader(engineClassLoader);
        return new StatelessBootstrap(engineClassLoader, extensionClassLoader, engineConfiguration);
    }

    /**
     * Creates a ClassLoader that is to be used as the 'root'/parent for all NiFi Extensions' ClassLoaders. The ClassLoader will inherit from its parent
     * any classes that exist in JAR files that can be found in the given NAR Directory. However, it will not allow any other classes to be loaded from the parent.
     * This approach is important because we need to ensure that the ClassLoader that is provided to extensions when run from NiFi Stateless is the same as the ClassLoader
     * that will be provided to it in traditional NiFi. Whereas in traditional NiFi, we have the ability to control the System ClassLoader, Stateless NiFi is designed to be
     * embedded, so we cannot control the System ClassLoader of the embedding application. This gives us a way to ensure that we control what is available to Extensions and
     * still provides us the ability to load the necessary classes from the System ClassLoader, which prevents ClassCastExceptions that might otherwise occur if we were to
     * load the same classes from another ClassLoader.
     *
     * @param narDirectory the NAR directory whose .jar files should be made available via the parent.
     * @param parent the parent class loader that the given BlockListClassLoader should delegate to for classes that it does not block
     * @return a BlockListClassLoader that allows only the appropriate classes to be loaded from the given parent
     */
    private static BlockListClassLoader createExtensionRootClassLoader(final File narDirectory, final ClassLoader parent) throws IOException {
        if (!(parent instanceof URLClassLoader)) {
            return new BlockListClassLoader(parent, Collections.emptySet());
        }

        final File[] narDirectoryFiles = narDirectory.listFiles();
        if (narDirectoryFiles == null) {
            throw new IOException("Could not get a listing of the NAR directory");
        }

        logger.debug("NAR directory used to find files to allow being loaded by Stateless Extension Classloaders from parent {}: {}", parent, narDirectory);

        final Set<URL> urls = new HashSet<>();
        findClassLoaderUrls(parent, urls);

        final Set<String> classesBlocked = new HashSet<>();
        final Set<String> filesBlocked = new HashSet<>();
        findClassNamesInJars(urls, classesBlocked, filesBlocked);

        final Set<String> classesAllowed = new HashSet<>();
        final Set<String> filesAllowed = new HashSet<>();
        for (final File file : narDirectoryFiles) {
            findClassNamesInJar(file, classesAllowed);
            filesAllowed.add(file.getName());
        }

        final File java11Directory = new File(narDirectory, "java11");
        final File[] java11DirectoryFiles = java11Directory.listFiles();
        if (java11DirectoryFiles != null) {
            for (final File file : java11DirectoryFiles) {
                findClassNamesInJar(file, classesAllowed);
                filesAllowed.add(file.getName());
            }
        }
        logger.debug("The following JAR files are proposed to be blocked from being loaded by Stateless Extensions ClassLoaders from parent {}: {}", parent, filesBlocked);
        logger.debug("Of the full list above, the following JAR files will be explicitly allowed to be loaded by Stateless Extensions ClassLoaders from parent {}: {}", parent, filesAllowed);

        classesBlocked.removeAll(classesAllowed);
        filesBlocked.removeAll(filesAllowed);
        logger.debug("The final list of JAR files blocked from being loaded by Stateless Extensions ClassLoaders from parent {}: {}", parent, filesBlocked);

        logger.debug("The final list of classes blocked from being loaded by Stateless Extension ClassLoaders from parent {}: {}", parent, classesBlocked);

        final BlockListClassLoader blockingClassLoader = new BlockListClassLoader(parent, classesBlocked);
        return blockingClassLoader;
    }

    private static void findClassNamesInJars(final Collection<URL> jarUrls, final Set<String> classesFound, final Set<String> jarFilesFound) throws IOException {
        for (final URL url : jarUrls) {
            final File file;
            try {
                file = new File(url.toURI());
            } catch (URISyntaxException e) {
                logger.warn("Could not find file for {} in classpath", url);
                continue;
            }

            findClassNamesInJar(file, classesFound);
            jarFilesFound.add(file.getName());
        }
    }

    private static void findClassLoaderUrls(final ClassLoader classLoader, final Set<URL> urls) {
        if (classLoader == null) {
            return;
        }

        if (classLoader instanceof URLClassLoader) {
            final URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
            urls.addAll(Arrays.asList(urlClassLoader.getURLs()));
        }

        // If the classLoader is the system class loader, we are done. We don't want to process the parent of
        // the system class loader (which would be the Launcher$ExtClassLoader that contains the JDK/JRE classes, etc)
        if (classLoader != ClassLoader.getSystemClassLoader()) {
            findClassLoaderUrls(classLoader.getParent(), urls);
        }
    }

    private static void findClassNamesInJar(final File file, final Set<String> classNames) throws IOException {
        if (!file.getName().endsWith(".jar") || !file.isFile() || !file.exists()) {
            return;
        }

        final JarFile jarFile = new JarFile(file);
        final Enumeration<? extends ZipEntry> enumeration = jarFile.entries();
        while (enumeration.hasMoreElements()) {
            final ZipEntry zipEntry = enumeration.nextElement();
            final String entryName = zipEntry.getName();

            if (entryName.endsWith(".class")) {
                final int lastIndex = entryName.lastIndexOf(".class");
                final String className = entryName.substring(0, lastIndex).replace("/", ".");
                classNames.add(className);
            }
        }
    }

    private static File locateStatelessNarWorkingDirectory(final File workingDirectory) throws IOException {
        final File[] files = workingDirectory.listFiles();
        if (files == null) {
            throw new IOException("Could not read contents of working directory " + workingDirectory);
        }

        final List<File> matching = new ArrayList<>();
        for (final File file : files) {
            final String filename = file.getName();
            if (STATELESS_NAR_PATTERN.matcher(filename).matches()) {
                matching.add(file);
            }
        }

        if (matching.isEmpty()) {
            throw new IOException("Could not find NiFi Stateless NAR in working directory " + workingDirectory);
        }
        if (matching.size() > 1) {
            throw new IOException("Found multiple NiFi Stateless NARs in working directory " + workingDirectory + ": " + matching);
        }

        return matching.get(0);
    }

    private static <T> T getSingleInstance(final ClassLoader classLoader, final Class<T> type) {
        final ServiceLoader<T> serviceLoader = ServiceLoader.load(type, classLoader);

        T instance = null;
        for (final T object : serviceLoader) {
            if (instance == null) {
                instance = object;
            } else {
                throw new IllegalStateException("Found multiple implementations of " + type);
            }
        }

        if (instance == null) {
            throw new IllegalStateException("Could not find any implementations of " + type);
        }

        return instance;
    }
}


text:
require 'activerecord_search/term'
require 'activerecord_search/railtie'

def Search(condition)
  ActiverecordSearch::Term.new(condition) unless condition.nil?
end


text:
<?php

namespace HealthCareAbroad\HelperBundle\Services;

use Doctrine\ORM\Query;

use HealthCareAbroad\HelperBundle\Entity\City;
use HealthCareAbroad\HelperBundle\Entity\State;
use HealthCareAbroad\HelperBundle\Entity\Country;

use HealthCareAbroad\HelperBundle\Exception\LocationServiceException;

class LocationService
{
	protected $doctrine;

	/**
	 * @var ChromediaGlobalRequest
	 */
	private $request;

	private $loadedGlobalCountryList = array();

	private $totalResults;

	private static $activeCountries = null;

	public $chromediaApiUri;

	/**
	 *
	 * @var CouchDbService
	 */
	public $couchDbServie;

	/**
	 * @var LocationService
	 */
	private static $instance = null;

	public function __construct()
	{
	    static::$instance = $this;
	}

	public function setChromediaApiUri($uri)
	{
	    $this->chromediaApiUri = $uri;
	}

	public function setChromediaGlobalRequest(ChromediaGlobalRequest $request)
	{
	    $this->request = $request;
	}

	public function setDoctrine(\Doctrine\Bundle\DoctrineBundle\Registry $doctrine)
	{
		$this->doctrine = $doctrine;
	}

	public function setCouchDbService(CouchDbService $couchDbService, $locationDb)
	{
	    $this->couchDbService = $couchDbService;
	    $this->couchDbService->setDatabase($locationDb);
	}

	/**
	 * Hackish way to use this service without injecting it on other services.
	 *
	 * @return \HealthCareAbroad\HelperBundle\Services\LocationService
	 */
	public static function getCurrentInstance()
	{
	    return self::$instance;
	}

    /// ======== Country Related Functions ======== //
	/**
	 * Currently being used in Institution Signup Only
	 *
	 * @param array $data
	 * @param unknown_type $id
	 * @return \HealthCareAbroad\HelperBundle\Entity\Country or NULL
	 */
	public function updateCountry(array $data, $id)
	{
	    if($countryObj = $this->getCountryById($id)) {
	        $em = $this->doctrine->getEntityManagerForClass('HelperBundle:Country');

	        $countryObj->setName($data['name']);
	        $countryObj->setCcIso($data['ccIso']);
	        $countryObj->setCountryCode($data['countryCode']);
	        $countryObj->setSlug($data['slug']);
	        $countryObj->setStatus($data['status']);

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

	        return $countryObj;
	    }

	    return null;
	}

	/**
	 * Add Gobal GeoCountry
	 * @param array $countryData
	 * @return mixed
	 */
	public function addGlobalCountry(array $countryData)
	{
	    $response = $this->request->post($this->chromediaApiUri.'/countries', array('geoCountry' => $countryData));

	    return \json_decode($response->getBody(true), true);
	}

	/**
	 * Update Global GeoCountry
	 * @param array $countryData
	 * @param unknown_type $id
	 * @return mixed
	 */
	public function updateGlobalCountry(array $countryData, $id)
	{
	    $response = $this->request->post($this->chromediaApiUri. "/countries/$id", array('geoCountry' => $countryData));

	    if (200 != $response->getStatusCode()) {
	        throw LocationServiceException::failedApiRequest($response->getRequest()->getUrl(false), $response->getReasonPhrase());
	    }

	    return \json_decode($response->getBody(true), true);
	}

	/**
	 * Update Global GeoCountry status
	 * @param unknown_type $id
	 * @param unknown_type $status
	 * @return mixed
	 */
	public function updateGlobalCountryStatus($id, $status)
	{
	    $response = $this->request->post($this->chromediaApiUri."/countries/$id/update-status", array('status' => $status));

	    return \json_decode($response->getBody(true), true);
	}

	/**
	 * Get Global GeoCountry
	 * @param unknown_type $id
	 * @return mixed
	 */
	public function getGlobalCountryById($id)
	{
	    $response = $this->request->get($this->chromediaApiUri.'/countries/'.$id);
	    if (200 != $response->getStatusCode()) {
	        throw LocationServiceException::failedApiRequest($response->getRequest()->getUrl(false), $response->getBody(true));
	    }

	    return \json_decode($response->getBody(true), true);
	}

    /**
     * Get List of Global GeoCountry with parameters
     * @param array $params
     * @return Ambigous <multitype:, mixed>
     */
	public function getGlobalCountries(array $params = array())
	{
	    static $hasLoaded = false;
	    static $results = array();

	    if (!$hasLoaded) {
	        $queryString = count($params) ? '?' . http_build_query($params) : '';
	        $response = $this->request->get($this->chromediaApiUri."/countries" . $queryString);

	        if (200 != $response->getStatusCode()) {
	            throw LocationServiceException::failedApiRequest($response->getRequest()->getUrl(false), $response->getBody(true));
	        }

	        $results = \json_decode($response->getBody(true), true);

	        $hasLoaded = true;
	    }

	    return $results;
	}

	/**
	 * Get Local Country
	 * @param unknown_type $id
	 * @return \HealthCareAbroad\HelperBundle\Entity\Country or NULL
	 */
	public function getCountryById($id)
	{
	    return $this->doctrine->getRepository('HelperBundle:Country')->find($id);
	}

	/**
	 * Get Local Country
	 * @param string $slug
	 * @return \HealthCareAbroad\HelperBundle\Entity\Country or NULL
	 */
	public function getCountryBySlug($slug)
	{
	    static $countryBySlugs = array();
	    if (!isset($countryBySlugs[$slug])) {
	        $countryBySlugs[$slug] = $this->doctrine->getRepository('HelperBundle:Country')->findOneBySlug($slug);
	    }

	    return $countryBySlugs[$slug];
	}

	/**
	 * Create Country instance from array $data
	 *
	 * @param array $data
	 * @return \HealthCareAbroad\HelperBundle\Entity\Country
	 */
	public function createCountryFromArray(array $data)
	{
	    $requiredFields = array('id', 'name', 'slug');

	    foreach ($requiredFields as $key) {
	        if (!isset($data[$key])) {
	            throw LocationServiceException::missingRequiredCountryDataKey($key);
	        }
	    }

	    $country = new Country();
	    $country->setId($data['id']);
	    $country->setName($data['name']);
	    $country->setSlug($data['slug']);
	    $country->setCcIso(isset($data['ccIso']) ? $data['ccIso'] : '');
	    $country->setCountryCode(isset($data['countryCode']) ? $data['countryCode'] : '');
	    $country->setStatus(isset($data['code']) ? $data['code'] : Country::STATUS_ACTIVE);

	    return $country;
	}

	/**
	 * Get Active Local Country
	 * @param unknown_type $hydrationMode
	 * @return array or NULL
	 */
	public function getActiveCountries($hydrationMode=Query::HYDRATE_ARRAY)
	{
	    if(!static::$activeCountries) {
	        $qb = $this->getQueryBuilderForCountries();
	        static::$activeCountries = $qb->getQuery()->getResult($hydrationMode);
	    }

	    return static::$activeCountries;
	}

	public function getQueryBuilderForCountries()
	{
	    return $this->doctrine->getEntityManager()->getRepository('HelperBundle:Country')->getQueryBuilderForCountries();
	}
	/// ======== End of Country Related Functions ======== //

    /// ======== State Related Functions ======== //
	/**
	 * Currently being used in Institution Signup Only
	 *
	 * This will add a new data in global states (geo_states) first
	 * and will save/update local states if success.
	 * @param array $data
	 * @return \HealthCareAbroad\HelperBundle\Entity\State
	 */
	public function addNewState(array $data) {
	    // Save to global state.
	    $stateData = $this->addGlobalState($data);

        if(isset($stateData['form'])) {
            return null;
        }

	    // Update local state if successfully saved in global state.
	    $state = $this->getStateById($stateData['id']);
	    if(!$state) {
	        $state = new State();
	        $state->setId($stateData['id']);
	        $state->setCountry($this->getCountryById($data['geoCountry']));
	    }

	    $state->setName($stateData['name']);
	    $state->setInstitutionId($stateData['institutionId']);
	    $state->setStatus($stateData['status']);

	    $em = $this->doctrine->getEntityManagerForClass('HelperBundle:State');
	    $em->persist($state);
	    $em->flush($state);

	    return $state;
	}

	/**
	 * Update Local State
	 *
	 * Note: Currently being used in Institution Signup Only
	 * @param array $data
	 * @param unknown_type $id
	 */
	public function updateState(array $data, $id)
	{
	    if($stateObj = $this->getStateById($id)) {
	        $em = $this->doctrine->getEntityManagerForClass('HelperBundle:State');
	        $country = $this->getCountryById($data['geoCountry']['id']);

	        if(!$country) {
	            $country = $this->createCountryFromArray($data['geoCountry']);
	            $em->persist($country);
	        }

	        $stateObj->setName($data['name']);
	        $stateObj->setCountry($country);
	        $state->setAdministrativeCode(isset($data['administrativeCode']) ? $data['administrativeCode'] : null);
	        //$stateObj->setSlug($data['slug']);
	        $stateObj->setStatus($data['status']);

	        $em->persist($stateObj);
	        $em->flush();
	    }
	}

	/**
	 * Add Global State
	 *
	 * @param array $stateData
	 * @return mixed
	 */
	public function addGlobalState(array $stateData)
	{
	    if(!isset($stateData['institutionId']) || is_null($stateData['institutionId']))
	        $stateData['institutionId'] = 0;

	    $response = $this->request->post($this->chromediaApiUri.'/states', array('geoState' => $stateData));

	    return \json_decode($response->getBody(true), true);
	}

	/**
	 * Update Global State
	 *
	 * @param array $stateData
	 * @param unknown_type $id
	 * @return mixed
	 */
	public function updateGlobalState(array $stateData, $id)
	{
	    $response = $this->request->post($this->chromediaApiUri."/states/$id", array('geoState' => $stateData));

	    return \json_decode($response->getBody(true), true);
	}

	/**
	 * Update Global State status
	 *
	 * @param unknown_type $id
	 * @param unknown_type $status
	 * @return mixed
	 */
	public function updateGlobalStateStatus($id, $status)
	{
	    $response = $this->request->post($this->chromediaApiUri. "/states/$id/update-status", array('status' => $status));

	    if (200 != $response->getStatusCode()) {
	        throw LocationServiceException::failedApiRequest($response->getRequest()->getUrl(false), $response->getReasonPhrase());
	    }

	    return \json_decode($response->getBody(true), true);
	}

	/**
	 * Get Lost of Global State with parameters
	 *
	 * @param array $params
	 * @return mixed
	 */
	public function getGlobalStates(array $params)
	{
	    static $hasLoaded = false;

	    if (!$hasLoaded) {
	        $queryString = count($params) ? '?' . http_build_query($params) : '';
	        $response = $this->request->get($this->chromediaApiUri."/states" . $queryString);

	        if (200 != $response->getStatusCode()) {
	            throw LocationServiceException::failedApiRequest($response->getRequest()->getUrl(false), $response->getBody(true));
	        }

	        $results = \json_decode($response->getBody(true), true);

	        $hasLoaded = true;
	    }

	    return $results;
	}

	/**
	 * Get Global State
	 *
	 * @param unknown_type $id
	 * @return NULL|mixed
	 */
	public function getGlobalStateById($id)
	{
	    $response = $this->request->get($this->chromediaApiUri.'/states/'.$id);

	    if (200 != $response->getStatusCode()) {
	        if (404 == $response->getStatusCode()){
	            return null; // id does not exist
	        }
	        else {
	            throw LocationServiceException::failedApiRequest($response->getRequest()->getUrl(false), $response->getReasonPhrase());
	        }
	    }

	    return \json_decode($response->getBody(true), true);
	}

	/**
	 * Get Local State
	 *
	 * @param unknown_type $id
	 */
	public function getStateById($id)
	{
	    return $this->doctrine->getRepository('HelperBundle:State')->find($id);
	}

	/**
	 * Create State instance from array $data
	 *
	 * @param array $data
	 * @return \HealthCareAbroad\HelperBundle\Entity\State
	 */
	public function createStateFromArray(array $data)
	{
	    $requiredFields = array('id', 'name', 'country');

	    if(isset($data['geoCountry']) && isset($data['geoCountry']['id'])) {
	        $data['country'] = $this->getCountryById($data['geoCountry']['id']);
	    }

	    foreach ($requiredFields as $key) {
	        if (!isset($data[$key])) {
	            throw LocationServiceException::missingRequiredStateDataKey($key);
	        }
	    }

	    $state = new State();
	    $state->setId($data['id']);
	    $state->setName($data['name']);
	    $state->setCountry($data['country']);
	    $state->setInstitutionId(isset($data['institutionId']) ? $data['institutionId'] : 0);
	    $state->setAdministrativeCode(isset($data['administrativeCode']) ? $data['administrativeCode'] : null);
	    $state->setStatus(isset($data['status']) ? $data['status'] : State::STATUS_ACTIVE);

	    return $state;
	}
	/// ======== End of State Related Functions ======== //

    /// ======== City Related Functions ======== //
	/**
	 * Add Local City
	 *
 	 * Note: Currently being used in Institution Signup Only
 	 *
	 * @param array $data
	 * @return \HealthCareAbroad\HelperBundle\Entity\City
	 */
	public function addNewCity(array $data) {
	    // Save to global city.
	    $cityData = $this->addGlobalCity($data);

	    if(isset($cityData['form'])) {
	        return null;
	    }

	    $city = $this->getCityById($cityData['id']);

	    if(!$city) {
	        $city = new City();
	        $city->setId($cityData['id']);
	        $city->setCountry($this->getCountryById($data['geoCountry']));
	    }

	    if($data['geoState']) {
	        $state = $this->getStateById($data['geoState']);
	        $city->setState($state ? $state : null);
	    }

	    $city->setName($cityData['name']);
	    $city->setSlug($cityData['slug']);
	    $city->setInstitutionId($cityData['institutionId']);
	    $city->setStatus($cityData['status']);

	    $em = $this->doctrine->getEntityManagerForClass('HelperBundle:City');
	    $em->persist($city);
	    $em->flush($city);

	    return $city;
	}

	/**
	 * Update Local City
	 *
	 * Note: Currently being used in Institution Signup Only
	 *
	 * @param array $data
	 * @param $id
	 * @return \HealthCareAbroad\HelperBundle\Entity\City|NULL
	 */
	public function updateCity(array $data, $id)
	{
	    if($cityObj = $this->getCityById($id)) {
	        $em = $this->doctrine->getEntityManagerForClass('HelperBundle:City');
	        $country = $this->getCountryById($data['geoCountry']['id']);

	        if(!$country) {
	            $country = $this->createCountryFromArray($data['geoCountry']);
	            $em->persist($country);
	        }

	        if(!isset($data['geoState']) || !$data['geoState']) {
	            $cityObj->setState(null);
	        } else {
	            $state = $this->getStateById($data['geoState']['id']);
	            if(!$state) {
	                $data['geoState']['country'] = $country;
	                $state = $this->createStateFromArray($data['geoState']);
	            }

	            $em->persist($state);
	        }

	        $cityObj->setName($data['name']);
	        $cityObj->setCountry($country);
	        $cityObj->setState($state);
	        $cityObj->setSlug($data['slug']);
	        $cityObj->setStatus($data['status']);

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

	        return $cityObj;
	    }

	    return null;
	}

	/**
	 * Add Global City
	 *
	 * @param array $cityData
	 * @return mixed
	 */
	public function addGlobalCity(array $cityData)
	{
	    if(!isset($cityData['institutionId']) || is_null($cityData['institutionId']))
	        $cityData['institutionId'] = 0;

	    $response = $this->request->post($this->chromediaApiUri.'/cities', array('geoCity' => $cityData));

	    return \json_decode($response->getBody(true), true);
	}

	/**
	 * Update Global City
	 *
	 * @param array $cityData
	 * @param $id
	 * @return mixed
	 */
	public function updateGlobalCity(array $cityData, $id)
	{
	    $response = $this->request->post($this->chromediaApiUri."/cities/$id", array('geoCity' => $cityData));

	    return \json_decode($response->getBody(true), true);
	}

	/**
	 * Update Global City status
	 *
	 * @param unknown_type $id
	 * @param unknown_type $status
	 * @return mixed
	 */
	public function updateGlobalCityStatus($id, $status)
	{
	    $response = $this->request->post($this->chromediaApiUri. "/cities/$id/update-status", array('status' => $status));

	    if (200 != $response->getStatusCode()) {
	        throw LocationServiceException::failedApiRequest($response->getRequest()->getUrl(false), $response->getReasonPhrase());
	    }

	    return \json_decode($response->getBody(true), true);
	}

	/**
	 * Get List of Global City with parameters
	 *
	 * @param array $params
	 * @return mixed
	 */
	public function getGlobalCities(array $params)
	{
	    static $hasLoaded = false;

	    if (!$hasLoaded) {
	        $queryString = count($params) ? '?' . http_build_query($params) : '';

	        $response = $this->request->get($this->chromediaApiUri."/cities" . $queryString);
	        if (200 != $response->getStatusCode()) {
	            throw LocationServiceException::failedApiRequest($response->getRequest()->getUrl(false), $response->getBody(true));
	        }

	        $results = \json_decode($response->getBody(true), true);
	        $hasLoaded = true;
	    }

	    return $results;
	}

	/**
	 * Get Global City
	 *
	 * @param unknown_type $id
	 * @return NULL|mixed
	 */
	public function getGlobalCityById($id)
	{
	    $response = $this->request->get($this->chromediaApiUri.'/cities/'.$id);
	    if (200 != $response->getStatusCode()) {
	        if (404 == $response->getStatusCode()){
	            return null;
	        }
	        else {
	            throw LocationServiceException::failedApiRequest($response->getRequest()->getUrl(false), $response->getBody(true));
	        }
	    }

	    return \json_decode($response->getBody(true), true);
	}

	/**
	 * Get Local City
	 *
	 * @param unknown_type $id
	 * @return \HealthCareAbroad\HelperBundle\Entity\City or NULL
	 */
	public function getCityById($id)
	{
	    return $this->doctrine->getRepository('HelperBundle:City')->find($id);
	}

	/**
	 * Get Local City by slug
	 *
	 * @param string $slug
	 * @return \HealthCareAbroad\HelperBundle\Entity\City or NULL
	 */
	public function getCityBySlug($slug)
	{
	    static $cityBySlugs = array();
	    if (!isset($cityBySlugs[$slug])) {
	        $cityBySlugs[$slug] = $this->doctrine->getRepository('HelperBundle:City')->findOneBySlug($slug);
	    }

	    return $cityBySlugs[$slug];
	}

	public function getActiveCitiesByCountry(Country $country)
	{
	    $criteria = array('status' => City::STATUS_ACTIVE, 'country' => $country);

	    return $this->doctrine->getEntityManager()->getRepository('HelperBundle:City')->findBy($criteria);
	}

	public function getActiveCitiesByCountryId($countryId)
	{
	    $country = $this->getCountryById($countryId);

	    return $this->getActiveCitiesByCountry($country);
	}

	public function getListActiveCitiesByCountry(Country $country)
	{
	    $cities = array();
	    $result = $this->getActiveCitiesByCountry($country);
	    foreach($result as $each)
	        $cities[] = array('id' => $each->getId(), 'name' => $each->getName());

	    return $cities;
	}

	public function getListActiveCitiesByCountryId($countryId)
	{
	    $cities = array();
	    $result = $this->getActiveCitiesByCountryId($countryId);
	    foreach($result as $each)
	        $cities[] = array('id' => $each->getId(), 'name' => $each->getName());

	    return $cities;
	}

	public function createCityFromArray(array $data)
	{
	    $requiredFields = array('id', 'name', 'country');

	    if(isset($data['geoCountry']) && isset($data['geoCountry']['id'])) {
	        $data['country'] = $this->getCountryById($data['geoCountry']['id']);
	    }

	    foreach ($requiredFields as $key) {
	        if (!\array_key_exists($key, $data)) {
	            throw LocationServiceException::missingRequiredCityDataKey($key);
	        }
	    }

	    $city = new City();
	    $city->setId($data['id']);
	    $city->setName($data['name']);
	    $city->setCountry($data['country']);
	    $city->setInstitutionId(isset($data['institutionId']) ? $data['institutionId'] : 0);
	    $city->setStatus(isset($data['status']) ? $data['status'] : City::STATUS_ACTIVE);
	    if (isset($data['slug'])){
	        $city->setSlug($data['slug']);
	    }

	    /* Disabled to avoid duplicate persist!
        if(isset($data['geoState']) && isset($data['geoState']['id'])) {
	        $state = $this->getStateById($data['geoState']['id']);
	    if(!$state) {
    	    $data['geoState']['country'] = $data['country'];
    	    $state = $this->createStateFromArray($data['geoState']);
	    }
	    $city->setState($state);
	    } */

	    return $city;
	}

}


text:
#include "Themes.h"

// Theme uses some unnamed functions, these are the definitions
typedef DWORD (WINAPI *pThemeWait)(DWORD dwTimeout);
typedef BOOL (WINAPI *pThemeWatch)(void);

namespace pGina
{
	namespace GINA
	{
		/* static */
		void Themes::Init()
		{
			HMODULE hDll = LoadLibrary(L"shsvcs.dll");

			if(hDll)
				return;

			pThemeWait themeWait = (pThemeWait) GetProcAddress(hDll, "ThemeWaitForServiceReady");
			pThemeWatch themeWatch = (pThemeWatch) GetProcAddress(hDll, "ThemeWatchForStart");

			if(themeWait && themeWatch)
			{
				themeWait(5000);
				themeWatch();
			}

			FreeLibrary(hDll);
		}
	}
}


text:
package com.sromku.simple.fb.entities;

import com.google.gson.annotations.SerializedName;

public class Image {

    private static final String HEIGHT = "height";
    private static final String NULL = "null";
    private static final String SOURCE = "source";
    private static final String SRC = "src";
    private static final String URL = "url";
    private static final String WIDTH = "width";

    @SerializedName(HEIGHT)
    private Integer mHeight;

    @SerializedName(SOURCE)
    private String mSource;

    @SerializedName(WIDTH)
    private Integer mWidth;

    @SerializedName(URL)
    private String mUrl;

    public Integer getHeight() {
        return mHeight;
    }

    public String getSource() {
        return mSource;
    }

    public Integer getWidth() {
        return mWidth;
    }

    public String getUrl() {
        return mUrl;
    }

    @Override
    public String toString() {
        return mUrl;
    }
}