text:
package ProGAL.proteins;

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

import ProGAL.geom3d.Point;
import ProGAL.geom3d.complex.CEdge;
import ProGAL.geom3d.complex.CTetrahedron;
import ProGAL.geom3d.complex.CTriangle;
import ProGAL.geom3d.complex.CVertex;
import ProGAL.geom3d.complex.alphaComplex.AlphaComplex;
import ProGAL.geom3d.viewer.J3DScene;
import ProGAL.geom3d.volumes.LSS;
import ProGAL.proteins.PDBFile;
import ProGAL.proteins.PDBFile.AtomRecord;

public class ProteinComplex extends AlphaComplex {
	public final PDBFile pdbFile;
	private List<Hole> holes;
	private List<Cavity> cavities;

	public ProteinComplex(PDBFile f) {
		this(f,2.8);
	}

	public ProteinComplex(PDBFile f, double waterRad) {
		super(f.getAtomCoords(), waterRad);
		this.pdbFile = f;
	}

	public List<CEdge> getEdges() {
		List<CEdge> ret = new ArrayList<CEdge>();
		for(CEdge e: super.edges){
			if(getDepth(e)>=0) ret.add(e);
		}
		return ret;
	}

	public List<CTetrahedron> getTetrahedra() {
		List<CTetrahedron> ret = new ArrayList<CTetrahedron>();
		for(CTetrahedron t: super.tetrahedra){
			if(getDepth(t)>=0) ret.add(t);
		}
		return ret;
	}

	public List<CTriangle> getTriangles() {
		List<CTriangle> ret = new ArrayList<CTriangle>();
		for(CTriangle t: super.triangles){
			if(getDepth(t)>=0) ret.add(t);
		}
		return ret;
	}

	public CVertex getVertex(Point p) {
		for(CVertex v: vertices){
			if(v.distance(p)<0.001) return v;
		}
		return null;
	}
	public AtomRecord getAtom(Point p){
		for(AtomRecord ar: pdbFile.getAtomRecords()){
			if(ar.coords.distanceSquared(p)<0.001){
				return ar;
			}
		}
		return null;
	}
	public char getAtomType(Point p){
		return getAtom(p).atomType.charAt(0);
	}

	public boolean isBuried(CVertex v){
		Set<CTetrahedron> hull = getVertexHull(v);
		for(CTetrahedron t: hull){
			if(getDepth(t)<0) return false;
		}
		return true;
	}

	public boolean isBuried(AtomRecord ar){
		return isBuried(getVertex(ar.coords));
	}

	public List<Hole> getHoles(){
		if(holes==null){
			holes = getHoles(alpha);
		}
		return holes;
	}

	public List<Hole> getHoles(double probeRad){
		List<Hole> ret = new LinkedList<Hole>();
		for(CTetrahedron t: tetrahedra){
			if(getDepth(t)<=0) continue;
			if(getInAlpha(t)<probeRad) continue;
			boolean include = true;
			for(Hole h: ret){ if(h.tetrahedra.contains(t)) { include = false; break; } }
			if(!include) continue;

			ret.add(new Hole(t, probeRad));
		}
		return ret;
	}

	public class Hole{
		public final List<CTetrahedron> tetrahedra = new ArrayList<CTetrahedron>();

		public Hole(CTetrahedron representative, double probeRad){
			List<CTetrahedron> candidates = new LinkedList<CTetrahedron>();
			candidates.add(representative);

			while(!candidates.isEmpty()){
				CTetrahedron c = candidates.remove(0);
				if(getDepth(c)<=0) continue;
				if(c.circumRadius()<probeRad) continue;
				if(tetrahedra.contains(c)) continue;
				tetrahedra.add(c);

				for(int n=0;n<4;n++)
					if(c.getTriangle(n).circumradius()>=probeRad) candidates.add(c.getNeighbour(n));
			}
		}
		public Hole(CTetrahedron representative){
			this(representative, alpha);
		}

		public double averageDepth(){
			int sum = 0;
			for(CTetrahedron t: tetrahedra) sum+=getDepth(t);
			return (sum*1.0)/tetrahedra.size();
		}
		public double volume(){
			double sum = 0;
			for(CTetrahedron t: tetrahedra) sum+=t.getVolume();
			return sum;
		}
		public String toString(){
			return String.format("ProteinComplex.Hole[%d tetrahedra, volume=%.2f, avg depth=%.2f]", tetrahedra.size(), volume(), averageDepth());
		}
	}

	public List<Cavity> getCavities(){
		if(cavities==null){
			cavities = new LinkedList<Cavity>();
			for(CTetrahedron t: tetrahedra){
				if(getDepth(t)>=0) continue;
				if(getInAlpha(t)<alpha) continue;
				if(getInAlpha(t)>=Cavity.largeProbeRadius) continue;
				boolean include = true;
				for(Cavity v: cavities){ if(v.tetrahedrons.contains(t)) { include = false; break; } }
				if(!include) continue;

				cavities.add(new Cavity(t));
			}
		}
		return cavities;
	}

	public class Cavity{
		public final List<CTetrahedron> tetrahedrons = new ArrayList<CTetrahedron>();
		private final static double largeProbeRadius = 3000;

		public Cavity(CTetrahedron representative){
			List<CTetrahedron> candidates = new LinkedList<CTetrahedron>();
			candidates.add(representative);

			while(!candidates.isEmpty()){
				CTetrahedron c = candidates.remove(0);
				if(getDepth(c)>=0) continue;
				if(c.circumRadius()<alpha) continue;
				if(c.circumRadius()>largeProbeRadius) continue;
				if(tetrahedrons.contains(c)) continue;
				tetrahedrons.add(c);

				candidates.add(c.getNeighbour(0));
				candidates.add(c.getNeighbour(1));
				candidates.add(c.getNeighbour(2));
				candidates.add(c.getNeighbour(3));
			}
		}
		public double volume(){
			double sum = 0;
			for(CTetrahedron t: tetrahedrons) sum+=t.getVolume();
			return sum;
		}
		public String toString(){
			return String.format("ProteinComplex.Cavity[%d tetrahedra, volume=%.2f]", tetrahedrons.size(), volume());
		}
	}

	public static void main(String[] args){
//		PDBFile f = new PDBFile("/Users/ras/Documents/Datasets/CASP8Training/T0490/T0490.pdb");
		PDBFile f = new PDBFile("/Users/pawel/Downloads/1X0O.pdb");
		ProteinComplex pc = new ProteinComplex(f);
		System.out.println(pc.getTetrahedra().size());
				J3DScene scene = J3DScene.createJ3DSceneInFrame();
				List<AtomRecord> allAtoms = f.getAtomRecords();
				AtomRecord prev = null;
				for(AtomRecord ca: f.getCARecords()){
					if(prev!=null){
						scene.addShape(new LSS(prev.coords, ca.coords, 0.1),java.awt.Color.GRAY,5);
					}
					scene.addText(allAtoms.indexOf(ca)+"", ca.coords, 1.0f);

					prev = ca;
				}
				System.out.println("Finding shortest paths:");
		//
		//		List<CVertex> vertices = pc.getVertices();
		//		System.out.printf("> %d-%d: %d\n",0,1,		pc.getCovalentBondDistance(vertices.get(0), vertices.get(1)));
		//		System.out.printf("> %d-%d: %d\n",0,10,		pc.getCovalentBondDistance(vertices.get(0), vertices.get(10)));
		//		System.out.printf("> %d-%d: %d\n",0,100,	pc.getCovalentBondDistance(vertices.get(0), vertices.get(100)));
		//		System.out.printf("> %d-%d: %d\n",50,100,	pc.getCovalentBondDistance(vertices.get(50), vertices.get(100)));
		//		System.out.printf("> %d-%d: %d\n",50,60,	pc.getCovalentBondDistance(vertices.get(50), vertices.get(60)));
	}

}


text:
from setuptools import setup, find_packages

requires = [
    'amaasutils',
    'configparser',
    'python-dateutil',
    'pytz',
    'requests',
    'warrant'
]

setup(
    name='amaascore',
    version='0.4.0',
    description='Asset Management as a Service - Core SDK',
    license='Apache License 2.0',
    url='https://github.com/amaas-fintech/amaas-core-sdk-python',
    author='AMaaS',
    author_email='tech@amaas.com',
    classifiers=[
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
    ],
    packages=find_packages(exclude=['tests']),  # Very annoying that this doesnt work - I have to include a MANIFEST
    install_requires=requires,
)

redpajama_set_name: RedPajamaGithub


text:
"""Specialization of AgentTestScenario to facilitate testing Spinnaker.

This provides means for locating spinnaker and extracting configuration
information so that the tests can adapt to the deployment information
to make appropriate observations.
"""

import logging
import traceback

from citest.base import JournalLogger

import citest.service_testing as sk
import citest.service_testing.http_agent as http_agent

from spinnaker_testing import aws_scenario_support
from spinnaker_testing import appengine_scenario_support
from spinnaker_testing import google_scenario_support
from spinnaker_testing import kubernetes_scenario_support
from spinnaker_testing import openstack_scenario_support
from spinnaker_testing import azure_scenario_support

PLATFORM_SUPPORT_CLASSES = [
    aws_scenario_support.AwsScenarioSupport,
    # appengine depends on google so order it after
    google_scenario_support.GoogleScenarioSupport,
    appengine_scenario_support.AppEngineScenarioSupport,
    kubernetes_scenario_support.KubernetesScenarioSupport,
    openstack_scenario_support.OpenStackScenarioSupport,
    azure_scenario_support.AzureScenarioSupport
]

class SpinnakerTestScenario(sk.AgentTestScenario):
  """Specialization of AgentTestScenario to facilitate testing Spinnaker.

  Adds standard command line arguments for locating the deployed system, and
  setting up observers.
  """
  ENDPOINT_SUBSYSTEM = 'the server to test'

  @classmethod
  def new_post_operation(cls, title, data, path, status_class=None):
    """Creates an operation that posts data to the given path when executed.

    The base_url will come from the agent that the operation is eventually
    executed on.

    Args:
      title: [string] The name of the operation for reporting purposes.
      data: [string] The payload to send in the HTTP POST.
      path: [string] The path relative to the base url provided later.
      status_class: [class AgentOperationStatus] If provided, a specialization
         of the AgentOperationStatus to use for tracking the execution.
    """
    return http_agent.HttpPostOperation(title=title, data=data, path=path,
                                        status_class=status_class)

  @classmethod
  def new_put_operation(cls, title, data, path, status_class=None):
    """Creates an operation that puts data to the given path when executed.

    The base_url will come from the agent that the operation is eventually
    executed on.

    Args:
      title: [string] The name of the operation for reporting purposes.
      data: [string] The payload to send in the HTTP PUT.
      path: [string] The path relative to the base url provided later.
      status_class: [class AgentOperationStatus] If provided, a specialization
         of the AgentOperationStatus to use for tracking the execution.
    """
    return http_agent.HttpPutOperation(title=title, data=data, path=path,
                                       status_class=status_class)

  @classmethod
  def new_patch_operation(cls, title, data, path, status_class=None):
    """Creates an operation that patches data to the given path when executed.

    The base_url will come from the agent that the operation is eventually
    executed on.

    Args:
      title: [string] The name of the operation for reporting purposes.
      data: [string] The payload to send in the HTTP PATCH.
      path: [string] The path relative to the base url provided later.
      status_class: [class AgentOperationStatus] If provided, a specialization
         of the AgentOperationStatus to use for tracking the execution.
    """
    return http_agent.HttpPatchOperation(title=title, data=data, path=path,
                                         status_class=status_class)

  @classmethod
  def new_delete_operation(cls, title, data, path, status_class=None):
    """Creates an operation that deletes from the given path when executed.

    The base_url will come from the agent that the operation is eventually
    executed on.

    Args:
      title: [string] The name of the operation for reporting purposes.
      data: [string] The payload to send in the HTTP DELETE.
      path: [string] The path relative to the base url provided later.
      status_class: [class AgentOperationStatus] If provided, a specialization
         of the AgentOperationStatus to use for tracking the execution.
    """
    return http_agent.HttpDeleteOperation(title=title, data=data, path=path,
                                          status_class=status_class)

  @classmethod
  def _init_spinnaker_bindings_builder(cls, builder, defaults):
    """Initialize bindings for spinnaker itself.

    Args:
      builder: [citest.base.ConfigBindingsBuilder]
      defaults: [dict] Default binding value overrides.
         This is used to initialize the default commandline parameters.
    """
    # This could probably be removed fairly easily.
    # It probably isnt useful anymore.
    builder.add_argument(
        '--host_platform', default=defaults.get('HOST_PLATFORM', None),
        help='Platform running spinnaker (gce, native).'
             ' If this is not explicitly set, then try to'
             ' guess based on other parameters set.')

    builder.add_argument(
        '--native_hostname', default=defaults.get('NATIVE_HOSTNAME', None),
        help='Host name that {system} is running on.'
             ' This parameter is only used if the spinnaker host platform'
             ' is "native".'.format(system=cls.ENDPOINT_SUBSYSTEM))

    builder.add_argument(
        '--network_protocol', default='http',
        help='The network protocol to use talking to the native port.'
        ' The default is "http", but this could be changed to "https".')

    builder.add_argument(
        '--native_port', default=defaults.get('NATIVE_PORT', None),
        help='Port number that {system} is running on.'
             ' This parameter is only used if the spinnaker host platform'
             ' is "native". It is not needed if the system is using its'
             ' standard port.'.format(system=cls.ENDPOINT_SUBSYSTEM))

    builder.add_argument(
        '--test_stack', default=defaults.get('TEST_STACK', 'test'),
        help='Default Spinnaker stack decorator.')

    builder.add_argument(
        '--test_app', default=defaults.get('TEST_APP', cls.__name__.lower()),
        help='Default Spinnaker application name to use with test.')

  @classmethod
  def init_bindings_builder(cls, builder, defaults=None):
    """Initialize command line bindings.

    Args:
      builder: [citest.base.ConfigBindingsBuilder]
      defaults: [dict] Default binding value overrides.
         This is used to initialize the default commandline parameters.
    """
    defaults = defaults or {}

    for klas in PLATFORM_SUPPORT_CLASSES:
      klas.add_commandline_parameters(cls, builder, defaults)

    cls._init_spinnaker_bindings_builder(builder, defaults=defaults)

    super(SpinnakerTestScenario, cls).init_bindings_builder(
        builder, defaults=defaults)

  @property
  def gcp_observer(self):
    """The observer for inspecting GCE platform stated.

    Raises:
      Exception if the observer is not available.
    """
    return self.__platform_support['google'].observer

  @property
  def kube_observer(self):
    """The observer for inspecting Kubernetes platform state."

    Raises:
      Exception if the observer is not available.
    """
    return self.__platform_support['kubernetes'].observer

  @property
  def aws_observer(self):
    """The observer for inspecting AWS platform state.

    Raises:
      Exception if the observer is not available.
    """
    return self.__platform_support['aws'].observer

  @property
  def appengine_observer(self):
    """The observer for inspecting App Engine platform state.

    Raises:
      Exception if the observer is not available.
    """
    return self.__platform_support['appengine'].observer

  @property
  def os_observer(self):
    """The observer for inspecting OpenStack platform state.

    Raises:
      Exception if the observer is not available.
    """
    return self.__platform_support['openstack'].observer

  @property
  def az_observer(self):
    """The observer for inspecting Azure platform state.

    Raises:
      Exception if the observer is not available.
    """
    return self.__platform_support['azure'].observer

  def __init__(self, bindings, agent=None):
    """Constructor

    Args:
      bindings: [dict] The parameter bindings for overriding the test
         scenario configuration.
      agent: [SpinnakerAgent] The Spinnaker agent to bind to the scenario.
    """
    super(SpinnakerTestScenario, self).__init__(bindings, agent)
    agent = self.agent
    bindings = self.bindings

    # For read-only tests that don't make mutating calls to Spinnaker,
    # there is nothing to update in the bindings, e.g. GCP quota test.
    if agent is not None:
      for key, value in agent.runtime_config.items():
        try:
          if bindings[key]:
            continue  # keep existing value already set within citest
        except KeyError:
          pass
        bindings[key] = value  # use value from agent's configuration

    JournalLogger.begin_context('Configure Scenario Bindings')
    self.__platform_support = {}
    for klas in PLATFORM_SUPPORT_CLASSES:
      try:
        support = klas(self)
        self.__platform_support[support.platform_name] = support
      except:
        logger = logging.getLogger(__name__)

        logger.exception('Failed to initialize support class %s:\n%s',
                         str(klas), traceback.format_exc())

    try:
      self._do_init_bindings()
    except:
      logger = logging.getLogger(__name__)
      logger.exception('Failed to initialize spinnaker agent.')
      raise
    finally:
      JournalLogger.end_context()

  def _do_init_bindings(self):
    """Hook for specific tests to add additional bindings."""
    pass


text:
package com.github.seratch.signedrequest4j;

import org.junit.Test;

import java.util.Map;

import static org.junit.Assert.*;

public class HttpResponseTest {

	@Test
	public void type() throws Exception {
		assertNotNull(HttpResponse.class);
	}

	@Test
	public void instantiation() throws Exception {
		HttpResponse target = new HttpResponse();
		assertNotNull(target);
	}

	@Test
	public void getStatusCode_A$() throws Exception {
		HttpResponse target = new HttpResponse();
		target.setStatusCode(200);
		Integer actual = target.getStatusCode();
		Integer expected = 200;
		assertEquals(expected, actual);
	}

	@Test
	public void setStatusCode_A$Integer() throws Exception {
		HttpResponse target = new HttpResponse();
		Integer statusCode = 501;
		target.setStatusCode(statusCode);
	}

	@Test
	public void getHeaders_A$() throws Exception {
		HttpResponse target = new HttpResponse();
		Map<String, String> actual = target.getHeaders();
		assertNotNull(actual);
	}

	@Test
	public void setHeaders_A$Map() throws Exception {
		HttpResponse target = new HttpResponse();
		Map<String, String> headers = target.getHeaders();
		target.setHeaders(headers);
	}

}


text:
require 'rails_helper'
include NegativeBalanceProtection
include NegativeBalanceProtection::Actions

describe NegativeBalanceChecker do
  let(:scope) {NegativeBalanceChecker.new}

  context "enqueing jobs" do
    before(:each) do
      Sidekiq::Testing.fake!
      Sidekiq::Worker.clear_all
    end

    it "enque job for check no paying customers" do
      expect {
        NegativeBalanceChecker.perform_async(5)
      }.to change(NegativeBalanceChecker.jobs, :size).by(1)
    end
  end

  context "perform jobs" do
    let!(:user1) { FactoryGirl.create(:user) }
    let!(:user2) { FactoryGirl.create(:user) }
    let!(:suspended_user) { FactoryGirl.create(:user, suspended: true) }
    let!(:invoice) {FactoryGirl.create :invoice, account: user1.account}
    let!(:server1) {FactoryGirl.create :server, user: user1}
    let(:mailer_q) {ActionMailer::Base.deliveries}

    before(:each) do
      mailer_q.clear
      item1 = FactoryGirl.create(:invoice_item, invoice: invoice, net_cost: 100_000)
      item2 = FactoryGirl.create(:invoice_item, invoice: invoice, net_cost: 34_000)
      invoice.invoice_items << [item1, item2]
    end

    it "performs actions on active and suspended users" do
      expect(scope).to receive(:check_user).with(user1)
      expect(scope).to receive(:check_user).with(user2)
      expect(scope).to receive(:check_user).with(suspended_user)
      scope.perform
    end

    it "calls proper actions for users and sets tags" do
      user2.add_tags_by_label(:negative_balance)
      expect(user1).to receive(:act_for_negative_balance)
      expect(user2).to receive(:clear_unpaid_notifications)
      expect(user2.tags.count).to eq 1

      scope.check_user(user1)
      scope.check_user(user2)

      expect(user1.tags.count).to eq 1
      expect(user1.tags.first.label).to eq 'negative_balance'
      expect(user2.tags.count).to eq 0
    end

    context "integration tests for active user" do
      it_behaves_like "negative balance integration" do
        let(:user) {user1}
      end
    end

    context "integration tests for suspended user" do
      it_behaves_like "negative balance integration" do
        let(:user) {suspended_user}
        let!(:server) {FactoryGirl.create :server, user: user}

        before(:each) do
          user.account = invoice.account
          user.save
          user1.reload
        end
      end
    end
  end
end


text:
<!--
Description: ldquo
Expect:      feed['title'] == 'testing \u201c entity'
-->
<feed xmlns="http://www.w3.org/2005/Atom">
<title>testing “ entity</title>
</feed>


text:
from __future__ import print_function

import argparse
import sys
import xml.sax

class PathsExtractor(xml.sax.ContentHandler):

  def __init__(self, polymer_version):
    self.paths = []
    self.polymer_version = polymer_version

  def startElement(self, name, attrs):
    if name != 'structure':
      return
    path = attrs['file']
    if path.startswith('../../../third_party/web-animations-js'):
      return
    prefix = ('../../../third_party/polymer/v%s_0/components-chromium/' %
        self.polymer_version)
    if path.startswith(prefix):
      self.paths.append(path[len(prefix):])
    else:
      raise Exception("Unexpected path %s." % path)

def main(argv):
  parser = argparse.ArgumentParser()
  parser.add_argument('input')
  parser.add_argument('--polymer_version', required=True)
  args = parser.parse_args(argv)

  xml_handler = PathsExtractor(args.polymer_version)
  xml.sax.parse(args.input, xml_handler)
  print('\n'.join(sorted(xml_handler.paths)))

if __name__ == '__main__':
  sys.exit(main(sys.argv[1:]))


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../libc/fn._exit.html">

Redirecting to ../../libc/fn._exit.html...


text:
package org.hisp.dhis.webapi.controller;

import static java.util.stream.Collectors.toList;
import static org.hisp.dhis.datastore.DatastoreQuery.parseFields;
import static org.hisp.dhis.dxf2.webmessage.WebMessageUtils.created;
import static org.hisp.dhis.dxf2.webmessage.WebMessageUtils.ok;
import static org.hisp.dhis.webapi.utils.ContextUtils.setNoStore;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.AllArgsConstructor;
import lombok.Value;

import org.apache.commons.beanutils.BeanUtils;
import org.hisp.dhis.common.DhisApiVersion;
import org.hisp.dhis.common.OpenApi;
import org.hisp.dhis.common.OpenApi.Response.Status;
import org.hisp.dhis.datastore.DatastoreEntry;
import org.hisp.dhis.datastore.DatastoreParams;
import org.hisp.dhis.datastore.DatastoreQuery;
import org.hisp.dhis.datastore.DatastoreQuery.Field;
import org.hisp.dhis.datastore.DatastoreService;
import org.hisp.dhis.dxf2.webmessage.WebMessage;
import org.hisp.dhis.dxf2.webmessage.WebMessageUtils;
import org.hisp.dhis.webapi.JsonWriter;
import org.hisp.dhis.webapi.controller.exception.NotFoundException;
import org.hisp.dhis.webapi.mvc.annotation.ApiVersion;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author Stian Sandvold
 */
@OpenApi.Tags( "data" )
@Controller
@RequestMapping( "/dataStore" )
@ApiVersion( { DhisApiVersion.DEFAULT, DhisApiVersion.ALL } )
@AllArgsConstructor
public class DatastoreController
{
    private final DatastoreService service;

    private final ObjectMapper jsonMapper;

    /**
     * Returns a JSON array of strings representing the different namespaces
     * used. If no namespaces exist, an empty array is returned.
     */
    @GetMapping( value = "", produces = APPLICATION_JSON_VALUE )
    public @ResponseBody List<String> getNamespaces( HttpServletResponse response )
    {
        setNoStore( response );

        return service.getNamespaces();
    }

    /**
     * The path {@code /{namespace}} is clashing with
     * {@link #getEntries(String, String, boolean, DatastoreParams, HttpServletResponse)}
     * therefore a collision free alternative was added
     * {@code /{namespace}/keys}.
     */
    @OpenApi.Response( status = Status.NOT_FOUND, value = WebMessage.class )
    @GetMapping( value = { "/{namespace}/keys" }, produces = APPLICATION_JSON_VALUE )
    public @ResponseBody List<String> getKeysInNamespace( @RequestParam( required = false ) Date lastUpdated,
        @PathVariable String namespace,
        HttpServletResponse response )
        throws Exception
    {
        return getKeysInNamespaceLegacy( lastUpdated, namespace, response );
    }

    /**
     * Returns a list of strings representing keys in the given namespace.
     */
    @OpenApi.Ignore
    @GetMapping( value = "/{namespace}", produces = APPLICATION_JSON_VALUE )
    public @ResponseBody List<String> getKeysInNamespaceLegacy( @RequestParam( required = false ) Date lastUpdated,
        @PathVariable String namespace,
        HttpServletResponse response )
        throws Exception
    {
        setNoStore( response );

        List<String> keys = service.getKeysInNamespace( namespace, lastUpdated );

        if ( keys.isEmpty() && !service.isUsedNamespace( namespace ) )
        {
            throw new NotFoundException( String.format( "Namespace not found: '%s'", namespace ) );
        }

        return keys;
    }

    @Value
    private static class Pager
    {
        int page;

        int pageSize;
    }

    @Value
    private static class EntriesResponse
    {
        Pager pager;

        List<Map<String, JsonNode>> entries;
    }

    @OpenApi.Response( status = Status.OK, value = EntriesResponse.class )
    @OpenApi.Response( status = Status.BAD_REQUEST, value = WebMessage.class )
    @GetMapping( value = "/{namespace}", params = "fields", produces = APPLICATION_JSON_VALUE )
    public void getEntries( @PathVariable String namespace,
        @RequestParam( required = true ) String fields,
        @RequestParam( required = false, defaultValue = "false" ) boolean includeAll,
        DatastoreParams params, HttpServletResponse response )
        throws Exception
    {
        DatastoreQuery query = service.plan( DatastoreQuery.builder()
            .namespace( namespace )
            .fields( parseFields( fields ) )
            .includeAll( includeAll )
            .build().with( params ) );

        response.setContentType( APPLICATION_JSON_VALUE );
        setNoStore( response );

        try ( PrintWriter writer = response.getWriter();
            JsonWriter out = new JsonWriter( writer ) )
        {
            try
            {
                List<String> members = query.getFields().stream().map( Field::getAlias ).collect( toList() );
                service.getFields( query, entries -> {
                    if ( !query.isHeadless() )
                    {
                        writer.write( "{\"pager\":{" );
                        writer.write( "\"page\":" + query.getPage() + "," );
                        writer.write( "\"pageSize\":" + query.getPageSize() );
                        writer.write( "},\"entries\":" );
                    }
                    out.writeEntries( members, entries );
                    return true;
                } );
                if ( !query.isHeadless() )
                {
                    writer.write( "}" );
                }
            }
            catch ( RuntimeException ex )
            {
                response.setStatus( HttpServletResponse.SC_BAD_REQUEST );
                Throwable cause = ex.getCause();
                String msg = "Unknown error when running the query: "
                    + (cause != null && ex.getMessage().contains( "could not extract ResultSet" )
                        ? cause.getMessage()
                        : ex.getMessage());
                if ( cause != null && cause.getMessage().contains( "cannot cast type " )
                    && cause.getMessage().contains( " to double precision" ) )
                {
                    String sortProperty = query.getOrder().getPath();
                    msg = "Cannot use numeric sort order on property `" + sortProperty
                        + "` as the property contains non-numeric values for matching entries. Use " + query.getOrder()
                            .getDirection().name().substring( 1 )
                        + " instead or apply a filter that only matches entries with numeric values for " + sortProperty
                        + ".";
                }
                jsonMapper.writeValue( writer, WebMessageUtils.badRequest( msg ) );
            }
        }
    }

    /**
     * Deletes all keys with the given namespace.
     */
    @OpenApi.Response( status = Status.NOT_FOUND, value = WebMessage.class )
    @ResponseBody
    @DeleteMapping( "/{namespace}" )
    public WebMessage deleteNamespace( @PathVariable String namespace )
        throws Exception
    {
        if ( !service.isUsedNamespace( namespace ) )
        {
            throw new NotFoundException( String.format( "Namespace not found: '%s'", namespace ) );
        }

        service.deleteNamespace( namespace );

        return ok( String.format( "Namespace deleted: '%s'", namespace ) );
    }

    /**
     * Retrieves the value of the KeyJsonValue represented by the given key from
     * the given namespace.
     */
    @OpenApi.Response( status = Status.NOT_FOUND, value = WebMessage.class )
    @GetMapping( value = "/{namespace}/{key}", produces = APPLICATION_JSON_VALUE )
    public @ResponseBody String getKeyJsonValue( @PathVariable String namespace, @PathVariable String key )
        throws NotFoundException
    {
        return getExistingEntry( namespace, key ).getValue();
    }

    /**
     * Retrieves the KeyJsonValue represented by the given key from the given
     * namespace.
     */
    @OpenApi.Response( status = Status.NOT_FOUND, value = WebMessage.class )
    @GetMapping( value = "/{namespace}/{key}/metaData", produces = APPLICATION_JSON_VALUE )
    public @ResponseBody DatastoreEntry getKeyJsonValueMetaData( @PathVariable String namespace,
        @PathVariable String key,
        HttpServletResponse response )
        throws Exception
    {
        DatastoreEntry entry = getExistingEntry( namespace, key );

        DatastoreEntry metaData = new DatastoreEntry();
        BeanUtils.copyProperties( metaData, entry );
        metaData.setValue( null );
        metaData.setJbPlainValue( null );
        metaData.setEncryptedValue( null );
        return metaData;
    }

    /**
     * Creates a new KeyJsonValue Object on the given namespace with the key and
     * value supplied.
     */
    @ResponseBody
    @PostMapping( value = "/{namespace}/{key}", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE )
    @ResponseStatus( HttpStatus.CREATED )
    public WebMessage addKeyJsonValue( @PathVariable String namespace, @PathVariable String key,
        @RequestBody String value,
        @RequestParam( defaultValue = "false" ) boolean encrypt, HttpServletRequest request )
    {
        DatastoreEntry entry = new DatastoreEntry();
        entry.setKey( key );
        entry.setNamespace( namespace );
        entry.setValue( value );
        entry.setEncrypted( encrypt );

        service.addEntry( entry );

        return created( String.format( "Key created: '%s'", key ) );
    }

    /**
     * Update a key in the given namespace.
     */
    @OpenApi.Response( status = Status.NOT_FOUND, value = WebMessage.class )
    @ResponseBody
    @PutMapping( value = "/{namespace}/{key}", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE )
    public WebMessage updateKeyJsonValue( @PathVariable String namespace, @PathVariable String key,
        @RequestBody String value )
        throws Exception
    {
        DatastoreEntry entry = getExistingEntry( namespace, key );
        entry.setValue( value );

        service.updateEntry( entry );

        return ok( String.format( "Key updated: '%s'", key ) );
    }

    /**
     * Delete a key from the given namespace.
     */
    @OpenApi.Response( status = Status.NOT_FOUND, value = WebMessage.class )
    @ResponseBody
    @DeleteMapping( value = "/{namespace}/{key}", produces = APPLICATION_JSON_VALUE )
    public WebMessage deleteKeyJsonValue( @PathVariable String namespace, @PathVariable String key )
        throws Exception
    {
        DatastoreEntry entry = getExistingEntry( namespace, key );
        service.deleteEntry( entry );

        return ok( String.format( "Key '%s' deleted from namespace '%s'", key, namespace ) );
    }

    private DatastoreEntry getExistingEntry( String namespace, String key )
        throws NotFoundException
    {
        DatastoreEntry entry = service.getEntry( namespace, key );

        if ( entry == null )
        {
            throw new NotFoundException( String.format( "Key '%s' not found in namespace '%s'", key, namespace ) );
        }

        return entry;
    }
}


text:
<?php defined('BASEPATH') or exit('No direct script access allowed');

// Page Permissions
$lang['pages:role_put_live']    = 'Publicar páginas';
$lang['pages:role_edit_live']   = 'Editar páginas publicadas';
$lang['pages:role_delete_live'] = 'Eliminar páginas publicadas';

// Page Type Permissions
$lang['pages:role_create_types'] = 'Create Types'; #translate
$lang['pages:role_edit_types']   = 'Edit Types'; #translate
$lang['pages:role_delete_types'] = 'Delete Types'; #translate


text:
using Microsoft.AspNet.Identity;
using Microsoft.Extensions.Logging;
using School.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace School.Services
{
    public class SeedDataService
    {
        private WorldContext _context;
        private ILogger<SeedDataService> _logger;
        private UserManager<WorldUser> _userManager;

        public SeedDataService(WorldContext context, UserManager<WorldUser> userManager,ILogger<SeedDataService> logger)
        {
            _context = context;
            _userManager = userManager;
            _logger = logger;
        }

        public async Task EnsureSeedDataAsync()
        {

            if (await _userManager.FindByEmailAsync("cowboy@acme.com") == null)
            {
                var user = new WorldUser()
                {
                    UserName = "cowboy",
                    Email = "cowboy@acme.com"
                };
               var result= await _userManager.CreateAsync(user, "X");
                Debug.WriteLine(result);
                _logger.LogDebug(String.Format("Default user creation result:{0} {1}",result.Succeeded,result.Errors));
            }
            if (!_context.Trips.Any())
            {
                Trip t = new Trip()
                {
                    Created = DateTime.UtcNow,
                    Name = "Cappadocia",
                    UserName = "cowboy",
                    Destinations = new List<Stop>
                    {
                        new Stop() {
                            Arrival=DateTime.UtcNow,
                            Order=1,
                            Name="Uchisar",
                            Latitude=0.123,
                            Longitude=0.321
                        },
                            new Stop() {
                            Arrival=DateTime.UtcNow,
                            Order=2,
                            Name="Ortahisar",
                            Latitude=2.123,
                            Longitude=2.321
                        },
                            new Stop() {
                            Arrival=DateTime.UtcNow,
                            Order=3,
                            Name="Göreme",
                            Latitude=3.123,
                            Longitude=3.321
                        },
                            new Stop() {
                            Arrival=DateTime.UtcNow,
                            Order=4,
                            Name="Ürgüp",
                            Latitude=4.123,
                            Longitude=4.321
                        }
                    }
                };
                _context.Trips.Add(t);
                await _context.SaveChangesAsync();
            }
        }
    }
}


text:
using System;
using System.Runtime.Serialization;

namespace Spring.Messaging
{
    /// <summary>
    /// Base exception class for exceptions thrown by Spring in Spring.Messaging
    /// </summary>
    /// <author>Mark Pollack</author>
    [Serializable]
    public class MessagingException : ApplicationException
    {
        #region Constructor (s) / Destructor

        /// <summary>Creates a new instance of the MessagingException class.</summary>
        public MessagingException()
        {
        }

        /// <summary>
        /// Creates a new instance of the MessagingException class. with the specified message.
        /// </summary>
        /// <param name="message">
        /// A message about the exception.
        /// </param>
        public MessagingException(string message) : base(message)
        {
        }

        /// <summary>
        /// Creates a new instance of the MessagingException class with the specified message
        /// and root cause.
        /// </summary>
        /// <param name="message">
        /// A message about the exception.
        /// </param>
        /// <param name="rootCause">
        /// The root exception that is being wrapped.
        /// </param>
        public MessagingException(string message, Exception rootCause)
            : base(message, rootCause)
        {
        }

        /// <summary>
        /// Creates a new instance of the MessagingException class.
        /// </summary>
        /// <param name="info">
        /// The <see cref="System.Runtime.Serialization.SerializationInfo"/>
        /// that holds the serialized object data about the exception being thrown.
        /// </param>
        /// <param name="context">
        /// The <see cref="System.Runtime.Serialization.StreamingContext"/>
        /// that contains contextual information about the source or destination.
        /// </param>
        protected MessagingException(
            SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        #endregion
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.ai.metricsadvisor;

import com.azure.ai.metricsadvisor.models.IncidentRootCause;
import com.azure.ai.metricsadvisor.models.MetricsAdvisorServiceVersion;
import com.azure.core.http.HttpClient;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import reactor.test.StepVerifier;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

import static com.azure.ai.metricsadvisor.TestUtils.DISPLAY_NAME_WITH_ARGUMENTS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

public class IncidentRootCauseAsyncTest extends IncidentRootCauseTestBase {

    private MetricsAdvisorAsyncClient client;

    @BeforeAll
    static void beforeAll() {
        StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
    }

    @AfterAll
    static void afterAll() {
        StepVerifier.resetDefaultTimeout();
    }

    /**
     * Verifies the root causes for an incident.
     */
    @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
    @MethodSource("com.azure.ai.metricsadvisor.TestUtils#getTestParameters")
    public void listIncidentRootCauses(HttpClient httpClient,
        MetricsAdvisorServiceVersion serviceVersion) {
        client = getMetricsAdvisorBuilder(httpClient, serviceVersion).buildAsyncClient();
        List<IncidentRootCause> actualIncidentRootCauses = new ArrayList<>();

        StepVerifier.create(client.listIncidentRootCauses(
            INCIDENT_ROOT_CAUSE_CONFIGURATION_ID, INCIDENT_ROOT_CAUSE_ID))
            .thenConsumeWhile(actualIncidentRootCauses::add)
            .verifyComplete();

        assertNotNull(actualIncidentRootCauses);
        assertEquals(1, actualIncidentRootCauses.size());
        validateIncidentRootCauses(getExpectedIncidentRootCause(), actualIncidentRootCauses.get(0));
    }
}


text:
The Work and Meaning Inventory (WAMI) Calculator: https://kevgrig.github.io/wami-react/

## Development

* Main code at https://github.com/kevgrig/wami-react/blob/master/src/App.js
* Built with https://github.com/facebookincubator/create-react-app (see also https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md)
  * sudo npm install -g create-react-app
  * sudo npm install --save-dev gh-pages
* npm start # Local site at http://localhost:3000/
* npm run deploy # Deploy production build to https://kevgrig.github.io/wami-react/


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Deleting model 'Prey'
        db.delete_table('mantises_prey')

        # Deleting model 'Feeding'
        db.delete_table('mantises_feeding')

    def backwards(self, orm):
        # Adding model 'Prey'
        db.create_table('mantises_prey', (
            ('short_name', self.gf('django.db.models.fields.CharField')(max_length=200)),
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
            ('status', self.gf('django.db.models.fields.CharField')(max_length=1)),
            ('long_name', self.gf('django.db.models.fields.CharField')(max_length=300)),
        ))
        db.send_create_signal('mantises', ['Prey'])

        # Adding model 'Feeding'
        db.create_table('mantises_feeding', (
            ('total_fed', self.gf('django.db.models.fields.PositiveSmallIntegerField')()),
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('prey', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['mantises.Prey'])),
            ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
            ('feeding_date', self.gf('django.db.models.fields.DateTimeField')()),
            ('accepted', self.gf('django.db.models.fields.PositiveSmallIntegerField')()),
        ))
        db.send_create_signal('mantises', ['Feeding'])

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'to': "orm['auth.Permission']", 'symmetrical': 'False'})
        },
        'auth.permission': {
            'Meta': {'object_name': 'Permission', 'unique_together': "(('content_type', 'codename'),)", 'ordering': "('content_type__app_label', 'content_type__model', 'codename')"},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'blank': 'True', 'max_length': '75'}),
            'first_name': ('django.db.models.fields.CharField', [], {'blank': 'True', 'max_length': '30'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'to': "orm['auth.Group']", 'related_name': "'user_set'", 'symmetrical': 'False'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'blank': 'True', 'max_length': '30'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'to': "orm['auth.Permission']", 'related_name': "'user_set'", 'symmetrical': 'False'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'containers.container': {
            'Meta': {'object_name': 'Container'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['containers.ContainerType']"}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
        },
        'containers.containertype': {
            'Meta': {'object_name': 'ContainerType', 'unique_together': "(('height', 'length', 'width', 'type'),)"},
            'height': ('django.db.models.fields.DecimalField', [], {'decimal_places': '2', 'max_digits': '5'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'length': ('django.db.models.fields.DecimalField', [], {'decimal_places': '2', 'max_digits': '5'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200'}),
            'type': ('django.db.models.fields.CharField', [], {'max_length': '1'}),
            'url': ('django.db.models.fields.URLField', [], {'blank': 'True', 'max_length': '200'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
            'width': ('django.db.models.fields.DecimalField', [], {'decimal_places': '2', 'max_digits': '5'})
        },
        'contenttypes.contenttype': {
            'Meta': {'db_table': "'django_content_type'", 'object_name': 'ContentType', 'unique_together': "(('app_label', 'model'),)", 'ordering': "('name',)"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'mantises.breed': {
            'Meta': {'object_name': 'Breed'},
            'adult_instar_female': ('django.db.models.fields.SmallIntegerField', [], {}),
            'adult_instar_male': ('django.db.models.fields.SmallIntegerField', [], {}),
            'high_humidity': ('django.db.models.fields.DecimalField', [], {'decimal_places': '2', 'max_digits': '5'}),
            'high_temperature': ('django.db.models.fields.DecimalField', [], {'decimal_places': '2', 'max_digits': '5'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'life_expectancy': ('django.db.models.fields.DecimalField', [], {'decimal_places': '4', 'max_digits': '5'}),
            'long_name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '300'}),
            'low_humidity': ('django.db.models.fields.DecimalField', [], {'decimal_places': '2', 'max_digits': '5'}),
            'low_temperature': ('django.db.models.fields.DecimalField', [], {'decimal_places': '2', 'max_digits': '5'}),
            'picture': ('django.db.models.fields.related.ForeignKey', [], {'null': 'True', 'blank': 'True', 'to': "orm['photologue.Photo']"}),
            'short_name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
        },
        'mantises.mantis': {
            'Meta': {'object_name': 'Mantis'},
            'born': ('django.db.models.fields.DateTimeField', [], {}),
            'breed': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['mantises.Breed']"}),
            'container': ('django.db.models.fields.related.ForeignKey', [], {'null': 'True', 'blank': 'True', 'to': "orm['containers.Container']"}),
            'died': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
            'from_colony': ('django.db.models.fields.related.ForeignKey', [], {'null': 'True', 'blank': 'True', 'to': "orm['mantises.NymphColony']"}),
            'gallery': ('django.db.models.fields.related.ForeignKey', [], {'null': 'True', 'blank': 'True', 'to': "orm['photologue.Gallery']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'notes': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'sex': ('django.db.models.fields.CharField', [], {'max_length': '1'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
        },
        'mantises.molt': {
            'Meta': {'object_name': 'Molt', 'unique_together': "(('to_instar', 'from_instar', 'mantis'),)"},
            'date': ('django.db.models.fields.DateTimeField', [], {}),
            'from_instar': ('django.db.models.fields.PositiveSmallIntegerField', [], {}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'mantis': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['mantises.Mantis']"}),
            'to_instar': ('django.db.models.fields.PositiveSmallIntegerField', [], {}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
        },
        'mantises.nymphcolony': {
            'Meta': {'object_name': 'NymphColony'},
            'container': ('django.db.models.fields.related.ForeignKey', [], {'null': 'True', 'blank': 'True', 'to': "orm['containers.Container']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'num_died': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'num_hatched': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
        },
        'mantises.ooth': {
            'Meta': {'object_name': 'Ooth'},
            'container': ('django.db.models.fields.related.ForeignKey', [], {'null': 'True', 'blank': 'True', 'to': "orm['containers.Container']"}),
            'date_hatched': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
            'date_laid': ('django.db.models.fields.DateTimeField', [], {}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'laid_by': ('django.db.models.fields.related.ForeignKey', [], {'null': 'True', 'blank': 'True', 'to': "orm['mantises.Mantis']"}),
            'nymphs': ('django.db.models.fields.related.ForeignKey', [], {'null': 'True', 'blank': 'True', 'to': "orm['mantises.NymphColony']"}),
            'picture': ('django.db.models.fields.related.ForeignKey', [], {'null': 'True', 'blank': 'True', 'to': "orm['photologue.Photo']"}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
        },
        'photologue.gallery': {
            'Meta': {'object_name': 'Gallery', 'ordering': "['-date_added']"},
            'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'photos': ('django.db.models.fields.related.ManyToManyField', [], {'null': 'True', 'blank': 'True', 'to': "orm['photologue.Photo']", 'related_name': "'galleries'", 'symmetrical': 'False'}),
            'tags': ('photologue.models.TagField', [], {'blank': 'True', 'max_length': '255'}),
            'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'}),
            'title_slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'})
        },
        'photologue.photo': {
            'Meta': {'object_name': 'Photo', 'ordering': "['-date_added']"},
            'caption': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'crop_from': ('django.db.models.fields.CharField', [], {'blank': 'True', 'max_length': '10', 'default': "'center'"}),
            'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'date_taken': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
            'effect': ('django.db.models.fields.related.ForeignKey', [], {'null': 'True', 'blank': 'True', 'to': "orm['photologue.PhotoEffect']", 'related_name': "'photo_related'"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}),
            'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'tags': ('photologue.models.TagField', [], {'blank': 'True', 'max_length': '255'}),
            'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'}),
            'title_slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}),
            'view_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'})
        },
        'photologue.photoeffect': {
            'Meta': {'object_name': 'PhotoEffect'},
            'background_color': ('django.db.models.fields.CharField', [], {'max_length': '7', 'default': "'#FFFFFF'"}),
            'brightness': ('django.db.models.fields.FloatField', [], {'default': '1.0'}),
            'color': ('django.db.models.fields.FloatField', [], {'default': '1.0'}),
            'contrast': ('django.db.models.fields.FloatField', [], {'default': '1.0'}),
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'filters': ('django.db.models.fields.CharField', [], {'blank': 'True', 'max_length': '200'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}),
            'reflection_size': ('django.db.models.fields.FloatField', [], {'default': '0'}),
            'reflection_strength': ('django.db.models.fields.FloatField', [], {'default': '0.6'}),
            'sharpness': ('django.db.models.fields.FloatField', [], {'default': '1.0'}),
            'transpose_method': ('django.db.models.fields.CharField', [], {'blank': 'True', 'max_length': '15'})
        }
    }

    complete_apps = ['mantises']


text:
package com.factual.demo;

import static com.factual.driver.FactualTest.factual;

import com.factual.driver.Factual;
import com.factual.driver.Query;

public class DemoSimpleRead {

  public static void main(String[] args) {
    Factual factual = factual();

    System.out.println(
        factual.fetch("places", new Query().limit(3)));
  }

}


text:
import setuptools

setuptools.setup(
    name='python-runabove',
    version='1.3.0',
    author='RunAbove',
    author_email='dev@runabove.com',
    url='https://www.runabove.com/',
    description='RunAbove API Client Library',
    keywords = "runabove api sdk",
    license='MIT',
    packages=['runabove'],
    test_suite='runabove.tests',
    install_requires=[
        'python-swiftclient>=2.3.1',
        'requests>=2.5.1'
    ]
)


text:
namespace DivineInject.Test.DummyModel
{
    public class DomainObjectWithOneDependency : IDomainObject
    {
        public DomainObjectWithOneDependency(IDatabase database)
        {
            Database = database;
        }

        public IDatabase Database { get; private set; }
    }
}


text:
define :apache_conf do
  template "#{node[:apache][:dir]}/mods-available/#{params[:name]}.conf" do
    source "mods/#{params[:name]}.conf.erb"
    notifies :restart, resources(:service => "apache2")
    mode 0644
  end
end


text:
package edu.ncsu.monopoly;

import junit.framework.TestCase;

public class PropertyCellTest extends TestCase {

	GameMaster gameMaster;

	protected void setUp() {
		gameMaster = GameMaster.instance();
		gameMaster.setGameBoard(new SimpleGameBoard());
		gameMaster.setNumberOfPlayers(2);
		gameMaster.reset();
		gameMaster.setGUI(new MockGUI());
	}

	public void testPlayerAction() {
		PropertyCell cell =
			(PropertyCell) gameMaster.getGameBoard().queryCell("Blue 3");
		int cellIndex = gameMaster.getGameBoard().queryCellIndex("Blue 3");
		gameMaster.movePlayer(0, cellIndex);
		gameMaster.getPlayer(0).purchase();
		gameMaster.switchTurn();
		gameMaster.movePlayer(1, cellIndex);
		cell.playAction();
		assertEquals(
				1500 - cell.getRent(),
				gameMaster.getPlayer(1).getMoney());
		assertEquals(
				1380 + cell.getRent(),
				gameMaster.getPlayer(0).getMoney());
	}
}


text:
namespace web
{
namespace page
{
namespace templates
{

AbstractTemplatePage::~AbstractTemplatePage()
{
    Q_D(AbstractTemplatePage);

    delete d->pageModel;
    qDeleteAll(d->templateModels);

    delete d_ptr;
}

QByteArray AbstractTemplatePage::getContent()
{
    Q_D(AbstractTemplatePage);

    if ( d->pageData.isEmpty() ) {
            initPage();
        }

    if ( d->templates.isEmpty() ) {
            initTemplates();
        }

    initModels();

    render();

    destroyModels();

    return d->content;
}

void AbstractTemplatePage::setSession(website::WebSession *s)
{
    Q_D(AbstractTemplatePage);
    d->session = s;
}

void AbstractTemplatePage::setRequest(Tufao::HttpServerRequest *r)
{
    Q_D(AbstractTemplatePage);
    d->request = r;
}

void AbstractTemplatePage::setResponse(Tufao::HttpServerResponse *r)
{
    Q_D(AbstractTemplatePage);
    d->response = r;
}

void AbstractTemplatePage::setPostRequestData(QMap<QByteArray, QByteArray> data)
{
    Q_D(AbstractTemplatePage);
    d->post = data;
}

void AbstractTemplatePage::clearPostRequestData()
{
    Q_D(AbstractTemplatePage);
    d->post.clear();
}

void AbstractTemplatePage::setGetRequestData(QMap<QByteArray, QByteArray> data)
{
    Q_D(AbstractTemplatePage);
    d->get = data;
}

void AbstractTemplatePage::clearGetRequestData()
{
    Q_D(AbstractTemplatePage);
    d->get.clear();
}

void AbstractTemplatePage::setRequestPath(const QString & path)
{
    Q_D(AbstractTemplatePage);
    d->requestPath = path;
}

bool AbstractTemplatePage::isFileUploadAllowed()
{
    return false;
}

bool AbstractTemplatePage::isWaitingForFileUploadToFinish()
{
    return false;
}

void AbstractTemplatePage::onFileUploadFinished()
{
    return; // Do nothing
}

AbstractTemplatePage::AbstractTemplatePage(AbstractTemplatePagePrivate *d) :
    d_ptr(d)
{
}

void AbstractTemplatePage::initPage()
{
    Q_D(AbstractTemplatePage);
    QString filepath = QCoreApplication::applicationDirPath() + QDir::separator() + d->pageFilename;
    QFile f(filepath);
    if ( f.open(QIODevice::ReadOnly) ) {
            QByteArray data = f.readAll();
            d->pageData = data;
            f.close();
        }
    else {
            qDebug() << Q_FUNC_INFO << f.errorString();
        }
}

void AbstractTemplatePage::initTemplate(QString name, QString filename)
{
    QFile f(filename);
    if ( f.open(QIODevice::ReadOnly) ) {
            Q_D(AbstractTemplatePage);
            QByteArray data = f.readAll();
            d->templates.insert(name, data);
            f.close();
        }
    else {
            qDebug() << Q_FUNC_INFO << f.errorString();
    }
}

void AbstractTemplatePage::loadModel(const QString & name)
{
    Q_D(AbstractTemplatePage);
    model::AbstractListModel * model = d->templateModels.value(name);
    model->load();
}

void AbstractTemplatePage::unloadModel(const QString & name)
{
    Q_D(AbstractTemplatePage);
    model::AbstractListModel * model = d->templateModels.value(name);
    model->unload();
}

void AbstractTemplatePage::render()
{
    Q_D(AbstractTemplatePage);

    QDomDocument doc;
    QString errMsg;
    int errLine, errColumn;
    doc.setContent(d->pageData, false, &errMsg, &errLine, &errColumn);

    QDomNodeList templates = doc.elementsByTagName("tpl");
    const int templateSize = templates.size();
    // We need to go backwards because otherwise the deleting of nodes doesnt work
    for (int i = templateSize-1; i >= 0 ; --i) {
            QDomElement element = templates.item(i).toElement();
            QDomNode parentNode = element.parentNode();

            if (element.hasAttribute("src")) {
                    QString tplName = element.attribute("src");
                    bool isAllowedToShow = true;

                    if (element.hasAttribute("if")) {
                            QString ifAttribute = element.attribute("if");
                            isAllowedToShow = d->isTemplateAllowed(ifAttribute, d->pageModel);
                        }
                    else if (element.hasAttribute("if-not")) {
                            QString ifAttribute = element.attribute("if-not");
                            isAllowedToShow = !d->isTemplateAllowed(ifAttribute, d->pageModel);
                        }

                    if (isAllowedToShow) {

                            QString templateStartTag = QStringLiteral("<tpl>");
                            QString templateEndTag = QStringLiteral("</tpl>");
                            QString templateContent = d->templates[tplName].replace(templateStartTag, "").replace(templateEndTag, "");
                            QString templateFilled;

                            if (element.hasAttribute("model")) {
                                    QString modelName = element.attribute("model");
                                    web::page::model::AbstractListModel *model = d->templateModels[modelName];
                                    model->load();
                                    QList<web::page::model::AbstractModel *> modelList = model->models();
                                    QString modelIfAttribute;
                                    int modelCountAttribute = -1;
                                    int modelStartCountAttribute = -1;

                                    bool hasIfAttribute = false;

                                    if (element.hasAttribute("if-model")) {
                                            modelIfAttribute = element.attribute("if-model");
                                            hasIfAttribute = true;
                                        }

                                    if (element.hasAttribute("model-start-count")) {
                                        modelStartCountAttribute = d->getTemplateAttribute<int>(element,
                                                                                "model-start-count",
                                                                                d->pageModel);
                                    }

                                    if (element.hasAttribute("model-count")) {
                                        modelCountAttribute = d->getTemplateAttribute<int>(element,
                                                                                "model-count",
                                                                                d->pageModel);
                                    }

                                    if ( modelStartCountAttribute < 0 ) {
                                        modelStartCountAttribute = 0;
                                    }

                                    if ( modelCountAttribute <= 0 ) {
                                        modelCountAttribute  = modelList.size();
                                    }
                                    else {
                                        modelCountAttribute = modelStartCountAttribute + modelCountAttribute;
                                    }

                                    const int maxCount = modelList.size();

                                    for (int i = modelStartCountAttribute; i < modelCountAttribute && i < maxCount; ++i) {
                                            QString modelTemplate = templateContent;
                                            web::page::model::AbstractModel *templateModel = modelList.at(i);

                                            if (d->isTemplateAllowed(modelIfAttribute, templateModel) || !hasIfAttribute) {
                                                    d->replaceModelPlaceholders(modelTemplate, templateModel);
                                                    templateFilled += modelTemplate;
                                                }

                                            model->unload();
                                        }
                                } else {
                                    templateFilled = templateContent;
                                }

                            templateFilled = QStringLiteral("<div>") + templateFilled + QStringLiteral("</div>");
                            QDomDocument tplDoc;
                            tplDoc.setContent(templateFilled, false, &errMsg, &errLine, &errColumn);

                            parentNode.replaceChild(tplDoc.documentElement(), element);
                        } else {
                            parentNode.removeChild(element);
                        }
                }
            else {
                    parentNode.removeChild(element);
                }
        }

    QString content = doc.toString();
    d->replaceModelPlaceholders(content, d->pageModel);

    d->content = content.toUtf8();
}

AbstractTemplatePage *createTemplatePage(AbstractTemplatePage *t)
{
    t->createModels();
    return t;
}

}
}
}


text:
#!/usr/bin/env php
<?php
/**
 * Assumes to run in a SilverStripe webroot
 */
require_once 'lib.php';

$opts = getopt('', array(
	'if-env:',
	'base-url:',
));

// --if-env=BEHAT_TEST means that this script will only be executed if the given environment var is set
if(!checkenv(@$opts['if-env'])) {
	echo "Apache skipped; {$opts['if-env']} wasn't set.\n";
	exit(0);
}

$baseurl = (isset($opts['base-url'])) ? $opts['base-url'] : 'http://localhost:8000';

$resolution = getenv('BEHAT_SCREEN_SIZE');
if(!$resolution) {
	$resolution = '1024x768';
	putenv("BEHAT_SCREEN_SIZE=$resolution");
}

echo "Starting xvfb at {$resolution}...\n";
$XVFBARGS = ":99 -ac -screen 0 {$resolution}x24";
putenv("XVFBARGS={$XVFBARGS}");
run("/usr/bin/Xvfb $XVFBARGS &");
//run("/sbin/start-stop-daemon --start --quiet --pidfile /tmp/cucumber_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- $XVFBARGS");

if(!putenv("DISPLAY=:99")) echo "ERROR: Could not set display!\n";
run("wget https://selenium-release.storage.googleapis.com/2.41/selenium-server-standalone-2.41.0.jar");
if(!file_exists('artifacts')) mkdir('artifacts');
run("java -jar selenium-server-standalone-2.41.0.jar > artifacts/selenium.log 2>&1 &");
sleep(5);

// Write templated behat configuration
$behatTemplate = file_get_contents(dirname(__FILE__).'/behat.tmpl.yml');
$behat = str_replace(
	array('$BASE_URL'),
	array($baseurl),
	$behatTemplate
);
echo "Writing behat.yml\n";
echo $behat . "\n";
file_put_contents("behat.yml", $behat);

if(file_exists("mysite/_config/behat.yml")) unlink("mysite/_config/behat.yml");
run("php framework/cli-script.php dev/generatesecuretoken path=mysite/_config/behat.yml");


text:
layout: post
date: 2017-11-24
title: "Sherri Hill Fall 2014 Style 32002 2014 Fall Sleeveless Short/Mini Sheath/Column"
category: Sherri Hill
tags: [Sherri Hill ,Sherri Hill,Sheath/Column,Halter,Short/Mini,Sleeveless,2014,Fall]
---
### Sherri Hill Fall 2014 Style 32002
Just **$469.99**
### 2014 Fall Sleeveless Short/Mini Sheath/Column

BRANDS	Sherri Hill

Silhouette	Sheath/Column

Neckline	Halter

Hemline/Train	Short/Mini

Sleeve	Sleeveless

Years	2014

Season	Fall

Buy it: [https://www.readybrides.com/en/sherri-hill-/50903-sherri-hill-fall-2014-style-32002.html](https://www.readybrides.com/en/sherri-hill-/50903-sherri-hill-fall-2014-style-32002.html)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.jenkins-ci.plugins</groupId>
    <artifactId>plugin</artifactId>
    <version>2.3</version>
    <relativePath/>
  </parent>
  <groupId>org.jenkins-ci.plugins</groupId>
  <artifactId>slack-bot</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>hpi</packaging>

  <properties>
    <!-- Baseline Jenkins version you use to build the plugin. Users must have this version or newer to run. -->
    <jenkins.version>1.625.3</jenkins.version>
    <!-- Java Level to use. Java 7 required when using core >= 1.612 -->
    <java.level>7</java.level>
    <!-- Jenkins Test Harness version you use to test the plugin. -->
    <!-- For Jenkins version >= 1.580.1 use JTH 2.x or higher. -->
    <jenkins-test-harness.version>2.1</jenkins-test-harness.version>
    <!-- Other properties you may want to use:
         ~ hpi-plugin.version: The HPI Maven Plugin version used by the plugin..
         ~ stapler-plugin.version: The Stapler Maven plugin version required by the plugin.
    -->
  </properties>

  <name>Slack bot Plugin</name>
  <description>Slack bot plugin for slack command /jenkins</description>
  <url>https://github.com/JIoJIaJIu/slack-bot-plugin.git</url>

  <!-- The default licence for Jenkins OSS Plugins is MIT. Substitute for the applicable one if needed. -->

  <licenses>
    <license>
      <name>MIT License</name>
      <url>http://opensource.org/licenses/MIT</url>
    </license>
  </licenses>

  <!-- If you want this to appear on the wiki page:
  <developers>
    <developer>
      <id>bhacker</id>
      <name>Bob Q. Hacker</name>
      <email>bhacker@nowhere.net</email>
    </developer>
  </developers>
  -->
  <!-- Assuming you want to host on @jenkinsci:
  <scm>
    <connection>scm:git:git://github.com/jenkinsci/${project.artifactId}-plugin.git</connection>
    <developerConnection>scm:git:git@github.com:jenkinsci/${project.artifactId}-plugin.git</developerConnection>
    <url>http://github.com/jenkinsci/${project.artifactId}-plugin</url>
  </scm>
   -->
  <repositories>
    <repository>
      <id>repo.jenkins-ci.org</id>
      <url>http://repo.jenkins-ci.org/public/</url>
    </repository>
  </repositories>
  <pluginRepositories>
    <pluginRepository>
      <id>repo.jenkins-ci.org</id>
      <url>http://repo.jenkins-ci.org/public/</url>
    </pluginRepository>
  </pluginRepositories>

  <dependencies>
    <dependency>
      <groupId>org.jenkins-ci.plugins</groupId>
      <artifactId>build-token-root</artifactId>
      <version>1.3</version>
    </dependency>
    <dependency>
      <groupId>org.jenkins-ci.plugins</groupId>
      <artifactId>buildtriggerbadge</artifactId>
      <version>2.2</version>
    </dependency>
  </dependencies>

</project>


text:
class InlineLoginHandler : public content::WebUIMessageHandler {
 public:
  InlineLoginHandler();
  virtual ~InlineLoginHandler();

  // content::WebUIMessageHandler overrides:
  virtual void RegisterMessages() OVERRIDE;

 protected:
  // Enum for gaia auth mode, must match AuthMode defined in
  // chrome/browser/resources/gaia_auth_host/gaia_auth_host.js.
  enum AuthMode {
    kDefaultAuthMode = 0,
    kOfflineAuthMode = 1,
    kDesktopAuthMode = 2
  };

 private:
  // JS callback to initialize the gaia auth extension. It calls
  // |SetExtraInitParams| to set extra init params.
  void HandleInitializeMessage(const base::ListValue* args);
  // JS callback to complete login. It calls |CompleteLogin| to do the real
  // work.
  void HandleCompleteLoginMessage(const base::ListValue* args);

  virtual void SetExtraInitParams(base::DictionaryValue& params) {}
  virtual void CompleteLogin(const base::ListValue* args) = 0;

  DISALLOW_COPY_AND_ASSIGN(InlineLoginHandler);
};

#endif  // CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_HANDLER_H_


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Fonebox Privacy Policy</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/full-slider.css" rel="stylesheet">
    <link href="css/style.css?ver=1.0" rel="stylesheet">
	<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-nav">
                Toggle navigation

              </button>

Home

The Fonebox Experience

Fonebox for Business

Frequently Asked Questions

Contact Us

Privacy Policy

This privacy policy sets out how Fonebox uses and protects any information that you give Fonebox when you use this website.

Fonebox is committed to ensuring that your privacy is protected. Should we ask you to provide certain information by which you can be identified when using this website, then you can be assured that it will only be used in accordance with this privacy statement.

Fonebox may change this policy from time to time by updating this page. You should check this page from time to time to ensure that you are happy with any changes. This policy is effective from 8th May 2015.

What we collect

We may collect the following information:

name and job title

contact information including email address

demographic information such as postcode, preferences and interests

other information relevant to customer surveys and/or offers

What we do with the information we gather

We require this information to understand your needs and provide you with a better service, and in particular for the following reasons:

Internal record keeping.

We may use the information to improve our products and services.

We may periodically send promotional emails about new products, special offers or other information which we think you may find interesting using the email address which you have provided.

From time to time, we may also use your information to contact you for market research purposes. We may contact you by email, phone, fax or mail. We may use the information to customise the website according to your interests.

Security

We are committed to ensuring that your information is secure. In order to prevent unauthorised access or disclosure, we have put in place suitable physical, electronic and managerial procedures to safeguard and secure the information we collect online.

How we use cookies

A cookie is a small file which asks permission to be placed on your computer's hard drive. Once you agree, the file is added and the cookie helps analyse web traffic or lets you know when you visit a particular site. Cookies allow web applications to respond to you as an individual. The web application can tailor its operations to your needs, likes and dislikes by gathering and remembering information about your preferences.

We use traffic log cookies to identify which pages are being used. This helps us analyse data about webpage traffic and improve our website in order to tailor it to customer needs. We only use this information for statistical analysis purposes and then the data is removed from the system.

Overall, cookies help us provide you with a better website by enabling us to monitor which pages you find useful and which you do not. A cookie in no way gives us access to your computer or any information about you, other than the data you choose to share with us.

You can choose to accept or decline cookies. Most web browsers automatically accept cookies, but you can usually modify your browser setting to decline cookies if you prefer. This may prevent you from taking full advantage of the website.

Links to other websites

Our website may contain links to other websites of interest. However, once you have used these links to leave our site, you should note that we do not have any control over that other website. Therefore, we cannot be responsible for the protection and privacy of any information which you provide whilst visiting such sites and such sites are not governed by this privacy statement. You should exercise caution and look at the privacy statement applicable to the website in question.

Controlling your personal information

You may choose to restrict the collection or use of your personal information in the following ways:

whenever you are asked to fill in a form on the website, look for the box that you can click to indicate that you do not want the information to be used by anybody for direct marketing purposes

if you have previously agreed to us using your personal information for direct marketing purposes, you may change your mind at any time by writing to or emailing us at [email address]

We will not sell, distribute or lease your personal information to third parties unless we have your permission or are required by law to do so. We may use your personal information to send you promotional information about third parties which we think you may find interesting if you tell us that you wish this to happen.

You may request details of personal information which we hold about you under the Data Protection Act 1998. A small fee will be payable. If you would like a copy of the information held on you please write to 12 Epsom Road, CH46 1PT.

If you believe that any information we are holding on you is incorrect or incomplete, please write to or email us as soon as possible at the above address. We will promptly correct any information found to be incorrect.

Get News & Updates

        	<form>

                  <input type="email" name="email" class="form-control" placeholder="Enter your email address to recieve updates">

                    <button class="btn btn-primary" type="button">Sign Up!</button>

            </form>

© 2015 Fonebox Trading Ltd. All Rights Reserved | Terms & Conditions | Privacy Policy


text:
#include <v8.h>
#include <cerrno>
#include <sstream>
#include "device.h"

namespace node_ios_device {

using namespace v8;

void relayLogMessages(LogRelayInfo* info, const char* buffer) {
	std::string line;

	for (; *buffer; ++buffer) {
		if (*buffer == '\0' || *buffer == '\r' || *buffer == '\n') {
			if (!line.empty()) {
				send(info->eventName, line);
				line.clear();
			}
		} else {
			line += *buffer;
		}
	}

	if (!line.empty()) {
		send(info->eventName, line);
	}
}

/**
 * Constructs the device object.
 */
Device::Device(am_device& dev) : loaded(false), handle(dev), connected(0), syslogRelayInfo(NULL) {
	this->udid = AMDeviceCopyDeviceIdentifier(dev);

	char* str = cfstring_to_cstr(this->udid);
	if (str == NULL) {
		throw std::runtime_error("Unable to read device UDID");
	}

	this->props["udid"] = std::string(str);
	free(str);
}

/**
 * Disconnects and cleans up allocated memory.
 */
Device::~Device() {
	this->disconnect(true);

	auto it = this->logPortRelayInfo.begin();
	while (it != this->logPortRelayInfo.end()) {
		this->stopLogPortRelay(it->first);
		auto next = this->logPortRelayInfo.begin();
		if (next == it) {
			it++;
		} else {
			it = next;
		}
	}

	if (this->syslogRelayInfo) {
		this->stopSyslogRelay();
		delete this->syslogRelayInfo;
		this->syslogRelayInfo = NULL;
	}
}

/**
 * Connects to the device and gets the device info. This should be called
 * immediately after creating a new Device instance. Once it's initialized,
 * check the `loaded` member to make sure that things loaded properly.
 */
void Device::init() {
	debug("Getting device info: %s", this->props["udid"].c_str());

	// connect to the device and get its information
	this->connect();

	this->set("name",            CFSTR("DeviceName"));
	this->set("buildVersion",    CFSTR("BuildVersion"));
	this->set("cpuArchitecture", CFSTR("CPUArchitecture"));
	this->set("deviceClass",     CFSTR("DeviceClass"));
	this->set("deviceColor",     CFSTR("DeviceColor"));
	this->set("hardwareModel",   CFSTR("HardwareModel"));
	this->set("modelNumber",     CFSTR("ModelNumber"));
	this->set("productType",     CFSTR("ProductType"));
	this->set("productVersion",  CFSTR("ProductVersion"));
	this->set("serialNumber",    CFSTR("SerialNumber"));

	this->disconnect();

	this->loaded = true;
}

/**
 * Installs the specified app on the device.
 */
void Device::install(const char* appPath) {
	// get the path to the app
	CFStringRef appPathStr = ::CFStringCreateWithCString(NULL, appPath, kCFStringEncodingUTF8);
	CFURLRef relativeUrl = ::CFURLCreateWithFileSystemPath(NULL, appPathStr, kCFURLPOSIXPathStyle, false);
	CFURLRef localUrl = ::CFURLCopyAbsoluteURL(relativeUrl);
	::CFRelease(appPathStr);
	::CFRelease(relativeUrl);

	CFStringRef keys[] = { CFSTR("PackageType") };
	CFStringRef values[] = { CFSTR("Developer") };
	CFDictionaryRef options = CFDictionaryCreate(NULL, (const void **)&keys, (const void **)&values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

	this->connect();

	// copy .app to device
	debug("Transferring app to device: %s", this->props["udid"].c_str());
	mach_error_t rval = ::AMDeviceSecureTransferPath(0, this->handle, localUrl, options, NULL, 0);
	if (rval != MDERR_OK) {
		::CFRelease(options);
		::CFRelease(localUrl);
		this->disconnect();
		if (rval == -402653177) {
			throw std::runtime_error("Failed to copy app to device: can't install app that contains symlinks");
		} else {
			std::stringstream error;
			error << "Failed to transfer app to device (0x" << std::hex << rval << ")";
			throw std::runtime_error(error.str());
		}
	}

	// install package on device
	debug("Installing app on device: %s", this->props["udid"].c_str());
	rval = ::AMDeviceSecureInstallApplication(0, this->handle, localUrl, options, NULL, 0);
	::CFRelease(options);
	::CFRelease(localUrl);
	this->disconnect();

	if (rval == -402620395) {
		throw std::runtime_error("Failed to install app on device: most likely a provisioning profile issue");
	} else if (rval != MDERR_OK) {
		std::stringstream error;
		error << "Failed to install app on device (0x" << std::hex << rval << ")";
		throw std::runtime_error(error.str());
	}
}

/**
 * Connects to a port on the iOS device.
 */
void Device::startLogPortRelay(uint32_t port) {
	if (this->logPortRelayInfo.count(port)) {
		debug("Log connection already started");
		return;
	}

	std::stringstream eventName;
	eventName << "LOG_PORT_" << port << "_" << this->props["udid"];
	LogRelayInfo* info = new LogRelayInfo(this, eventName.str(), port);

	int fd = -1;
	unsigned int id = ::AMDeviceGetConnectionID(this->handle);

	debug("Trying to connect to port %d", port);
	if (::USBMuxConnectByPort(id, htons(port), &fd) != 0) {
		::close(fd);
		std::stringstream error;
		error << "Failed to connect to port " << port;
		throw std::runtime_error(error.str());
	}
	debug("Connected");

	CFSocketContext socketCtx = { 0, info, NULL, NULL, NULL };

	info->socket = ::CFSocketCreateWithNative(
		kCFAllocatorDefault,
		fd,
		kCFSocketDataCallBack,
		&Device::logPortRelaySocketCallback,
		&socketCtx
	);

	debug("Creating run loop source");
	info->source = ::CFSocketCreateRunLoopSource(kCFAllocatorDefault, info->socket, 0);
	if (!info->source) {
		delete info;
		throw std::runtime_error("Failed to create socket run loop source");
	}

	debug("Adding run loop source to run loop");
	::CFRunLoopAddSource(runloop, info->source, kCFRunLoopCommonModes);

	// only add the log relay info if things worked
	this->logPortRelayInfo[port] = info;
}

void Device::stopLogPortRelay(uint32_t port) {
	if (this->logPortRelayInfo.count(port)) {
		debug("Stopping log relay for port %d", port);
		delete this->logPortRelayInfo[port];
		this->logPortRelayInfo.erase(port);
	} else {
		debug("Log relay for port %d already stopped", port);
	}
}

/**
 * Called when there are bytes received from the tunnel to the device.
 */
void Device::logPortRelaySocketCallback(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) {
	const char* buffer = (const char*)CFDataGetBytePtr((CFDataRef)data);
	if (*buffer == '\0') {
		// if the buffer is empty, then that means that the app has quit
		LogRelayInfo* lri = (LogRelayInfo*)info;
		std::stringstream port;
		port << lri->port;

		lri->device->stopLogPortRelay(lri->port);

		send("app-quit", port.str());
	} else {
		relayLogMessages((LogRelayInfo*)info, buffer);
	}
}

/**
 * Starts the log relay service and wires up the connection to the run loop.
 */
void Device::startSyslogRelay() {
	if (this->syslogRelayInfo) {
		debug("Syslog connection already started");
		return;
	}

	std::stringstream eventName;
	eventName << "SYSLOG_" << this->props["udid"];
	this->syslogRelayInfo = new LogRelayInfo(this, eventName.str());

	debug("Starting syslog relay");
	this->connect();
	try {
		this->startService(AMSVC_SYSLOG_RELAY, &this->syslogRelayInfo->connection);
	} catch (...) {
		delete this->syslogRelayInfo;
		this->syslogRelayInfo = NULL;
		this->disconnect();
		throw;
	}
	this->disconnect();

	CFSocketContext socketCtx = { 0, this->syslogRelayInfo, NULL, NULL, NULL };

	debug("Creating socket to syslog service");
	this->syslogRelayInfo->socket = ::CFSocketCreateWithNative(kCFAllocatorDefault, this->syslogRelayInfo->connection, kCFSocketDataCallBack, &Device::syslogRelaySocketCallback, &socketCtx);
	if (!this->syslogRelayInfo->socket) {
		delete this->syslogRelayInfo;
		this->syslogRelayInfo = NULL;
		throw std::runtime_error("Failed to create socket");
	}

	debug("Creating run loop source");
	this->syslogRelayInfo->source = ::CFSocketCreateRunLoopSource(kCFAllocatorDefault, this->syslogRelayInfo->socket, 0);
	if (!this->syslogRelayInfo->source) {
		delete this->syslogRelayInfo;
		this->syslogRelayInfo = NULL;
		throw std::runtime_error("Failed to create socket run loop source");
	}

	debug("Adding run loop source to run loop");
	::CFRunLoopAddSource(runloop, this->syslogRelayInfo->source, kCFRunLoopCommonModes);
}

/**
 * Stops the syslog relay.
 */
void Device::stopSyslogRelay() {
	if (this->syslogRelayInfo) {
		debug("Stopping syslog relay");
		delete this->syslogRelayInfo;
		this->syslogRelayInfo = NULL;
	} else {
		debug("Syslog connection already stopped");
	}
}

/**
 * Called when there are bytes received from the log relay socket. Each
 * line of output is sent to the main thread so Node can consume it.
 */
void Device::syslogRelaySocketCallback(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) {
	relayLogMessages((LogRelayInfo*)info, (const char*)CFDataGetBytePtr((CFDataRef)data));
}

/**
 * Connects to the device, pairs with it, and starts a session. We use a
 * connected counter so that we don't connect more than once.
 */
void Device::connect() {
	if (this->connected < 0) {
		this->connected = 0;
	}
	if (this->connected++ > 0) {
		debug("Already connected");
		// already connected
		return;
	}

	try {
		// connect to the device
		debug("Connecting to device: %s", this->props["udid"].c_str());
		mach_error_t rval = ::AMDeviceConnect(this->handle);
		if (rval == MDERR_SYSCALL) {
			throw std::runtime_error("Failed to connect to device: setsockopt() failed");
		} else if (rval == MDERR_QUERY_FAILED) {
			throw std::runtime_error("Failed to connect to device: the daemon query failed");
		} else if (rval == MDERR_INVALID_ARGUMENT) {
			throw std::runtime_error("Failed to connect to device: invalid argument, USBMuxConnectByPort returned 0xffffffff");
		} else if (rval != MDERR_OK) {
			std::stringstream error;
			error << "Failed to connect to device (0x" << std::hex << rval << ")";
			throw std::runtime_error(error.str());
		}

		// if we're not paired, go ahead and pair now
		debug("Pairing device: %s", this->props["udid"].c_str());
		if (::AMDeviceIsPaired(this->handle) != 1 && ::AMDevicePair(this->handle) != 1) {
			throw std::runtime_error("Failed to pair device");
		}

		// double check the pairing
		debug("Validating device pairing");
		rval = ::AMDeviceValidatePairing(this->handle);
		if (rval == MDERR_INVALID_ARGUMENT) {
			throw std::runtime_error("Device is not paired: the device is null");
		} else if (rval == MDERR_DICT_NOT_LOADED) {
			throw std::runtime_error("Device is not paired: load_dict() failed");
		} else if (rval != MDERR_OK) {
			std::stringstream error;
			error << "Device is not paired (0x" << std::hex << rval << ")";
			throw std::runtime_error(error.str());
		}

		// start the session
		debug("Starting session: %s", this->props["udid"].c_str());
		rval = ::AMDeviceStartSession(this->handle);
		if (rval == MDERR_INVALID_ARGUMENT) {
			throw std::runtime_error("Failed to start session: the lockdown connection has not been established");
		} else if (rval == MDERR_DICT_NOT_LOADED) {
			throw std::runtime_error("Failed to start session: load_dict() failed");
		} else if (rval != MDERR_OK) {
			std::stringstream error;
			error << "Failed to start session (0x" << std::hex << rval << ")";
			throw std::runtime_error(error.str());
		}
	} catch (std::runtime_error& e) {
		this->disconnect();
		throw;
	}
}

/**
 * Disconnects the device if there are no other active connections to this
 * device. Generally, force should not be set. It's mainly there for the
 * destructor.
 */
void Device::disconnect(const bool force) {
	if (this->connected == 0) {
		debug("Already disconnected");
	} else {
		if (force || this->connected == 1) {
			debug("Stopping session: %s", this->props["udid"].c_str());
			::AMDeviceStopSession(this->handle);
			debug("Disconnecting from device: %s", this->props["udid"].c_str());
			::AMDeviceDisconnect(this->handle);
			this->connected = 0;
		} else {
			this->connected--;
		}
	}
}

/**
 * Starts a service.
 * Note that if the call to AMDeviceStartService() fails, it's probably
 * because MobileDevice thinks we're connected and paired, but we're not.
 */
void Device::startService(const char* serviceName, service_conn_t* conn) {
	debug("Starting \'%s\' service: %s", serviceName, this->props["udid"].c_str());
	mach_error_t rval = ::AMDeviceStartService(this->handle, ::CFStringCreateWithCStringNoCopy(NULL, serviceName, kCFStringEncodingUTF8, NULL), conn, NULL);
	std::stringstream error;
	if (rval == MDERR_SYSCALL) {
		error << "Failed to start \"" << serviceName << "\" service due to system call error (0x" << std::hex << rval << ")";
		throw std::runtime_error(error.str());
	} else if (rval == MDERR_INVALID_ARGUMENT) {
		error << "Failed to start \"" << serviceName << "\" service due to invalid argument (0x" << std::hex << rval << ")";
		throw std::runtime_error(error.str());
	} else if (rval != MDERR_OK) {
		error << "Failed to start \"" << serviceName << "\" service (0x" << std::hex << rval << ")";
		throw std::runtime_error(error.str());
	}
}

/**
 * Sets a property.
 */
void Device::set(const char* key, CFStringRef id) {
	CFStringRef valueStr = (CFStringRef)::AMDeviceCopyValue(this->handle, 0, id);
	if (valueStr != NULL) {
		char* value = cfstring_to_cstr(valueStr);
		::CFRelease(valueStr);
		if (value != NULL) {
			this->props[key] = std::string(value);
			::free(value);
		}
	}
}

} // end namespace node_ios_device


text:
/**
 * Represents a MethodDescriptor. Provides handy comparison functions,
 * and validates the descriptor in its constructor
 */
define(['util/Util', 'vm/FieldDescriptor', 'vm/ReturnDescriptor'],
  function(Util, FieldDescriptor, ReturnDescriptor) {
    "use strict";

    /**
     * Creates the method descriptor object.
     * Also performs verification.
     */
    function MethodDescriptor(descriptor) {
      this._descriptor = descriptor;
      this._parameters = FieldDescriptor.parseFromMethodDescriptor(descriptor);
      this._returnType = new ReturnDescriptor(descriptor.substr(descriptor.indexOf(')')+1));
    }

    /**
     * Returns the string form of this descriptor.
     */
    MethodDescriptor.prototype.toString = function() {
      return this._descriptor;
    };

    return MethodDescriptor;
  }
);


text:
/* This is just an example.  You shouldn't do this. */
#creditcardnanny-hello
{
  color: red ! important;
}
#creditcardnanny-toolbar-button
{
  list-style-image: url("chrome://creditcardnanny/skin/toolbar-button.png");
  -moz-image-region: rect(0px 24px 24px 0px);
}
#creditcardnanny-toolbar-button:hover
{
  -moz-image-region: rect(24px 24px 48px  0px);
}
[iconsize="small"] #creditcardnanny-toolbar-button
{
  -moz-image-region: rect( 0px 40px 16px 24px);
}
[iconsize="small"] #creditcardnanny-toolbar-button:hover
{
  -moz-image-region: rect(24px 40px 40px 24px);
}


text:
The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash's](https://lodash.com/) `_.template` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module.

## Installation

Using npm:

```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash.template
```

In Node.js/io.js:

```js
var template = require('lodash.template');
```

See the [documentation](https://lodash.com/docs#template) or [package source](https://github.com/lodash/lodash/blob/3.6.2-npm-packages/lodash.template) for more details.


text:
var helperCreeps = require('helper.creeps');

var roleMiner = {

    'typeID': 'ferry',
    'typeBuild1': [CARRY, MOVE, WORK]
    'typeBuild2': [CARRY, CARRY, MOVE, MOVE, WORK, WORK],

    /** @param {Creep} creep **/
    run: function(creep) {
        //Information

        //From tutorial
	    if(creep.carry.energy < creep.carryCapacity) {
            var sources = creep.room.find(FIND_SOURCES);
            if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
                creep.moveTo(sources[0], {visualizePathStyle: {stroke: '#ffaa00'}});
            }
        }
        else {
            var targets = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_EXTENSION || structure.structureType == STRUCTURE_SPAWN) &&
                            structure.energy < structure.energyCapacity;
                    }
            });
            if(targets.length > 0) {
                if(creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(targets[0], {visualizePathStyle: {stroke: '#ffffff'}});
                }
            }
            else {
                //creep.say('Idle -_- zz');
                if(Game.flags['IdleFlag'] != null) {
                    creep.moveTo(Game.flags['IdleFlag'].pos, {visualizePathStyle: {stroke: '#ffffff'}});
                }
            }
        }
	}
};

helperCreeps.submitCreepBuild(roleMiner.typeName, roleMiner.typeBuild1, 1);
helperCreeps.submitCreepBuild(roleMiner.typeName, roleMiner.typeBuild2, 2);

module.exports = roleMiner;