text:
#pragma once
#include <aws/devicefarm/DeviceFarm_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace DeviceFarm
{
namespace Model
{

  /**
   *
Represents the amount of CPU that an app is using on a physical device. Does
   * not represent system-wide CPU usage.

See Also:
   AWS API
   * Reference

   */
  class AWS_DEVICEFARM_API CPU
  {
  public:
    CPU();
    CPU(Aws::Utils::Json::JsonView jsonValue);
    CPU& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The CPU's frequency.

     */
    inline const Aws::String& GetFrequency() const{ return m_frequency; }

    /**
     *
The CPU's frequency.

     */
    inline bool FrequencyHasBeenSet() const { return m_frequencyHasBeenSet; }

    /**
     *
The CPU's frequency.

     */
    inline void SetFrequency(const Aws::String& value) { m_frequencyHasBeenSet = true; m_frequency = value; }

    /**
     *
The CPU's frequency.

     */
    inline void SetFrequency(Aws::String&& value) { m_frequencyHasBeenSet = true; m_frequency = std::move(value); }

    /**
     *
The CPU's frequency.

     */
    inline void SetFrequency(const char* value) { m_frequencyHasBeenSet = true; m_frequency.assign(value); }

    /**
     *
The CPU's frequency.

     */
    inline CPU& WithFrequency(const Aws::String& value) { SetFrequency(value); return *this;}

    /**
     *
The CPU's frequency.

     */
    inline CPU& WithFrequency(Aws::String&& value) { SetFrequency(std::move(value)); return *this;}

    /**
     *
The CPU's frequency.

     */
    inline CPU& WithFrequency(const char* value) { SetFrequency(value); return *this;}

    /**
     *
The CPU's architecture (for example, x86 or ARM).

     */
    inline const Aws::String& GetArchitecture() const{ return m_architecture; }

    /**
     *
The CPU's architecture (for example, x86 or ARM).

     */
    inline bool ArchitectureHasBeenSet() const { return m_architectureHasBeenSet; }

    /**
     *
The CPU's architecture (for example, x86 or ARM).

     */
    inline void SetArchitecture(const Aws::String& value) { m_architectureHasBeenSet = true; m_architecture = value; }

    /**
     *
The CPU's architecture (for example, x86 or ARM).

     */
    inline void SetArchitecture(Aws::String&& value) { m_architectureHasBeenSet = true; m_architecture = std::move(value); }

    /**
     *
The CPU's architecture (for example, x86 or ARM).

     */
    inline void SetArchitecture(const char* value) { m_architectureHasBeenSet = true; m_architecture.assign(value); }

    /**
     *
The CPU's architecture (for example, x86 or ARM).

     */
    inline CPU& WithArchitecture(const Aws::String& value) { SetArchitecture(value); return *this;}

    /**
     *
The CPU's architecture (for example, x86 or ARM).

     */
    inline CPU& WithArchitecture(Aws::String&& value) { SetArchitecture(std::move(value)); return *this;}

    /**
     *
The CPU's architecture (for example, x86 or ARM).

     */
    inline CPU& WithArchitecture(const char* value) { SetArchitecture(value); return *this;}

    /**
     *
The clock speed of the device's CPU, expressed in hertz (Hz). For example, a
     * 1.2 GHz CPU is expressed as 1200000000.

     */
    inline double GetClock() const{ return m_clock; }

    /**
     *
The clock speed of the device's CPU, expressed in hertz (Hz). For example, a
     * 1.2 GHz CPU is expressed as 1200000000.

     */
    inline bool ClockHasBeenSet() const { return m_clockHasBeenSet; }

    /**
     *
The clock speed of the device's CPU, expressed in hertz (Hz). For example, a
     * 1.2 GHz CPU is expressed as 1200000000.

     */
    inline void SetClock(double value) { m_clockHasBeenSet = true; m_clock = value; }

    /**
     *
The clock speed of the device's CPU, expressed in hertz (Hz). For example, a
     * 1.2 GHz CPU is expressed as 1200000000.

     */
    inline CPU& WithClock(double value) { SetClock(value); return *this;}

  private:

    Aws::String m_frequency;
    bool m_frequencyHasBeenSet = false;

    Aws::String m_architecture;
    bool m_architectureHasBeenSet = false;

    double m_clock;
    bool m_clockHasBeenSet = false;
  };

} // namespace Model
} // namespace DeviceFarm
} // namespace Aws


text:
<https://inbo.cartodb.com/u/lifewatch/viz/da04f120-ea70-11e4-a3f2-0e853d047bba/public_map>

## SQL

```SQL
SELECT
  t.cartodb_id,
  t.the_geom,
  t.the_geom_webmercator,
  d.species_code
FROM
  lifewatch.bird_tracking AS t
  LEFT JOIN lifewatch.bird_tracking_devices AS d
  ON t.device_info_serial = d.device_info_serial
WHERE
  t.userflag = false
  AND (d.species_code = 'lbbg' OR d.species_code = 'hg')
```

## CartoCSS

```CSS
#bird_tracking{
  marker-fill: #FFF;
  marker-width: 1.5;
  marker-line-color: #FFF;
  marker-line-width: 0;
  marker-line-opacity: 0.5;
  marker-opacity: 0.9;
  marker-comp-op: screen;
  marker-type: ellipse;
  marker-placement: point;
  marker-allow-overlap: true;
  marker-clip: false;
  marker-multi-policy: largest;
}
#bird_tracking[species_code = 'lbbg'] {
  marker-fill: #F29838;
}
#bird_tracking[species_code = 'hg'] {
  marker-fill: #5CA2D1;
}
```

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/SMBCComics.iml" filepath="$PROJECT_DIR$/SMBCComics.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
    </modules>
  </component>
</project>


text: This is  my first journey to github


text:
htseqjni
========

## Motivation

Native java bindings for htseq using samtools/htslib and samtools/htslib

Under developpement.

## Performance ( June 2014)

in `./src/tests/java/htsjdk/samtools/jni/SamReaderFactoryTest.java`

read 5000x samtools/test/mpileup/mpileup.1.bam, print a MD5 hash of each read[name/bases/quality/pos]

```
Native    (jni)      md5=d41d8cd98f00b204e9800998ecf8427e time=28379 msecs
Pure Java (htsjdk)   md5=d41d8cd98f00b204e9800998ecf8427e time=49878 msecs
```

## Author

Pierre Lindenbaum PhD @yokofakun


text:
using System;
using NetOffice;
using NetOffice.Attributes;
namespace NetOffice.ExcelApi.Enums
{
	 /// <summary>
	 /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
	 /// </summary>
	 ///<remarks> MSDN Online Documentation: <see href="https://docs.microsoft.com/en-us/office/vba/api/Excel.XlTextQualifier"/> </remarks>
	[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
	[EntityType(EntityType.IsEnum)]
	public enum XlTextQualifier
	{
		 /// <summary>
		 /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
		 /// </summary>
		 /// <remarks>1</remarks>
		 [SupportByVersion("Excel", 9,10,11,12,14,15,16)]
		 xlTextQualifierDoubleQuote = 1,

		 /// <summary>
		 /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
		 /// </summary>
		 /// <remarks>-4142</remarks>
		 [SupportByVersion("Excel", 9,10,11,12,14,15,16)]
		 xlTextQualifierNone = -4142,

		 /// <summary>
		 /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
		 /// </summary>
		 /// <remarks>2</remarks>
		 [SupportByVersion("Excel", 9,10,11,12,14,15,16)]
		 xlTextQualifierSingleQuote = 2
	}
}


text:
import Network from './network';

export default Network;


text:
using Newtonsoft.Json;

namespace AxosoftAPI.NET.Models
{
	public class SecurityRole : BaseModel
	{
		[JsonProperty("name")]
		public string Name { get; set; }

		[JsonProperty("is_admin")]
		public bool IsAdmin { get; set; }
	}
}


text:
package org.apache.camel.component.ldap;

import java.net.URISyntaxException;
import javax.naming.directory.SearchControls;

import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.impl.DefaultEndpoint;

/**
 * Represents an endpoint that synchronously invokes an LDAP server when a producer sends a message to it.
 */
public class LdapEndpoint extends DefaultEndpoint {
    public static final String SYSTEM_DN = "ou=system";
    public static final String OBJECT_SCOPE = "object";
    public static final String ONELEVEL_SCOPE = "onelevel";
    public static final String SUBTREE_SCOPE = "subtree";

    private String remaining;
    private String base = SYSTEM_DN;
    private String scope = SUBTREE_SCOPE;
    private Integer pageSize;
    private String returnedAttributes;

    protected LdapEndpoint(String endpointUri, String remaining, LdapComponent component) throws URISyntaxException {
        super(endpointUri, component);
        this.remaining = remaining;
    }

    @SuppressWarnings("deprecation")
    public LdapEndpoint(String endpointUri, String remaining) throws URISyntaxException {
        super(endpointUri);
        this.remaining = remaining;
    }

    public Consumer createConsumer(Processor processor) throws Exception {
        throw new RuntimeCamelException("An LDAP Consumer would be the LDAP server itself! No such support here");
    }

    public Producer createProducer() throws Exception {
        return new LdapProducer(this, remaining, base, toSearchControlScope(scope), pageSize, returnedAttributes);
    }

    public boolean isSingleton() {
        return true;
    }

    public String getBase() {
        return base;
    }

    public void setBase(String base) {
        this.base = base;
    }

    public String getScope() {
        return scope;
    }

    public void setScope(String scope) {
        this.scope = scope;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public String getReturnedAttributes() {
        return returnedAttributes;
    }

    public void setReturnedAttributes(String returnedAttributes) {
        this.returnedAttributes = returnedAttributes;
    }

    private int toSearchControlScope(String scope) {
        if (scope.equalsIgnoreCase(OBJECT_SCOPE)) {
            return SearchControls.OBJECT_SCOPE;
        } else if (scope.equalsIgnoreCase(ONELEVEL_SCOPE)) {
            return SearchControls.ONELEVEL_SCOPE;
        } else if (scope.equalsIgnoreCase(SUBTREE_SCOPE)) {
            return SearchControls.SUBTREE_SCOPE;
        } else {
            throw new IllegalArgumentException("Invalid search scope \"" + scope
                + "\" for LdapEndpoint: " + getEndpointUri());
        }
    }
}


text:
using System;
namespace CPTT.SystemFramework
{
	/// <summary>
	/// Classes µÄժҪ˵Ã÷¡£
	/// </summary>
	public class Classes
	{
		private int infoClassNumber;
		private string infoClassName;
		private int classInfoGradeNumber;
		private int infoMachineAddr;
		private string infoClassRemark;
		private string classType;
		public Classes()
		{
			//
			// TODO: ÔÚ´Ë´¦Ìí¼Ó¹¹Ô캯ÊýÂß¼
			//
		}

		public int InfoClassNumber
		{
			get{return this.infoClassNumber;}
			set{this.infoClassNumber = value;}
		}

		public string InfoClassName
		{
			get{return this.infoClassName;}
			set{this.infoClassName = value;}
		}

		public int ClassInfoGradeNumber
		{
			get{return this.classInfoGradeNumber;}
			set{this.classInfoGradeNumber = value;}
		}

		public int InfoMachineAddr
		{
			get{return this.infoMachineAddr;}
			set{this.infoMachineAddr = value;}
		}

		public string InfoClassRemark
		{
			get{return this.infoClassRemark;}
			set{this.infoClassRemark = value;}
		}

		public string ClassType
		{
			get{return this.classType;}
			set{this.classType = value;}
		}
	}
}


text:
/** Example only. Does not work yet */

"use strict";
var fetch = require('node-fetch')
var url = 'https://www.montastic.com/feeds/quick_status?key=' + {{api_key}};
var count = 0;
fetch(url)
    .then(function (res) {
        return res.text();
    }).then(function (data) {
        console.log('data from fetch: ' + data);
        if (data > 0) {
            console.log('Montastic alarms: ' + data);
        } else {
            console.log('OK');
        }
        console.log(data);
    });


text:
title:  "10 Fatores de Design que influenciam na credibilidade de um site"
date:   2015-11-01 11:05:00
description: Estudo realizado pela Stanford Persuasive Technology Lab
image: homem-na-lua.jpg
tags: [ux, design]
---

![Imagem de astronauta na lua](../../assets/images/homem-na-lua.jpg)

Os websites tem nos dias atuais uma importância absurda dentro de uma estratégia de negócios de uma empresa. Através deles podem ser fornecidos serviços, produtos, divulgação de eventos, servir como intermediário entre relações interpessoais, dentre milhares de outras coisas.

Mas você já parou pra pensar, por que dentre milhares de sites de determinado segmento, você sempre tem uma pequena lista, contendo um, dois ou três sites, cujo conteúdo é presumivelmente confiável?

Agora que você concordou comigo, pense como essa lista pessoal foi montada? Foi algo intencional ou de uma hora pra outra, você se via dentro desses sites, pesquisando e consumindo seu conteúdo?

A Universidade de Stanford, tem um grupo que estuda os fatores que influenciam os usuários na hora de dizer se determinado site tem credibilidade ou não. Eles levantaram questões como:

* O que leva as pessoas a acreditarem se a fonte daquela informação é confiável?
* Quais estratégias utilizadas por usuários pra avaliar credibilidade em fontes online?
* Qual o contexto e os fatores de design que influenciam nisso?
* Como e por que o processo de avaliação de credibilidade na web, é diferente do processo de avaliação utilizada no contexto offline, na interação face a face entre as pessoas?

O estudo revelou que elementos visuais, podem influenciar para o bem e para o mal, os visitantes e suas avaliações pertinentes à credibilidade daquele site.

Por causa disso, eles desenvolveram uma lista com **10 fatores de design que influenciam na credibilidade de um site**. Essas guidelines foram baseadas em três anos de pesquisa com mais de 4.500 pessoas.

### 1 - Deixe de fácil acesso as verificações de informações do seu site.

Você pode construir a credibilidade de seu site, oferecendo formas (citações, referências, materiais) de comprovar que aquela informação é de confiança. Mesmo se ninguém acessar esse material de apoio, isso já faz com que seu site seja bem visto.

### 2 - Mostre que existe uma organização real por trás daquela interface digital.

Mostre que sua organização é legítima e real. A maneira mais fácil, é você possuir um endereço físico.

### 3 - Destaque a *expertise* da sua organização nos produtos e serviços oferecidos.

Deixe clara a qualidade do serviço ou produto oferecido.  Cerque-se de pessoas capacitadas e de credibilidade. Não indique sites externos que não são confiáveis.

### 4 - Mostre que há pessoas honestas e honradas comandando aquela organização real.

Descubra uma forma de passar para as pessoas que as pessoas por trás daquele produto são pessoas reais e confiáveis. Forneça meios de identificar os responsáveis pelo conteúdo.

### 5 - Ofereça formas simples e eficientes de ser contatado.

Números de telefone, endereço físico, endereço de e-mail, redes sociais, área de suporte, reclamação...

### 6 - O design do seu site deve ser profissional.

As pessoas avaliam seu site primeiro pelo design. Invista em um layout profissional.

### 7 - Faça com que seu site seja útil e de boa usabilidade.

Forneça um produto ou serviço realmente útil e que seja simples de utilizar. Seja único para seu cliente/ usuário.

### 8 - Mantenha seu conteúdo constantemente atualizado.

Conteúdo constantemente atualizado e revisado, causa sempre boa impressão. Mas cuidado para não sufocar as pessoas com informação em excesso.

### 9 - Seja cauteloso com conteúdos promocionais.

Se possível evite <i>ads</i> no seu site. Se tiver, cuide para que ele forneça algo realmente útil e voltado para o público do seu site. Cuidado para não sobrecarregar visualmente e sobrepujar o conteúdo.

### 10 - Elimine erros de todos os tipos, por menor que pareçam.

Erros ortográficos e links quebrados, são alguns dos principais fatores que ferem a credibilidade do seu site. Elimine-os.

Fonte: [Stanford Guidelines][Stanford]

[Stanford]:http://credibility.stanford.edu/guidelines/index.html


text:
<?php
namespace gossi\propel\behavior\l10n;

use Propel\Generator\Behavior\I18n\I18nBehavior;

class L10nBehavior extends I18nBehavior {

	// default parameters value
	protected $parameters = [
		'i18n_table'        => '%TABLE%_i18n',
		'i18n_phpname'      => '%PHPNAME%I18n',
		'i18n_columns'      => '',
		'i18n_pk_column'    => null,
		'locale_column'     => 'locale',
		'locale_length'     => 76,
		'locale_alias'      => '',
	];

	protected $templateDirnameBackup;

	public function __construct() {
		parent::__construct();

		$r = new \ReflectionObject(new I18nBehavior());
		$this->dirname = dirname($r->getFileName());
	}

	public function modifyDatabase() {
		// override parent behavior... but do nothing
	}

	public function staticAttributes($builder) {
		// override parent behavior... but do nothing
	}

	public function getDefaultLocale() {
		return PropelL10n::getLocale();
	}

	public function getObjectBuilderModifier() {
		if (null === $this->objectBuilderModifier) {
			$this->objectBuilderModifier = new L10nBehaviorObjectBuilderModifier($this);
		}

		return $this->objectBuilderModifier;
	}

	public function getQueryBuilderModifier() {
		if (null === $this->queryBuilderModifier) {
			$this->queryBuilderModifier = new L10nBehaviorQueryBuilderModifier($this);
		}

		return $this->queryBuilderModifier;
	}

	public function backupTemplatesDirname() {
		$this->templateDirnameBackup = $this->dirname;

		$r = new \ReflectionObject($this);
		$this->dirname = dirname($r->getFileName());
	}

	public function restoreTemplatesDirname() {
		$this->dirname = $this->templateDirnameBackup;
	}

}


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title></title>
    <link rel="Stylesheet" href="../css/analysis.css" />

Créer des zones tampon

Une zone tampon est une surface qui couvre une distance donnée à partir d'une entité ponctuelle, linéaire ou surfacique.

Les zones tampon sont généralement utilisées pour créer des surfaces qui peuvent faire l'objet d'analyses plus approfondies à l'aide d'un outil, tel que Superposer les couches. Par exemple, si vous vous posez la question suivante : "Quels sont les bâtiments qui se trouvent à moins d'un kilomètre de l'école ?", vous pouvez obtenir la réponse en créant une zone tampon d'un kilomètre autour de l'école et en utilisant l'outil Superposer les couches pour superposer la zone tampon avec la couche contenant les emprises de bâtiments. Le résultat final est une couche des bâtiments qui se trouvent à moins d'un kilomètre de l'école.

Si l'option  Utiliser l'étendue courante de la carte est sélectionnée, seules les entités qui sont visibles au sein de l'étendue courante de la carte seront bufférisées.  Si l'option n'est pas sélectionnée, toutes les entités qui se trouvent dans la couche en entrée seront bufférisées, même si elles se trouvent en dehors de l'étendue courante de la carte.

Choisissez la couche contenant des entités à buffériser

Entités ponctuelles, linéaires ou surfaciques à buffériser.

En plus de choisir une couche de votre carte, vous pouvez sélectionner  Choisir une couche d'analyse d'atlas dynamique ou Choisir une couche d'analyse au bas de la liste déroulante. Cette opération ouvre une bibliothèque de couches utiles pour de nombreuses analyses.

Entrer la taille de la zone tampon

Vous pouvez entrer une seule distance ou plusieurs valeurs en séparant chaque valeur par un espace. Vous pouvez également spécifier un attribut sur la couche en entrée qui contient la distance en cliquant sur  Champ.

Options

Choisissez la manière dont les zones tampon superposées doivent être gérées. Pour les zones tampon qui se trouvent par dessus une autre, les surfaces en commun peuvent être conservées (Superposition) ou combinées (Fusion).

 Si vous utilisez plusieurs distances, vous pouvez choisir le mode de représentation de la distance à partir de la dernière distance de la zone tampon. Par exemple, si les distances sont de 10 et 14 :

Choisissez  Anneaux pour obtenir des zones tampon allant de 0 à 10 et de 10 à 14.

Choisissez  Disques pour obtenir des zones tampon allant de 0 à 10 et de 0 à 14.

Options

Choisissez la manière dont les zones tampon superposées doivent être gérées. Pour les zones tampon qui se trouvent par dessus une autre, les surfaces en commun peuvent être conservées (Superposition) ou combinées (Fusion).

Lorsque vous créez une seule zone tampon autour d'entités surfaciques (une distance entrée), vous pouvez choisir si l'entité qui est bufférisée est incluse ou exclue de la zone tampon obtenue.

Si vous utilisez plusieurs distances, vous pouvez choisir le mode de représentation de la distance à partir de la dernière distance de la zone tampon. Par exemple, si les distances sont de 10 et 14 :

Choisissez  Anneaux pour obtenir des zones tampon allant de 0 à 10 et de 10 à 14.

Choisissez  Disques pour obtenir des zones tampon allant de 0 à 10 et de 0 à 14.

Options

Choisissez la manière dont les zones tampon superposées doivent être gérées. Pour les zones tampon qui se trouvent par dessus une autre, les surfaces en commun peuvent être conservées (Superposition) ou combinées (Fusion).

Lorsque vous créez une seule zone tampon autour de lignes (une distance entrée), vous pouvez choisir le côté de la ligne à buffériser. En général, vous choisissez les deux côtés. La gauche et la droite sont déterminées si vous alliez de la première coordonnée x,y de la ligne (la coordonnée de départ) vers la dernière coordonnée x,y de la ligne (la coordonnée de fin). Vous choisissez généralement la gauche ou la droite lorsque vous savez que les entités linéaires ont été créées et stockées dans une direction particulière (par exemple, en amont ou en aval dans un réseau de rivière). Aux extrémités des lignes, la zone tampon peut être arrondie (Arrondi) ou toute droite (Plate).

Si vous créez plusieurs zones tampon (plusieurs distances), vous pouvez choisir le mode de représentation de la distance à partir de la dernière distance de la zone tampon. Par exemple, si les distances sont de 10 et 14 :

Choisissez  Anneaux pour obtenir des zones tampon allant de 0 à 10 et de 10 à 14.

Choisissez  Disques pour obtenir des zones tampon allant de 0 à 10 et de 0 à 14.

Options

Une fois la couche à buffériser choisie, vous pouvez indiquer le mode de gestion des zones tampon superposées. Pour les zones tampon qui se trouvent par dessus une autre, les surfaces en commun peuvent être conservées (Superposition) ou combinées (Fusion). Vous pouvez en outre spécifier comment représenter plusieurs distances.   Pour les couches qui contiennent des entités linéaires, vous pouvez choisir le côté de la ligne à buffériser.  Pour les couches qui contiennent des entités surfaciques, vous pouvez choisir si l'entité qui est bufférisée est incluse ou exclue de la zone tampon obtenue.

Nom de la couche résultat

Il s'agit du nom de la couche qui sera créée dans la page  Mon contenu et ajoutée à la carte.  Le nom par défaut repose sur le nom de l'outil et sur le nom de la couche en entrée. Si la couche existe déjà, vous êtes invité à fournir un autre nom.

La zone de liste déroulante  Enregistrer le résultat dans vous permet de spécifier le nom d'un dossier dans Mon contenu où le résultat sera enregistré.


text:
from __future__ import division
import kivy
kivy.require("1.8.0")
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.app import App
from kivy.properties import NumericProperty
from kivy.properties import ObjectProperty
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ReferenceListProperty
from kivy.core.window import Window
from kivy.animation import Animation
from math import fabs, sqrt
import random as rand
import time

def magnitude(x1, y1, x2, y2):
	return sqrt((x2-x1)**2+(y2-y1)**2)

class SwoopAndZoom(Animation):
	def __init__(self, **kwargs):
		super(SwoopAndZoom, self).__init__(**kwargs)
		self.i = 0
		self.j = 0
		self.bs = 0

	def on_complete(self, Widget):
		Widget.x = self.j*(Window.width//self.bs)+(Window.width//self.bs)//2
		Widget.y = Window.height-(self.i+1)*(Window.height//self.bs)
		print Widget.color
		Widget.color = Widget.color[:3]+[0.0]

	def set_ij_bs(self, t, bs):
		self.i = t[0]
		self.j = t[1]
		self.bs = bs

class MeWidget(Widget):
	def __init__(self, **kwargs):
		super(MeWidget, self).__init__(**kwargs)

		# change this variable to change the number that makes you lose.
		self.nonum = 5

		# bs is boardsize
		self.bs = 4
		self.board = {}

		self.hidden_board = {(i//self.bs, i%self.bs):0 for i in range(self.bs**2)}
		self.hidden_board[(rand.randint(1,self.bs-2),rand.randint(1,self.bs-2))] = 1

		self.score = 0
		self.highscore = 0
		self.score_board = Label(text="Score: "+str(self.score)+" Highscore: "+str(self.highscore), font_size='24sp', x=Window.width//2, y=Window.height-100)
		self.score_board.x -= self.score_board.width//2
		self.add_widget(self.score_board)

		self._keyboard = Window.request_keyboard(self._keyboard_closed,self,'text')
		self._keyboard.bind(on_key_down=self._on_keyboard_down)

		#self.layout = GridLayout(rows=bs, cols=bs, col_default_width=Window.width//bs, row_default_height=Window.height//bs)
		for i in range(self.bs):
			for j in range(self.bs):
				self.board[(i, j)] = Label(color=(1,1, 1, 1),text=str(self.hidden_board[(i,j)]), font_size='40sp',\
					x=j*(Window.width//(self.bs+1))+(Window.width//(self.bs+1))//2, y=Window.height-(i+1)*(Window.height//(self.bs+1)))
				self.add_widget(self.board[(i,j)])

	def on_touch_down(self, touch):
		self.oldx = touch.x
		self.oldy = touch.y

	def on_touch_up(self, touch):
		mag = magnitude(self.oldx, self.oldy, touch.x, touch.y)
		dx = self.oldx - touch.x
		dy = self.oldy - touch.y

		if self.check_lose():
			self.reset()
		#change the number below to change the sensitivity of the swipe.
		elif mag > 20:
			if fabs(dx)>fabs(dy):
				if dx < 0:
					self.move_right()
				else:
					self.move_left()
			else:
				if dy < 0:
					self.move_up()
				else:
					self.move_down()

	def one_plus_score(self):
		self.score += 1
		self.score_board.text = "Score: " + str(self.score) +" Highscore: "+str(self.highscore)

	def score_reset(self):
		if self.highscore < self.score:
			self.highscore = self.score
		self.score = 0
		self.score_board.text = "Score: " + str(self.score) +" Highscore: "+str(self.highscore)

	def _keyboard_closed(self):
		print 'My keyboard have been closed!'
		self._keyboard.unbind(on_key_down=self._on_keyboard_down)
		self._keyboard = None

		#self.add_widget(self.layout)
	def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
		if self.check_lose() or keycode[1] == "r":
			self.reset()
		elif keycode[1] == "up":
			self.move_up()
			return True
		elif keycode[1] == "down":
			self.move_down()
			return True
		elif keycode[1] == "left":
			self.move_left()
			return True
		elif keycode[1] == "right":
			self.move_right()
			return True
		# Return True to accept the key. Otherwise, it will be used by
		# the system.
		return False

	def move_right(self):
		for i in range(self.bs):
			for j in range(self.bs)[::-1]:
				if self.hidden_board[(i,j)] != 0:
					if j +1 < self.bs:
						self.hidden_board[(i,j+1)] += self.hidden_board[(i,j)]
						self.hidden_board[(i,j)] = 1
		self.redraw_board()
		if self.check_lose():
			self.colour_wrong()
		else:
			self.one_plus_score()

	def on_complete_saz (t):
		self.board[t].x = t[1]*(Window.width//bs)+(Window.width//bs)//2
		self.board[t].y = Window.height-(t[0]+1)*(Window.height//bs)

	def move_left(self):
		# swoopandzoom = {}
		for i in range(self.bs):
			for j in range(self.bs):
				if self.hidden_board[(i,j)] != 0:
					if j - 1 >= 0:
						# swoopandzoom[(i,j)] = [SwoopAndZoom(x=(j-1)*(Window.width//self.bs)+(Window.width//self.bs)//2), self.board[(i,j)]]
						# swoopandzoom[(i,j)][0].set_ij_bs((i, j),self.bs)
						self.hidden_board[(i,j-1)] += self.hidden_board[(i,j)]
						self.hidden_board[(i,j)] = 1

		# for k in swoopandzoom:
		# 	swoopandzoom[k][0].start(swoopandzoom[k][1])
		# 	reset_alpha = Animation(color=swoopandzoom[k][1].color[:3]+[1.0])
		# 	reset_alpha.start(swoopandzoom[k][1])

		self.redraw_board()
		if self.check_lose():
			self.colour_wrong()
		else:
			self.one_plus_score()

	def move_down(self):
		for i in range(self.bs):
			for j in range(self.bs)[::-1]:
				if self.hidden_board[(j, i)] != 0:
					if j +1 < self.bs:
						self.hidden_board[(j+1, i)] += self.hidden_board[(j, i)]
						self.hidden_board[(j, i)] = 1
		self.redraw_board()
		if self.check_lose():
			self.colour_wrong()
		else:
			self.one_plus_score()

	def move_up(self):
		for i in range(self.bs):
			for j in range(self.bs):
				if self.hidden_board[(j,i)] != 0:
					if j - 1 >= 0:
						self.hidden_board[(j-1, i)] += self.hidden_board[(j,i)]
						self.hidden_board[(j, i)] = 1
		self.redraw_board()
		if self.check_lose():
			self.colour_wrong()
		else:
			self.one_plus_score()

	def check_lose(self):
		for i in range(self.bs):
			for j in range(self.bs):
				if self.hidden_board[(i, j)] % self.nonum == 0 and self.hidden_board[(i, j)] != 0:
					return True
		return False

	def redraw_board(self):
		for k in self.board:
			if self.hidden_board[k] != 0:
				self.board[k].color = (0.0, 1.0, 0.0, 1.0)
			self.board[k].text = str(self.hidden_board[k])

	def colour_wrong(self):
		for k in self.hidden_board:
			if self.hidden_board[k]%5 == 0 and self.hidden_board[k] != 0:
				self.board[k].color = (1.0, 0.0, 0.0, 1.0)

	def reset(self):
		for k in self.hidden_board:
			self.hidden_board[k] = 0
			self.board[k].text = '0'
			self.board[k].color = (1.0, 1.0, 1.0, 1.0)
		a = rand.randint(1,self.bs-2)
		b = rand.randint(1,self.bs-2)
		self.hidden_board[(a,b)] = 1
		self.board[(a,b)].text = '1'
		self.board[(a,b)].color = (0.0, 1.0, 0.0, 1.0)
		self.score_reset()

class MeApp(App):
	def build(self):
		return MeWidget()

if __name__ == '__main__':
	MeApp().run()


text:
package org.durid.sql.ast.statement;

import org.durid.sql.ast.SQLExpr;
import org.durid.sql.visitor.SQLASTVisitor;

public class SQLExprTableSource extends SQLTableSourceImpl {

    private static final long serialVersionUID = 1L;

    protected SQLExpr         expr;
	private String tablename;

	public SQLExprTableSource(){

    }

    public SQLExprTableSource(SQLExpr expr){
        this.expr = expr;
		this.tablename = expr.toString().replace(" ", "");
    }

	public SQLExprTableSource(String tablename){
		this.tablename = tablename;
	}

    public SQLExpr getExpr() {
        return this.expr;
    }

    public void setExpr(SQLExpr expr) {
        this.expr = expr;
		this.tablename = expr.toString().replace(" ", "");
    }

    @Override
    protected void accept0(SQLASTVisitor visitor) {
        if (visitor.visit(this)) {
            acceptChild(visitor, this.expr);
        }
        visitor.endVisit(this);
    }

    public void output(StringBuffer buf) {
        this.expr.output(buf);
    }

	@Override
	public String getTablename() {
		return this.tablename;
	}
}


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.0">
        <meta name="description" content="">
        <meta name="author" content="">
        <title>Flights</title>

                        Flight Planner

Info

Create route

Report

User

New Plane

Log In

Registration

Log Out

            	<wicket:child />

Flight planner by Robert Balent.


text:
package dry

import (
	"os"
	"strings"
)

// EnvironMap returns the current environment variables as a map.
func EnvironMap() map[string]string {
	return environToMap(os.Environ())
}

func environToMap(environ []string) map[string]string {
	ret := make(map[string]string)

	for _, v := range environ {
		parts := strings.SplitN(v, "=", 2)

		ret[parts[0]] = parts[1]
	}

	return ret
}

// GetenvDefault retrieves the value of the environment variable
// named by the key. It returns the given defaultValue if the
// variable is not present.
func GetenvDefault(key, defaultValue string) string {
	ret := os.Getenv(key)
	if ret == "" {
		return defaultValue
	}

	return ret
}


text:
Register Now!

Schedule

Speakers

Sessions

Sponsors

Venue

Contact


text:
require "chef/version_class"

class Cookbook < ApplicationRecord
  include PgSearch::Model
  include Badgeable
  extend Badgeable::ClassMethods

  #
  # Query cookbooks by case-insensitive name.
  #
  # @param name [String, Array<String>] a single name, or a collection of names
  #
  # @example
  #   Cookbook.with_name('redis').first
  #     #<Cookbook name: "redis"...>
  #   Cookbook.with_name(['redis', 'apache2']).to_a
  #     [#<Cookbook name: "redis"...>, #<Cookbook name: "apache2"...>]
  #
  # @todo: query and index by +LOWER(name)+ when ruby schema dumps support such
  #   a thing.
  #
  scope :with_name, lambda { |names|
    lowercase_names = Array(names).map { |name| name.to_s.downcase }

    where(lowercase_name: lowercase_names)
  }

  ORDER_OPTIONS = {
    "recently_updated" => Arel.sql("cookbooks.updated_at DESC"),
    "recently_added" => Arel.sql("cookbooks.id DESC"),
    "most_downloaded" => Arel.sql("(cookbooks.web_download_count + cookbooks.api_download_count) DESC, cookbooks.id ASC"),
    "most_followed" => Arel.sql("cookbook_followers_count DESC, cookbooks.id ASC"),
    "by_name" => Arel.sql("cookbooks.name ASC"),
  }.freeze

  scope :ordered_by, lambda { |option|
    ordering = ORDER_OPTIONS.fetch(option, ORDER_OPTIONS["by_name"] )
    reorder(ordering)
  }

  scope :order_by_latest_upload_date, lambda {
    joins(:cookbook_versions)
      .select("cookbooks.*", "MAX(cookbook_versions.created_at) AS latest_upload")
      .group("cookbooks.id")
      .order("latest_upload DESC")
  }

  scope :owned_by, lambda { |username|
    joins(owner: :chef_account).where("accounts.username = ?", username)
  }

  scope :paginated_with_owner_and_versions, lambda { |opts = {}|
    includes(:cookbook_versions, owner: :chef_account)
      .ordered_by(opts.fetch(:order, "name ASC"))
      .limit(opts.fetch(:limit, 10))
      .offset(opts.fetch(:start, 0))
  }

  scope :featured, -> { where(featured: true) }

  scope :filter_platforms, lambda { |platforms|
    joins(cookbook_versions: :supported_platforms)
      .where("supported_platforms.name IN (?)", platforms).distinct
      .select("cookbooks.*", "(cookbooks.web_download_count + cookbooks.api_download_count)")
  }

  scope :filter_badges, lambda { |badges|
    with_badges badges
  }

  # Search
  # --------------------
  pg_search_scope(
    :search,
    against: {
      name: "A",
    },
    associated_against: {
      chef_account: { username: "B" },
      cookbook_versions: { description: "C" },
    },
    using: {
      tsearch: { dictionary: "english", only: [:username, :description], prefix: true },
      trigram: { only: [:name] },
    },
    ranked_by: ":trigram + (0.5 * :tsearch)",
    order_within_rank: "cookbooks.name"
  )

  # Callbacks
  # --------------------
  before_validation :copy_name_to_lowercase_name

  # Associations
  # --------------------
  has_many :cookbook_versions, dependent: :destroy
  has_many :cookbook_followers # rubocop:disable Rails/HasManyOrHasOneDependent
  has_many :followers, through: :cookbook_followers, source: :user
  belongs_to :category, optional: true
  belongs_to :owner, class_name: "User", foreign_key: :user_id, inverse_of: :owned_cookbooks
  has_one :chef_account, through: :owner
  belongs_to :replacement, class_name: "Cookbook", inverse_of: :replaces, optional: true
  has_many :replaces, class_name: "Cookbook", foreign_key: :replacement_id, inverse_of: :replacement, dependent: :nullify
  has_many :collaborators, as: :resourceable, inverse_of: :resourceable # rubocop:disable Rails/HasManyOrHasOneDependent
  has_many :collaborator_users, through: :collaborators, source: :user
  has_many :direct_collaborators, -> { where(group_id: nil) }, as: :resourceable, class_name: "Collaborator", inverse_of: :resourceable
  has_many :direct_collaborator_users, through: :direct_collaborators, source: :user
  has_many :group_resources, as: :resourceable, inverse_of: :resourceable, dependent: :destroy

  # Delegations
  # --------------------
  delegate :description, to: :latest_cookbook_version
  delegate :supported_platforms, to: :latest_cookbook_version
  delegate :cookbook_dependencies, to: :latest_cookbook_version

  # Validations
  # --------------------
  validates :name, presence: true, uniqueness: { case_sensitive: false }, format: /\A[\w_-]+\z/i # rubocop:disable Rails/UniqueValidationWithoutIndex
  validates :lowercase_name, presence: true, uniqueness: true
  validates :cookbook_versions, presence: true
  validates :source_url, url: { allow_blank: true }
  validates :issues_url, url: { allow_blank: true }

  #
  # The total number of times a cookbook has been downloaded from Supermarket
  #
  # @return [Fixnum]
  #
  def self.total_download_count
    sum(:api_download_count) + sum(:web_download_count)
  end

  #
  # Sorts cookbook versions according to their semantic version
  #
  # @return [Array<CookbookVersion>] the sorted CookbookVersion records
  #
  def sorted_cookbook_versions
    @sorted_cookbook_versions ||= cookbook_versions.sort_by { |v| Chef::Version.new(v.version) }.reverse
  end

  #
  # Transfers ownership of this cookbook to someone else. If the user id passed
  # in represents someone that is already a collaborator on this cookbook, or
  # if the User initiating this transfer is an admin, then we just assign the
  # new owner and move on. If they're not already a collaborator, then we send
  # them an email asking if they want ownership of this cookbook. This
  # prevents abuse of people assigning random owners without getting permission.
  #
  # @param initiator [User] the User initiating the transfer
  # @param recipient [User] the User to assign ownership to
  #
  # @return [String] a key representing a message to display to the user
  #

  def transfer_ownership(initiator, recipient, add_owner_as_collaborator = false)
    original_owner = owner

    if initiator.is?(:admin) || collaborator_users.include?(recipient)
      update(user_id: recipient.id)

      if add_owner_as_collaborator
        create_new_collaborator(original_owner)
      end

      delete_old_collaborator(recipient)
      "cookbook.ownership_transfer.done"
    else
      transfer_request = OwnershipTransferRequest.create(
        sender: initiator,
        recipient: recipient,
        add_owner_as_collaborator: add_owner_as_collaborator,
        cookbook: self
      )
      CookbookMailer.delay.transfer_ownership_email(transfer_request)
      "cookbook.ownership_transfer.email_sent"
    end
  end

  #
  # The most recent CookbookVersion, based on the semantic version number
  #
  # @return [CookbookVersion] the most recent CookbookVersion
  #
  def latest_cookbook_version
    @latest_cookbook_version ||= sorted_cookbook_versions.first
  end

  #
  # Return all of the cookbook errors as well as full error messages for any of
  # the CookbookVersions
  #
  # @return [Array<String>] all the error messages
  #
  def seriously_all_of_the_errors
    messages = errors.full_messages.reject { |e| e == "Cookbook versions is invalid" }

    cookbook_versions.each do |version|
      almost_everything = version.errors.full_messages.reject { |x| x =~ /Tarball can not be/ }
      messages += almost_everything
    end

    messages
  end

  #
  # Returns the name of the +Cookbook+ parameterized.
  #
  # @return [String] the name of the +Cookbook+ parameterized
  #
  def to_param
    name.parameterize
  end

  #
  # Return the specified +CookbookVersion+. Raises an
  # +ActiveRecord::RecordNotFound+ if the version does not exist. Versions can
  # be specified with either underscores or dots.
  #
  # @example
  #   cookbook.get_version!("1_0_0")
  #   cookbook.get_version!("1.0.0")
  #   cookbook.get_version!("latest")
  #
  # @param version [String] the version of the Cookbook to find. Pass in
  #                         'latest' to return the latest version of the
  #                         cookbook.
  #
  # @return [CookbookVersion] the +CookbookVersion+ with the version specified
  #
  def get_version!(version)
    version.tr!("_", ".")

    if version == "latest"
      latest_cookbook_version
    else
      cookbook_versions.find_by!(version: version)
    end
  end

  #
  # Saves a new version of the cookbook as specified by the given metadata, tarball
  # and readme. If it's a new cookbook the user specified becomes the owner.
  #
  # @raise [ActiveRecord::RecordInvalid] if the new version fails validation
  # @raise [ActiveRecord::RecordNotUnique] if the new version is a duplicate of
  #   an existing version for this cookbook
  #
  # @return [CookbookVersion] the Cookbook Version that was published
  #
  # @param params [CookbookUpload::Parameters] the upload parameters
  #
  def publish_version!(params, user)
    metadata = params.metadata

    if metadata.privacy &&
       ENV["ENFORCE_PRIVACY"].present? &&
       ENV["ENFORCE_PRIVACY"] == "true"
      errors.add(:base, I18n.t("api.error_messages.privacy_violation"))
      raise ActiveRecord::RecordInvalid.new(self)
    end

    tarball = params.tarball
    readme = params.readme
    changelog = params.changelog

    dependency_names = metadata.dependencies.keys
    existing_cookbooks = Cookbook.with_name(dependency_names)

    cookbook_version = nil

    transaction do
      cookbook_version = cookbook_versions.build(
        cookbook: self,
        user: user,
        description: metadata.description,
        license: metadata.license,
        version: metadata.version,
        tarball: tarball,
        readme: readme.contents,
        readme_extension: readme.extension,
        changelog: changelog.contents,
        changelog_extension: changelog.extension,
        chef_versions: metadata.chef_versions,
        ohai_versions: metadata.ohai_versions
      )

      self.updated_at = Time.current

      [:source_url, :issues_url].each do |url|
        url_val = metadata.send(url)

        if url_val.present?
          self[url] = url_val
        end
      end

      self.privacy = metadata.privacy
      save!

      metadata.platforms.each do |name, version_constraint|
        cookbook_version.add_supported_platform(name, version_constraint)
      end

      metadata.dependencies.each do |name, version_constraint|
        cookbook_version.cookbook_dependencies.create!(
          name: name,
          version_constraint: version_constraint,
          cookbook: existing_cookbooks.find { |c| c.name == name }
        )
      end
    end

    cookbook_version
  end

  #
  # Returns true if the user passed follows the cookbook.
  #
  # @return [TrueClass]
  #
  # @param user [User]
  #
  def followed_by?(user)
    cookbook_followers.where(user: user).any?
  end

  #
  # Returns all of the CookbookDependency records that are contingent upon this one.
  #
  # @return [Array<CookbookDependency>]
  #
  def contingents
    CookbookDependency
      .includes(cookbook_version: :cookbook)
      .where(cookbook_id: id)
      .sort_by do |cd|
        [
          cd.cookbook_version.cookbook.name,
          Chef::Version.new(cd.cookbook_version.version),
        ]
      end
  end

  #
  # The username of this cookbook's owner
  #
  # @return [String]
  #
  def maintainer
    owner.username
  end

  #
  # The total number of times this cookbook has been downloaded
  #
  # @return [Fixnum]
  #
  def download_count
    web_download_count + api_download_count
  end

  #
  # Sets the cookbook's deprecated attribute to true, assigns the replacement
  # cookbook if specified and saves the cookbook.
  #
  # A cookbook can only be replaced with a cookbook that is not deprecated.
  #
  # @param replacement_cookbook_name [String] the name of the cookbook to
  #   succeed this cookbook once deprecated
  #
  # @return [Boolean] whether or not the cookbook was successfully deprecated
  #   and  saved
  #
  def deprecate(replacement_cookbook_name = "")
    replacement_cookbook = Cookbook.find_by name: replacement_cookbook_name

    if replacement_cookbook.present? && replacement_cookbook.deprecated?
      errors.add(:base, I18n.t("cookbook.deprecate_with_deprecated_failure"))
      return false
    end

    self.deprecated = true
    self.replacement = replacement_cookbook if replacement_cookbook.present?
    save
  end

  #
  # Searches for cookbooks based on the +query+ parameter. Returns results that
  # are elgible for deprecation (not deprecated and not this cookbook).
  #
  # @param query [String] the search term
  #
  # @return [Array<Cookbook> the +Cookbook+ search results
  #
  def deprecate_search(query)
    Cookbook.search(query).where(deprecated: false).where.not(id: id)
  end

  private

  #
  # Populates the +lowercase_name+ attribute with the lowercase +name+
  #
  # This exists until Rails schema dumping supports Posgres's expression
  # indices, which would allow us to create an index on LOWER(name). To do that
  # now, we'd have to use the raw SQL schema dumping functionality, which is
  # less-than ideal
  #
  def copy_name_to_lowercase_name
    self.lowercase_name = name.to_s.downcase
  end

  def create_new_collaborator(initiator)
    collaborators.find_or_create_by!(user_id: initiator.id)
  end

  def delete_old_collaborator(user)
    if collaborator_users.include?(user)
      collaborator = collaborators.find_by(
        user_id: user.id,
        resourceable: self,
        group_id: nil
      )
      # Do not destroy collaborator is collaborator does not exist
      # OR if the collaborator is associated with a group
      collaborator&.destroy
    end
  end
end


text:
using Castle.DynamicProxy;
using StructureMap.Configuration.DSL.Expressions;
using StructureMap.TypeRules;
using System;

namespace StructureMap.AutoFactory
{
    public static class AutoFactoryExtensions
    {
        private static readonly ProxyGenerator proxyGenerator = new ProxyGenerator();

        public static void CreateFactory<TPluginType>(this CreatePluginFamilyExpression<TPluginType> expression)
            where TPluginType : class
        {
            CreateFactory(expression, new DefaultAutoFactoryConventionProvider());
        }

        public static void CreateFactory<TPluginType>(this CreatePluginFamilyExpression<TPluginType> expression,
            IAutoFactoryConventionProvider conventionProvider)
            where TPluginType : class
        {
            var callback = CreateFactoryCallback<TPluginType>(conventionProvider);

            expression.Use(GetDescription<TPluginType>(), callback);
        }

        public static void CreateFactory<TPluginType, TConventionProvider>(
            this CreatePluginFamilyExpression<TPluginType> expression)
            where TPluginType : class
            where TConventionProvider : IAutoFactoryConventionProvider
        {
            var callback = CreateFactoryCallback<TPluginType, TConventionProvider>();

            expression.Use(GetDescription<TPluginType>(), callback);
        }

        private static string GetDescription<TPluginType>() where TPluginType : class
        {
            return "AutoFactory builder for " + typeof(TPluginType).GetFullName();
        }

        private static Func<IContext, TPluginType> CreateFactoryCallback<TPluginType>(IAutoFactoryConventionProvider conventionProvider)
            where TPluginType : class
        {
            return ctxt =>
            {
                var proxyFactory = new ProxyFactory<TPluginType>(proxyGenerator, ctxt, conventionProvider);

                return proxyFactory.Create();
            };
        }

        private static Func<IContext, TPluginType> CreateFactoryCallback<TPluginType, TConventionProvider>()
            where TPluginType : class
            where TConventionProvider : IAutoFactoryConventionProvider
        {
            return ctxt =>
            {
                var conventionProvider = ctxt.GetInstance<TConventionProvider>();

                var proxyFactory = new ProxyFactory<TPluginType>(proxyGenerator, ctxt, conventionProvider);

                return proxyFactory.Create();
            };
        }
    }
}


text:
Git Smart HTTP Server Rack Implementation

Python clone of [grack](https://github.com/schacon/grack)

## Dependency
```
* git
* gevent
```

## License
See the LICENSE file for the full license text.


text:
package org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher;

import org.apache.hadoop.yarn.api.records.SignalContainerCommand;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;

// This event can be triggered by one of the following flows
// WebUI -> Container
// CLI -> RM -> NM
public class SignalContainersLauncherEvent extends ContainersLauncherEvent{

  private final SignalContainerCommand command;
  public SignalContainersLauncherEvent(Container container,
      SignalContainerCommand command) {
    super(container, ContainersLauncherEventType.SIGNAL_CONTAINER);
    this.command = command;
  }
  public SignalContainerCommand getCommand() {
    return command;
  }
}


text:
global.DOMParser = require("xmldom-alpha").DOMParser;
var xadesjs = require("xadesjs");
global.xadesjs = xadesjs;
var asn1js = require("asn1js");
global.asn1js = asn1js;
var request = require("sync-request");
global.request = request;
var WebCrypto = require("node-webcrypto-ossl");
xadesjs.Application.setEngine("OpenSSL", new WebCrypto());
var tl_create = require("../built/tl-create");
var assert = require("assert");

var fs = require("fs");

describe("EUTL format", function () {

    it("TrustServiceStatusList LoadXML", function () {
        // get static file
        var eutlText = fs.readFileSync("./test/static/eutl.xml", "utf8");

        var eutl = new tl_create.TrustServiceStatusList();
        var xml = new DOMParser().parseFromString(eutlText, "application/xml");
        eutl.LoadXml(xml);
        assert.equal(eutl.SchemaInformation.Pointers.length, 48);
        assert.equal(eutl.SchemaInformation.Pointers[0].X509Certificates.length, 2);
    })

    it("TrustServiceStatusList check signature", function (done) {
        // get static file
        var eutlText = fs.readFileSync("./test/static/eutl.xml", "utf8");

        var eutl = new tl_create.TrustServiceStatusList();
        var xml = new DOMParser().parseFromString(eutlText, "application/xml");
        eutl.LoadXml(xml);

        eutl.CheckSignature()
            .then(function (v) {
                assert.equal(v, true, "Wrong signature");
                done();
            })
            .catch(done);
    });

    it("EU EUTL parse", function () {
        // get static file
        var eutlText = fs.readFileSync("./test/static/eutl.xml", "utf8");

        var eutl = new tl_create.EUTL();
        var tl = eutl.getTrusted(eutlText);
        assert.equal(tl.Certificates.length, 0);
    });

    it("Member-state EUTL parse", function () {
        // get static file
        var eutlText = fs.readFileSync("./test/static/EL-TSL.xml", "utf8");

        var eutl = new tl_create.EUTL();
        var tl = eutl.getTrusted(eutlText);
        assert.equal(tl.Certificates.length, 23);
    });

})


text:
using Android.OS;
using Android.Views;
using Android.Widget;
using MvvmCross.Core.ViewModels;
using MvvmCross.Droid.Support.V4;

namespace Demo.Android.Views
{
    public abstract class BaseFragment<TViewModel> : MvxFragment<TViewModel>
        where TViewModel : class, IMvxViewModel
    {
        protected abstract int FragmentLayoutId { get; }
        protected abstract string ToolbarText { get; }

        TextView _toolbarTextView;

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            base.OnCreateView(inflater, container, savedInstanceState);

            // If your bindings are done in XML rather than codebehind, you need to call this.BindingInflate. If not, call inflater.Inflate instead
            var view = inflater.Inflate(FragmentLayoutId, null);

            _toolbarTextView = Activity.FindViewById<TextView>(Resource.Id.textview_toolbar_title);

            _toolbarTextView.Text = ToolbarText;

            return view;
        }
    }
}


text:
require 'spec_helper'

module RestClient
  describe Client do
    let(:subject) { RestClient::Client.new('http://www.google.com') }

    it 'should make the request', vcr: {cassette_name: 'get-google', allow_unused_http_interactions: false} do
      expect {subject.get('')}.to_not raise_error
    end
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Spin-1/2 system with sublattice particle consevation — QuSpin 0.3.6 documentation</title>
    <link rel="stylesheet" href="../static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../static/classic.css" type="text/css" />

    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />

Navigation

          index

          modules |

QuSpin 0.3.6 documentation »

Spin-1/2 system with sublattice particle consevation

Spin-1/2 system with sublattice particle consevation¶

This example makes use of the user_basis class to define the Hamiltonian

\[H = \sum_{j=0}^{N/2-1} t (\tau^+_{j+1}\tau^-_j + \sigma^+_{j+1}\sigma^-_j + \mathrm{h.c.}) + U \sigma^z_j\tau^z_j\]

where \(\sigma\) and \(\tau\) describe hardcore bosons on the two legs of a ladder geometry. Note that particles cannot be exchanged between the legs of the ladder, which allows to further reduce the Hilbert space dimension using a Hilbert space constraint.

Please consult this post – A tutorial on QuSpin's user_basis – for more detailed explanations on using the user_basis class.

Script¶

download script

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

from __future__ import print_function, division
#
import sys,os
os.environ['KMP_DUPLICATE_LIB_OK']='True' # uncomment this line if omp error occurs on OSX for python 3
os.environ['OMP_NUM_THREADS']='1' # set number of OpenMP threads to run in parallel
os.environ['MKL_NUM_THREADS']='1' # set number of MKL threads to run in parallel
#
quspin_path = os.path.join(os.getcwd(),"../../")
sys.path.insert(0,quspin_path)
###########################################################################
#                            example 15                                   #
#  In this script we demonstrate how to apply the user_basis to           #
#  construct a spin-1/2 model with sublattice particle conservation.      #
###########################################################################
from quspin.operators import hamiltonian
from quspin.basis import spin_basis_1d # Hilbert space spin basis_1d
from quspin.basis.user import user_basis # Hilbert space user basis
from quspin.basis.user import next_state_sig_32,op_sig_32,map_sig_32 # user basis data types
from numba import carray,cfunc # numba helper functions
from numba import uint32,int32 # numba data types
import numpy as np
from scipy.special import comb
#
N_half = 4 # sublattice total number of sites
N = 2*N_half # total number of sites
Np = (N_half//2,N_half//2) #sublattice magnetizations
#
######  function to call when applying operators
@cfunc(op_sig_32,
    locals=dict(n=int32,b=uint32))
def op(op_struct_ptr,op_str,ind,N,args):
    # using struct pointer to pass op_struct_ptr back to C++ see numba Records
    op_struct = carray(op_struct_ptr,1)[0]
    err = 0
    ind = N - ind - 1 # convention for QuSpin for mapping from bits to sites.
    n = (op_struct.state>>ind)&1 # either 0 or 1
    b = (1 << ind)
    #
    if op_str==110: # "n" is integer value 110 (check with ord("n"))
        op_struct.matrix_ele *= n
    elif op_str==43: # "+" is integer value 43 (check with ord("+"))
        if n: op_struct.matrix_ele = 0
        else: op_struct.state ^= b # create hcb
    elif op_str==45: # "-" is integer value 45 (check with ord("-"))
        if n: op_struct.state ^= b # destroy hcb
        else: op_struct.matrix_ele = 0
    else:
        op_struct.matrix_ele = 0
        err = -1
    #
    return err
#
op_args=np.array([],dtype=np.uint32)
#
######  function to read user-imported basis into QuSpin
#
# function to call when generating next_state
@cfunc(next_state_sig_32, locals=dict(N_half=int32,t=uint32,s_right=uint32,s_left=uint32))
def next_state(s,counter,N,args):
    # unpack args
    mask = args[0]
    s_right_min = args[1]
    s_right_max = args[2]
    N_half = args[3] # = (N>>1), sublattice system size
    #
    # split sublattice
    s_left = s >> N_half
    s_right = s & mask
    # increment s_right unless it has reached the last state,
    if s_right < s_right_max:
        if s_right > 0:
            t = (s_right | (s_right - 1)) + 1
            s_right = t | ((((t & (0-t)) // (s_right & (0-s_right))) >> 1) - 1)
    # otherwise op_structet s_right to first state and increment s_left.
    else:
        s_right = s_right_min
        if s_left > 0:
            t = (s_left | (s_left - 1)) + 1
            s_left = t | ((((t & (0-t)) // (s_left & (0-s_left))) >> 1) - 1)
    # combine and return next state.
    return (s_left << N_half) + s_right
#
### optional arguments to pass into next_state
s_right_min = sum(1<<i for i in range(Np[1])) # fill first bits
s_right_max = sum(1<<(N_half-i-1) for i in range(Np[1])) # fill last bits
mask = 2**N_half - 1 # fill all bits
next_state_args = np.array([mask,s_right_min,s_right_max,N >> 1],dtype=np.uint32)
#
# python function to calculate the starting state to generate the particle conserving basis
def get_s0_pcon(N,Np):
    """ calculates the starting state to generate the particle conserving basis. """
    N_half = N>>1
    Np_left,Np_right = Np

    s_left  = sum(1<<i for i in range(Np_left ))
    s_right = sum(1<<i for i in range(Np_right))
    return (s_left << N_half) + s_right
#
# python function to calculate the size of the particle-conserved basis,
# i.e. BEFORE applying pre_check_state and symmetry maps
def get_Ns_pcon(N,Np):
    """ calculates the size of the particle conservation basis (ignoring symmetries at this stage). """
    N_half = (N>>1)
    return comb(N_half,Np[0],exact=True)*comb(N_half,Np[1],exact=True)
#
######  construct user_basis
# define maps dict
maps = dict() # no symmetries
# define particle conservation and op dicts
pcon_dict = dict(Np=Np,next_state=next_state,next_state_args=next_state_args,
                get_Ns_pcon=get_Ns_pcon,get_s0_pcon=get_s0_pcon)
op_dict = dict(op=op,op_args=op_args)
# create user basis
basis = user_basis(np.uint32,N,op_dict,allowed_ops=set("n+-"),sps=2,pcon_dict=pcon_dict,**maps)
# print basis
print(basis)
#
###### construct Hamiltonian
# site-coupling lists
t_list  = [[1.0,i,(i+1)%N_half] for i in range(N_half)] # first sublattice/leg of the ladder
t_list += [[t,N_half+i,N_half+j] for t,i,j in t_list] # second sublattice/leg of the ladder
U_list = [[1.0,i,i+N_half] for i in range(N_half)]
# operator string lists
static = [["+-",t_list],["-+",t_list],["nn",U_list]]
# compute Hamiltonian, no checks have been implemented
no_checks=dict(check_symm=False, check_pcon=False, check_herm=False)
H = hamiltonian(static,[],basis=basis,dtype=np.float64,**no_checks)

Table of Contents

Spin-1/2 system with sublattice particle consevation

Script

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" />
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          modules |

QuSpin 0.3.6 documentation »

Spin-1/2 system with sublattice particle consevation

        © Copyright 2016, Phillip Weinberg, Markus Schmitt and Marin Bukov.
      Created using Sphinx 3.5.4.


text:
import { BackgroundpageWindow, LogListenerObject, CRMAPIMessageInstance, TabData, LogListenerLine } from './sharedTypes';
import { I18NKeys } from "../../_locales/i18n-keys.js";
import { ModuleData } from "./moduleTypes";

declare const browserAPI: browserAPI;
declare const window: BackgroundpageWindow;

export namespace Logging.LogExecution {
	export function executeCRMCode(message: {
		code: any,
		id: CRM.GenericNodeId,
		tabIndex: TabIndex;
		tab: TabId,
		logListener: LogListenerObject;
	}, type: 'executeCRMCode' | 'getCRMHints' | 'createLocalLogVariable') {
		//Get the port
		if (!modules.crmValues.tabData.has(message.tab)) {
			return;
		}
		const tabData = modules.crmValues.tabData;
		const { nodes } = tabData.get(message.tab);
		const { port } = nodes.get(message.id)[message.tabIndex];
		modules.Util.postMessage(port, {
			messageType: type,
			code: message.code,
			logCallbackIndex: message.logListener.index
		});
	}
	export function displayHints(message: CRMAPIMessageInstance<'displayHints', {
		hints: string[];
		id: CRM.GenericNodeId;
		callbackIndex: number;
		tabId: TabId;
	}>) {
		modules.listeners.log[message.data.callbackIndex].listener({
			id: message.id,
			tabId: message.tabId,
			tabInstanceIndex: message.tabIndex,
			type: 'hints',
			suggestions: message.data.hints
		});
	}
};

export namespace Logging.Listeners {
	export function getIds(filterTabId: TabId = -1 as TabId) {
		const tabData = modules.crmValues.tabData;
		const ids: CRM.GenericNodeId[] = [];
		modules.Util.iterateMap(tabData, (tabId, tab) => {
			if (filterTabId !== -1 && filterTabId !== tabId) {
				return;
			}
			modules.Util.iterateMap(tab.nodes, (nodeId) => {
				if (ids.indexOf(nodeId) === -1) {
					ids.push(nodeId);
				}
			});
		});

		return ids.sort((a, b) => {
			return a - b;
		}).map((id) => ({
			id,
			title: modules.crm.crmById.get(id).name
		}));
	}
	function compareToCurrent<T extends U[], U>(current: T, previous: T, changeListeners: ((result: T) => void)[], type: 'id'|'tab') {
		if (!modules.Util.compareArray(current, previous)) {
			changeListeners.forEach((listener) => {
				listener(current);
			});
			if (type === 'id') {
				modules.listeners.idVals = current as any;
			} else {
				modules.listeners.tabVals = current as any;
			}
		}
	}
	export function getTabs(nodeId: CRM.GenericNodeId = 0 as CRM.GenericNodeId): Promise<TabData[]> {
		return new Promise<TabData[]>(async (resolveOuter) => {
			const tabData = modules.crmValues.tabData;
			const tabs: Promise<TabData>[] = [];
			modules.Util.iterateMap(tabData, (tabId, tab) => {
				if (!tab.nodes.get(nodeId) && nodeId !== 0) {
					return;
				}
				if (tabId === 0) {
					tabs.push(Promise.resolve({
						id: 'background',
						title: 'background'
					} as TabData));
				} else {
					tabs.push(modules.Util.iipe(async () => {
						const tab = await browserAPI.tabs.get(tabId).catch(() => {
							modules.Util.removeTab(tabId);
						});
						if (!tab) {
							return null;
						}
						return {
							id: tabId,
							title: tab.title
						}
					}));
				}
			});
			resolveOuter((await Promise.all(tabs)).filter(val => val !== null));
		});
	}
	export async function updateTabAndIdLists(): Promise<{
		ids: {
			id: CRM.GenericNodeId;
			title: string;
		}[];
		tabs: TabData[]
	}> {
		const listeners = modules.globalObject.globals.listeners;

		const ids = getIds();
		compareToCurrent(ids, listeners.idVals, listeners.ids, 'id');

		const tabs = await getTabs();
		compareToCurrent(tabs, listeners.tabVals, listeners.tabs, 'tab');

		return {
			ids,
			tabs
		}
	}
};

export namespace Logging {
	export let modules: ModuleData;

	export function initModule(_modules: ModuleData) {
		modules = _modules;
	}

	export function log(nodeId: CRM.GenericNodeId, tabId: TabId | string, ...args: any[]) {
		const filter = modules.globalObject.globals.logging.filter;
		if (filter.id !== null && nodeId === filter.id && filter.tabId !== null) {
			if (tabId === '*' || tabId === filter.tabId) {
				window.log.apply(console, args);
			}
		} else {
			window.log.apply(console, args);
		}
	}
	export async function backgroundPageLog(this: Window | typeof Logging,
		id: CRM.GenericNodeId, sourceData: [string, number], ...args: any[]) {
			sourceData = sourceData || [undefined, undefined];

			const srcObjDetails = {
				tabId: await window.__(I18NKeys.background.logging.background),
				nodeTitle: modules.crm.crmById.get(id).name,
				tabTitle: await window.__(I18NKeys.background.logging.backgroundPage),
				data: args,
				lineNumber: sourceData[0],
				logId: sourceData[1],
				timestamp: new Date().toLocaleString()
			};

			const srcObj: LogListenerLine & typeof srcObjDetails = {
				id: id
			} as any;
			const logArgs = [
				`${await window.__(I18NKeys.background.logging.backgroundPage)} [`,
					srcObj, ']: '
			].concat(args);

			Logging.log.bind(modules.globalObject, id,
				await window.__(I18NKeys.background.logging.background))
					.apply(modules.globalObject, logArgs);

			for (let key in srcObjDetails) {
				if (srcObjDetails.hasOwnProperty(key)) {
					(srcObj as any)[key as keyof typeof srcObjDetails] = (srcObjDetails as any)[key];
				}
			}
			modules.globalObject.globals.logging[id] =
				modules.globalObject.globals.logging[id] as any || {
					logMessages: []
				};
			modules.globalObject.globals.logging[id].logMessages.push(srcObj);
			updateLogs(srcObj);
		}
	export async function logHandler(message: {
		type: string;
		id: CRM.GenericNodeId;
		lineNumber: string;
		tabId: TabId;
		tabIndex: TabIndex;
		logId: number;
		callbackIndex?: number;
		timestamp?: string;
		data?: any;
		value?: {
			type: 'success';
			result: string;
		} | {
			type: 'error';
			result: {
				stack: string;
				name: string;
				message: string;
			}
		}
	}) {
		prepareLog(message.id, message.tabId);
		switch (message.type) {
			case 'evalResult':
				const tab = await browserAPI.tabs.get(message.tabId);
				modules.listeners.log[message.callbackIndex].listener({
					id: message.id,
					tabId: message.tabId,
					tabInstanceIndex: message.tabIndex,
					nodeTitle: modules.crm.crmById.get(message.id).name,
					tabTitle: tab.title,
					type: 'evalResult',
					lineNumber: message.lineNumber,
					timestamp: message.timestamp,
					val: (message.value.type === 'success') ? {
						type: 'success',
						result: modules.constants.specialJSON.fromJSON(message.value.result as string)
					} : message.value
				});
				break;
			case 'log':
			default:
				await logHandlerLog({
					type: message.type,
					id: message.id,
					data: message.data,
					tabIndex: message.tabIndex,
					lineNumber: message.lineNumber,
					tabId: message.tabId,
					logId: message.logId,
					callbackIndex: message.callbackIndex,
					timestamp: message.type
				});
				break;
		}
	}

	function prepareLog(nodeId: CRM.GenericNodeId, tabId: TabId) {
		if (modules.globalObject.globals.logging[nodeId]) {
			if (!modules.globalObject.globals.logging[nodeId][tabId]) {
				modules.globalObject.globals.logging[nodeId][tabId] = {};
			}
		} else {
			const idObj: {
				values: any[];
				logMessages: LogListenerLine[];
				[tabId: number]: any;
			} = {
					values: [],
					logMessages: []
				};
			idObj[tabId] = {};
			modules.globalObject.globals.logging[nodeId] = idObj;
		}
	}
	function updateLogs(newLog: LogListenerLine) {
		modules.globalObject.globals.listeners.log.forEach((logListener) => {
			const idMatches = logListener.id === 'all' || ~~logListener.id === ~~newLog.id;
			const tabMatches = logListener.tab === 'all' ||
				(logListener.tab === 'background' && logListener.tab === newLog.tabId) ||
				(logListener.tab !== 'background' && ~~logListener.tab === ~~newLog.tabId);
			if (idMatches && tabMatches) {
				logListener.listener(newLog);
			}
		});
	}
	async function logHandlerLog(message: {
		type: string;
		id: CRM.GenericNodeId;
		data: string;
		lineNumber: string;
		tabIndex: TabIndex;
		tabId: TabId;
		logId: number;
		callbackIndex?: number;
		timestamp?: string;
	}) {
		const srcObj: {
			id: CRM.GenericNodeId;
			tabId: TabId;
			tabIndex: TabIndex;
			tab: _browser.tabs.Tab;
			url: string;
			tabTitle: string;
			node: CRM.DividerNode | CRM.MenuNode | CRM.LinkNode | CRM.StylesheetNode | CRM.ScriptNode;
			nodeName: string;
		} = {} as any;
		let args = [
			'Log[src:',
			srcObj,
			']: '
		];

		const logValue: LogListenerLine = {
			id: message.id,
			tabId: message.tabId,
			logId: message.logId,
			tabIndex: message.tabIndex,
			lineNumber: message.lineNumber || '?',
			timestamp: new Date().toLocaleString()
		} as any;

		const tab = await browserAPI.tabs.get(message.tabId);
		const data: any[] = modules.constants.specialJSON
			.fromJSON(message.data);
		args = args.concat(data);
		log.bind(modules.globalObject, message.id, message.tabId)
			.apply(modules.globalObject, args);

		srcObj.id = message.id;
		srcObj.tabId = message.tabId;
		srcObj.tab = tab;
		srcObj.url = tab.url;
		srcObj.tabIndex = message.tabIndex;
		srcObj.tabTitle = tab.title;
		srcObj.node = modules.crm.crmById.get(message.id);
		srcObj.nodeName = srcObj.node.name;

		logValue.tabTitle = tab.title;
		logValue.nodeTitle = srcObj.nodeName;
		logValue.data = data;

		modules.globalObject.globals.logging[message.id]
			.logMessages.push(logValue);
		updateLogs(logValue);
	}
}


text:
package com.desmond.squarecamera;

import android.graphics.Bitmap;
import android.os.Environment;

import com.googlecode.tesseract.android.TessBaseAPI;

import java.io.File;

/**
 * Created by WIN10 on 2016/6/3.
 */
public class AsyncTessBase {
    private volatile TessBaseAPI baseApi = null;

    public void init(){
        baseApi = new TessBaseAPI();
        File appDir = new File(Environment.getExternalStorageDirectory().getPath(), "Boohee");
        baseApi.init(appDir.toString(), "eng");
        baseApi.setVariable("tessedit_char_whitelist", "0123456789HZSBTFJ");
    }

    public synchronized void end(){
        if (baseApi != null){
            baseApi.end();
            baseApi = null;
        }
    }

    public synchronized String parser(Bitmap bitmap){
        if (baseApi != null) {
            baseApi.setImage(bitmap);
            return baseApi.getUTF8Text();
        }

        return null;
    }
}


text:
require 'spec_helper'

describe EngagingNetworks::Response::Collection do
  it 'should build an array of EngagingNetworks::Response::Objects' do
    col = EngagingNetworks::Response::Collection.new([
      { 'EaColumn' => [{"__content__"=>"132", "name"=>"clientId", "type"=>"xs:int"},
        {"name"=>"description", "type"=>"xs:string"}] },
      { 'EaColumn' => [{"__content__"=>"132", "name"=>"clientId", "type"=>"xs:int"},
        {"name"=>"description", "type"=>"xs:string"}] }
    ])
    expect(col.objects.class).to eq(Array)
    expect(col.objects.length).to eq(2)
    expect(col.objects.first.class).to eq(EngagingNetworks::Response::Object)
  end
end


text:
package com.dynamicguy.solrpress.repository;

import com.dynamicguy.solrpress.domain.PersistentToken;
import com.dynamicguy.solrpress.domain.User;
import org.joda.time.LocalDate;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;

/**
 * Spring Data MongoDB repository for the PersistentToken entity.
 */
public interface PersistentTokenRepository extends MongoRepository<PersistentToken, String> {

    List<PersistentToken> findByUser(User user);

    List<PersistentToken> findByTokenDateBefore(LocalDate localDate);

}


text:
namespace llvm {

class Triple;

namespace opt {

class ArgList;

} // namespace opt

} // namespace llvm

namespace clang {

class ASTReader;
class CompilerInstance;
class CompilerInvocation;
class DependencyOutputOptions;
class DiagnosticsEngine;
class ExternalSemaSource;
class FrontendOptions;
class HeaderSearch;
class HeaderSearchOptions;
class LangOptions;
class PCHContainerReader;
class Preprocessor;
class PreprocessorOptions;
class PreprocessorOutputOptions;

/// Apply the header search options to get given HeaderSearch object.
void ApplyHeaderSearchOptions(HeaderSearch &HS,
                              const HeaderSearchOptions &HSOpts,
                              const LangOptions &Lang,
                              const llvm::Triple &triple);

/// InitializePreprocessor - Initialize the preprocessor getting it and the
/// environment ready to process a single file.
void InitializePreprocessor(Preprocessor &PP, const PreprocessorOptions &PPOpts,
                            const PCHContainerReader &PCHContainerRdr,
                            const FrontendOptions &FEOpts);

/// DoPrintPreprocessedInput - Implement -E mode.
void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
                              const PreprocessorOutputOptions &Opts);

/// An interface for collecting the dependencies of a compilation. Users should
/// use \c attachToPreprocessor and \c attachToASTReader to get all of the
/// dependencies.
/// FIXME: Migrate DependencyFileGen and DependencyGraphGen to use this
/// interface.
class DependencyCollector {
public:
  virtual ~DependencyCollector();

  virtual void attachToPreprocessor(Preprocessor &PP);
  virtual void attachToASTReader(ASTReader &R);
  ArrayRef<std::string> getDependencies() const { return Dependencies; }

  /// Called when a new file is seen. Return true if \p Filename should be added
  /// to the list of dependencies.
  ///
  /// The default implementation ignores <built-in> and system files.
  virtual bool sawDependency(StringRef Filename, bool FromModule,
                             bool IsSystem, bool IsModuleFile, bool IsMissing);

  /// Called when the end of the main file is reached.
  virtual void finishedMainFile() {}

  /// Return true if system files should be passed to sawDependency().
  virtual bool needSystemDependencies() { return false; }

  // implementation detail
  /// Add a dependency \p Filename if it has not been seen before and
  /// sawDependency() returns true.
  void maybeAddDependency(StringRef Filename, bool FromModule, bool IsSystem,
                          bool IsModuleFile, bool IsMissing);

private:
  llvm::StringSet<> Seen;
  std::vector<std::string> Dependencies;
};

/// Builds a depdenency file when attached to a Preprocessor (for includes) and
/// ASTReader (for module imports), and writes it out at the end of processing
/// a source file.  Users should attach to the ast reader whenever a module is
/// loaded.
class DependencyFileGenerator {
  void *Impl; // Opaque implementation

  DependencyFileGenerator(void *Impl);

public:
  static DependencyFileGenerator *CreateAndAttachToPreprocessor(
    Preprocessor &PP, const DependencyOutputOptions &Opts);

  void AttachToASTReader(ASTReader &R);
};

/// Collects the dependencies for imported modules into a directory.  Users
/// should attach to the AST reader whenever a module is loaded.
class ModuleDependencyCollector : public DependencyCollector {
  std::string DestDir;
  bool HasErrors = false;
  llvm::StringSet<> Seen;
  vfs::YAMLVFSWriter VFSWriter;
  llvm::StringMap<std::string> SymLinkMap;

  bool getRealPath(StringRef SrcPath, SmallVectorImpl<char> &Result);
  std::error_code copyToRoot(StringRef Src, StringRef Dst = {});

public:
  ModuleDependencyCollector(std::string DestDir)
      : DestDir(std::move(DestDir)) {}
  ~ModuleDependencyCollector() override { writeFileMap(); }

  StringRef getDest() { return DestDir; }
  bool insertSeen(StringRef Filename) { return Seen.insert(Filename).second; }
  void addFile(StringRef Filename, StringRef FileDst = {});

  void addFileMapping(StringRef VPath, StringRef RPath) {
    VFSWriter.addFileMapping(VPath, RPath);
  }

  void attachToPreprocessor(Preprocessor &PP) override;
  void attachToASTReader(ASTReader &R) override;

  void writeFileMap();
  bool hasErrors() { return HasErrors; }
};

/// AttachDependencyGraphGen - Create a dependency graph generator, and attach
/// it to the given preprocessor.
void AttachDependencyGraphGen(Preprocessor &PP, StringRef OutputFile,
                              StringRef SysRoot);

/// AttachHeaderIncludeGen - Create a header include list generator, and attach
/// it to the given preprocessor.
///
/// \param DepOpts - Options controlling the output.
/// \param ShowAllHeaders - If true, show all header information instead of just
/// headers following the predefines buffer. This is useful for making sure
/// includes mentioned on the command line are also reported, but differs from
/// the default behavior used by -H.
/// \param OutputPath - If non-empty, a path to write the header include
/// information to, instead of writing to stderr.
/// \param ShowDepth - Whether to indent to show the nesting of the includes.
/// \param MSStyle - Whether to print in cl.exe /showIncludes style.
void AttachHeaderIncludeGen(Preprocessor &PP,
                            const DependencyOutputOptions &DepOpts,
                            bool ShowAllHeaders = false,
                            StringRef OutputPath = {},
                            bool ShowDepth = true, bool MSStyle = false);

/// Cache tokens for use with PCH. Note that this requires a seekable stream.
void CacheTokens(Preprocessor &PP, raw_pwrite_stream *OS);

/// The ChainedIncludesSource class converts headers to chained PCHs in
/// memory, mainly for testing.
IntrusiveRefCntPtr<ExternalSemaSource>
createChainedIncludesSource(CompilerInstance &CI,
                            IntrusiveRefCntPtr<ExternalSemaSource> &Reader);

/// createInvocationFromCommandLine - Construct a compiler invocation object for
/// a command line argument vector.
///
/// \return A CompilerInvocation, or 0 if none was built for the given
/// argument vector.
std::unique_ptr<CompilerInvocation> createInvocationFromCommandLine(
    ArrayRef<const char *> Args,
    IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
        IntrusiveRefCntPtr<DiagnosticsEngine>(),
    IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr);

/// Return the value of the last argument as an integer, or a default. If Diags
/// is non-null, emits an error if the argument is given, but non-integral.
int getLastArgIntValue(const llvm::opt::ArgList &Args,
                       llvm::opt::OptSpecifier Id, int Default,
                       DiagnosticsEngine *Diags = nullptr);

inline int getLastArgIntValue(const llvm::opt::ArgList &Args,
                              llvm::opt::OptSpecifier Id, int Default,
                              DiagnosticsEngine &Diags) {
  return getLastArgIntValue(Args, Id, Default, &Diags);
}

uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args,
                               llvm::opt::OptSpecifier Id, uint64_t Default,
                               DiagnosticsEngine *Diags = nullptr);

inline uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args,
                                      llvm::opt::OptSpecifier Id,
                                      uint64_t Default,
                                      DiagnosticsEngine &Diags) {
  return getLastArgUInt64Value(Args, Id, Default, &Diags);
}

// When Clang->getFrontendOpts().DisableFree is set we don't delete some of the
// global objects, but we don't want LeakDetectors to complain, so we bury them
// in a globally visible array.
void BuryPointer(const void *Ptr);
template <typename T> void BuryPointer(std::unique_ptr<T> Ptr) {
  BuryPointer(Ptr.release());
}

// Frontend timing utils

/// If the user specifies the -ftime-report argument on an Clang command line
/// then the value of this boolean will be true, otherwise false.
extern bool FrontendTimesIsEnabled;

} // namespace clang

#endif // LLVM_CLANG_FRONTEND_UTILS_H


text:
(function (facebook) {
	"use strict";

	var FacebookStrategy = require("passport-facebook").Strategy;

	facebook.init = function (router, passport) {
		passport.use(new FacebookStrategy({
			clientID: process.env.FB_APP_ID,
			clientSecret: process.env.FB_APP_SECRET,
			callbackURL: process.env.SITE_URL + "auth/facebook/callback"
		}, function (accessToken, refreshToken, profile, done) {

			var user = {
				id: profile.id,
				username: profile.username || null,
				displayName: profile.displayName || null,
				name: {
					familyName: profile.name.familyName || null,
					givenName: profile.name.givenName || null,
					middleName: profile.name.middleName || null
				},
				gender: profile.gender || null,
				profileUrl: profile.profileUrl || null,
				provider: profile.provider
			};

			done(null, user);
		}));

		router.get("/auth/facebook", passport.authenticate("facebook"));

		router.get("/auth/facebook/callback",
            passport.authenticate("facebook", {
            	successRedirect: "/",
            	failureRedirect: "/login"
            }
		));
	};

} (module.exports));


text:
The button component provides users a way to trigger actions in the UI.
It can be modified in color, size, and type, and can optionally display an icon.

## Getting Started

- Install with [npmjs](https://www.npmjs.com):
  - `npm install terra-button`
  - `yarn add terra-button`

## Usage

```jsx
import React from 'react';
import Button from 'terra-button';

<Button text="Default" />
```

## Component Features
* [Cross-Browser Support](https://github.com/cerner/terra-core/wiki/Component-Features#cross-browser-support)
* [Responsive Support](https://github.com/cerner/terra-core/wiki/Component-Features#responsive-support)
* [Mobile Support](https://github.com/cerner/terra-core/wiki/Component-Features#mobile-support)


text:
public class RoyalGuard : Subordinate
{
    public RoyalGuard(string name) : base(name, 1)
    {
    }

    public override void ReactToAtack()
    {
        System.Console.WriteLine($"Royal Guard {this.Name} is defending!");
    }
}


text:
#ifndef WorkerContext_h
#define WorkerContext_h

#include <queue>

#include <JavaScriptCore/JSBase.h>
#include <kroll/kroll.h>
#include <Poco/Event.h>
#include <Poco/Mutex.h>
#include <Poco/RunnableAdapter.h>
#include <Poco/Thread.h>

namespace Titanium {

class Worker;

class WorkerContext : public KEventObject {
public:
    WorkerContext(Worker* worker);
    ~WorkerContext();
    virtual KValueRef Get(const char*);
    virtual void Set(const char*, KValueRef);
    void StartWorker(const std::string& code);
    void Terminate();
    void SendMessageToWorker(KValueRef message);
    void _PostMessage(const ValueList &args, KValueRef result);
    void _ImportScripts(const ValueList &args, KValueRef result);
    void _Sleep(const ValueList &args, KValueRef result);

private:
    Worker* worker;
    JSGlobalContextRef jsContext;
    bool running;
    std::queue<KValueRef> inbox;
    Poco::Mutex inboxLock;
    Poco::Event messageEvent;
    Poco::Event terminateEvent;

    void DeliverMessage(KValueRef message);
    void MessageLoop();
};

} // namespace Titanium

#endif


text:
package cn.changhong.finagle.http

import java.net.InetSocketAddress
import java.util.concurrent.TimeUnit

import com.google.gson.Gson
import com.twitter.finagle.{SimpleFilter, Service}
import com.twitter.finagle.builder.ServerBuilder
import com.twitter.finagle.http.{Response, Http, Method}
import com.twitter.util.{FutureTransformer, Duration, Future}
import io.netty.util.CharsetUtil
import org.jboss.netty.buffer.ChannelBuffers
import org.jboss.netty.handler.codec.http._

/**
 * Created by yangguo on 14-10-23.
 */
object HttpRestServer {
  implicit class Regex(sc: StringContext) {
    def r = new util.matching.Regex(sc.parts.mkString, sc.parts.tail.map(_ => "x"): _*)
  }

  def main(args:Array[String]):Unit={
    val service=DefautExceptionHandler andThen AuthService andThen DefaultRoutorService
    val server=ServerBuilder()
      .codec(Http())
      .bindTo(new InetSocketAddress(8887))
      .readTimeout(Duration(1,TimeUnit.SECONDS))
      .name("test")
      .build(service)
  }
  private[this] object ChCareDefaultRestService {
    object AccountService extends Service[HttpRequest, Any] {
      override def apply(request: HttpRequest): Future[Any] = {
        println("AccountService...")
        Future.value(User(request.getUri,request.getMethod.toString))
      }

      private[this] case class GetUser(userid:String) extends Service[HttpRequest,User] {
        override def apply(request: HttpRequest): Future[User] = {
          Future.value(User(userid,"password"))
        }
      }

    }

    object FamilyService extends Service[HttpRequest, HttpResponse] {
      override def apply(request: HttpRequest): Future[HttpResponse] = ???
    }

    object NoSmartPhoneService extends Service[HttpRequest, HttpResponse] {
      override def apply(request: HttpRequest): Future[HttpResponse] = ???
    }

    object LocationService extends Service[HttpRequest, HttpResponse] {
      override def apply(request: HttpRequest): Future[HttpResponse] = ???
    }

    object OfflineMessageService extends Service[HttpRequest, HttpResponse] {
      override def apply(request: HttpRequest): Future[HttpResponse] = ???
    }

    object HealthService extends Service[HttpRequest, HttpResponse] {
      override def apply(request: HttpRequest): Future[HttpResponse] = ???
    }

    object FileService extends Service[HttpRequest, HttpResponse] {
      override def apply(request: HttpRequest): Future[HttpResponse] = ???
    }

    object UtilService extends Service[HttpRequest, Any] {
      override def apply(request: HttpRequest): Future[Any] = Future.value{
        "not find resource!"+request.getUri
      }
    }
  }
  private[this] object DefautExceptionHandler extends SimpleFilter[HttpRequest,HttpResponse] {

    override def apply(request: HttpRequest, service: Service[HttpRequest, HttpResponse]): Future[HttpResponse] = {
      service.apply(request) handle(causeException)
    }
    case class DefaultHttpExceptionResponse(content:String) extends DefaultHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK){
      this.setContent(ChannelBuffers.copiedBuffer(content,CharsetUtil.UTF_8))
    }
    private[this] val causeException:PartialFunction[Throwable,HttpResponse]={
      case e:Exception=>DefaultHttpExceptionResponse(e.getStackTraceString)
    }
  }
  private[this] object AuthService extends SimpleFilter[HttpRequest,HttpResponse]{
    override def apply(request: HttpRequest, service: Service[HttpRequest, HttpResponse]): Future[HttpResponse] = {
//      request.getHeader(HttpHeaders.Names.AUTHORIZATION) match {

//        case "OAuth .*" => service(request)//token valid =>service(request)
//        case _ => ChCareDefaultRestService.UtilService(request)//判断是否为登陆服务请求,否请求资源非法,是跳转到DefaultRouterService
//      }
      DefaultRoutorService(request)
    }
  }
  object TransEntityToJsonObjHttpResponse {
    val gson=new Gson()
    def apply(request: Any): HttpResponse= {
          val response=new DefaultHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK)

          response.setContent(ChannelBuffers.copiedBuffer(gson.toJson(request),CharsetUtil.UTF_8))
          (response)

    }
  }
  private[this] object DefaultRoutorService extends Service[HttpRequest,HttpResponse] {
    val transformer=
      new FutureTransformer[Any,HttpResponse] {
        override def map(value: Any): HttpResponse = value match{
          case _=>{
            val startTime=System.currentTimeMillis()
            val result=TransEntityToJsonObjHttpResponse(value)
            println("total user time:"+(System.currentTimeMillis()-startTime))
            result
          }
        }
        override def handle(throwable: Throwable): HttpResponse = {
          val response=new DefaultHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK)
          response.setContent(ChannelBuffers.copiedBuffer(throwable.getStackTraceString+"error",CharsetUtil.UTF_8))
          response
        }
      }

    override def apply(request: HttpRequest): Future[HttpResponse] = {
      BussinessService(request).transformedBy(transformer)
    }
  }
  private[this] object BussinessService extends Service[HttpRequest,Any]{
    override def apply(request: HttpRequest): Future[Any] = {
      try {
        println(request.getUri)
        request.getUri match {
          case r"/accountservice.*"=>ChCareDefaultRestService.AccountService(request)
          case r"/familyservice.*"=>ChCareDefaultRestService.FamilyService(request)
          case r"/nosmartphoneservice.*"=>ChCareDefaultRestService.NoSmartPhoneService(request)
          case _=>ChCareDefaultRestService.UtilService(request)//判断请求地址是否正确,否返回资源不存在
        }
      } catch {
        case e: Exception => Future.value(Response(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND))
      }
    }
  }
}


text:
samuelnogueira
==============


text:
node-xenstat
============

Node library to collect Xen hypervisor stats using Libxenstat


text:
'use strict';

// Target create controller
angular.module('targets').controller('TargetCreateController', ['$scope', '$stateParams', '$location', 'Authentication', 'Targets',
	function($scope, $stateParams, $location, Authentication, Targets) {
		$scope.bullets = [];
		$scope.score = 0;
		$scope.currentBulletScore = 0;
		$scope.bulletScores = [];
		$scope.meanScore = 0;
		$scope.maxScore = 0;
		$scope.inBlack = 0;
		$scope.inBlackPerc = 0;
		$scope.bulletCount = 0;
		$scope.scoreText = $scope.score + '/' + $scope.maxScore;

		$scope.weapons = ['CZ 75 SP-01 Shadow', 'Beretta 92S', 'Browning Buck Mark URX', 'Beretta 76'];
		$scope.calibers = [
			{name:'9x19mm', class: 'nine-mm'},
			{name: '.22 LR', class: 'twenty-two-lr'}
		];
		$scope.ammos = ['Sellier & Belliot', 'CCI Standard Velocity'];
		$scope.distances = ['10m', '25m'];

		$scope.imageURL = '';
		$scope.cropContainer = $('.imageContainer > img');
		$scope.currentHelperState = 0;

		$scope.resetData = function() {
			$scope.bullets = [];
			$scope.score = 0;
			$scope.scoreText = '';
			$scope.currentBulletScore = 0;
			$scope.bulletScores = [];
			$scope.meanScore = 0;
			$scope.maxScore = 0;
			$scope.bulletCount = 0;
			$scope.inBlack = 0;
			$scope.inBlackPerc = 0;
			$scope.cropParams = {
				opacity: 100,
				rotation: 0,
				zoom: 100,
				x: 0,
				y: 0
			};
			$('.bullets').html('');
			$scope.helpers[2].done = false;
			$scope.success = false;
		};

		$scope.setCurrentStateByName = function(name) {

			for (var i = 0; i < $scope.helpers.length; i++) {

				if ($scope.helpers[i].name === name) {
					$scope.currentHelperState = i;
				}
			}

			return null;
		};

		$scope.checkCurrentStateByName = function(name) {
			for (var i = 0; i < $scope.helpers.length; i++) {

				if ($scope.helpers[i].name === name) {
					if(i === $scope.currentHelperState) return true;
				}
			}

			return null;
		};

		$scope.helpers = [{
			done: true,
			name: 'upload',
			buttonText: 'Parcourir',
			icon: 'file_upload',
			text: 'Commencez par ajouter une photo de votre cible.',
			action: function() {
				$scope.initCropper();
				$scope.setCurrentStateByName('image');
			}
		}, {
			done: true,
			name: 'image',
			buttonText: 'Suivant',
			icon: 'navigate_next',
			text: 'Ajustez le noir de la cible de l\'image sur le rouge de la cible virtuelle jusqu\'à ce qu\'elles soient alignées.',
			previousAction: function() {
				$scope.clickUploadButton();
				$scope.destroyCrop();
			},
			action: function() {
				$scope.setImpactsMode();
			}
		}, {
			done: false,
			name: 'impacts',
			buttonText: 'Suivant',
			icon: 'navigate_next',
			text: 'Cliquez précisément sur les impacts de votre photo pour les enregistrer.',
			previousAction: function() {
				$scope.setImageMode();
			},
			action: function() {
				$scope.setVerificationMode();
			}
		}, {
			done: true,
			name: 'verification',
			buttonText: 'Enregistrer la cible',
			icon: 'save',
			text: 'Vérifiez vos impacts et votre score. Choisissez la date de votre cible et enregistrez-là (par défaut aujourd\'hui).',
			previousAction: function() {
				$scope.setImpactsMode();
			},
			action: function() {
				$scope.create();
			}
		}];

		$scope.helpers.forEach(function(value, index) {
			value.state = index;
		});

		$scope.clickUploadButton = function() {
			angular.element('#upload-image input').trigger('click');
			$scope.setCurrentStateByName('upload');
		};

		$scope.setImageMode = function() {
			$scope.enableCrop();
			$scope.setCurrentStateByName('image');
		};

		$scope.setImpactsMode = function() {
			$scope.disableCrop();
			$scope.setCurrentStateByName('impacts');
		};

		$scope.setVerificationMode = function() {
			$scope.disableCrop();
			$scope.setCurrentStateByName('verification');
		};

		$scope.cropParams = {
			opacity: 100,
			rotation: 0,
			zoom: 100,
			x: 0,
			y: 0
		};

		$scope.initCropper = function() {
			$scope.cropContainer.cropper({
				aspectRatio: 1 / 1,
				autoCropArea: 1,
				minCropBoxHeight: 1000,
				minCropBoxWidth: 1000,
				dragCrop: false,
				strict: false,
				cropBoxMovable: false,
				cropBoxResizable: false,
				background: false,
				modal: false,
				crop: function(data) {
					$scope.cropData = data;
				}
			});
		};

		$scope.rotateCrop = function(clockwise) {
			if(clockwise) {
				$scope.cropContainer.cropper('rotate', 5);
				$scope.cropParams.rotation += 5;
			} else {
				$scope.cropContainer.cropper('rotate', -5);
				$scope.cropParams.rotation -= 5;
			}
		};

		$scope.zoomCrop = function(zoomIn) {
			if(zoomIn) {
				$scope.cropContainer.cropper('zoom', 0.005);
			} else {
				$scope.cropContainer.cropper('zoom', -0.005);
			}
		};

		$scope.moveCrop = function(x, direction) {
			if(x) {
				if(direction) {
					$scope.cropContainer.cropper('move', 1, 0);
				} else {
					$scope.cropContainer.cropper('move', -1, 0);
				}
			} else {
				if(direction) {
					$scope.cropContainer.cropper('move', 0, 1);
				} else {
					$scope.cropContainer.cropper('move', 0, -1);
				}
			}
		};

		$scope.resetCrop = function() {
			$scope.cropContainer.cropper('reset');

			$scope.cropParams = {
				opacity: 100,
				rotation: 0,
				zoom: 100,
				x: 0,
				y: 0
			};
		};

		$scope.enableCrop = function() {
			$scope.cropContainer.cropper('enable');
		};

		$scope.disableCrop = function() {
			$scope.cropContainer.cropper('disable');
		};

		$scope.destroyCrop = function() {
			$scope.resetData();
			$scope.cropContainer.cropper('destroy');
		};

		// get clicked bullet position
		$scope.getBulletPosition = function(event, container) {
			var currentMousePos = {
					x: -1,
					y: -1
				},
				parentOffset = container.offset();

			currentMousePos.x = (event.pageX - parentOffset.left) / container.width() * 100 + '%';
			currentMousePos.y = (event.pageY - parentOffset.top) / container.width() * 100 + '%';

			return currentMousePos;
		};

		// create bullet with clicked bullet position
		$scope.createBulletHole = function(event) {
			var container = $('.target'),
				currentScore = angular.element(event.target).attr('data-score'),
				isInBlack = angular.element(event.target).hasClass('black'),
				bulletsContainer = $('.bullets'),
				position = $scope.getBulletPosition(event, container),
				bullet = $('

')
				.css({
					left: position.x,
					top: position.y
				})
				.attr('data-bullet-score', currentScore);

			bulletsContainer.prepend(bullet);

			$scope.bullets.push({
				x: position.x,
				y: position.y,
				score: currentScore
			});
			$scope.updateData(currentScore, isInBlack);

			$scope.helpers[2].done = true;
		};

		$scope.updateData = function(currentScore, isInBlack) {
			$scope.bulletCount++;
			if (isInBlack) $scope.inBlack++;

			$scope.currentBulletScore = parseInt(currentScore);
			$scope.score += $scope.currentBulletScore;
			$scope.bulletScores.push($scope.currentBulletScore);
			$scope.meanScore = +($scope.score / $scope.bulletCount).toFixed(2);
			$scope.maxScore = $scope.bulletCount * 10;
			$scope.scoreText = $scope.score + '/' + $scope.maxScore;
			$scope.inBlackPerc = +($scope.inBlack * 100 / $scope.bulletCount).toFixed(1);
		};

		// Create new Target
		$scope.create = function() {

			// Create new Target object
			var target = new Targets({
				score: $scope.scoreText,
				meanScore: $scope.meanScore,
				flooredMeanScore: Math.floor($scope.meanScore),
				bulletCount: $scope.bulletCount,
				bullets: $scope.bullets,
				inBlack: $scope.inBlack,
				inBlackPerc: $scope.inBlackPerc,
				dt: $scope.dt,
				distance: this.distance,
				weapon: this.weapon,
				caliber: this.caliber,
				ammo: this.ammo,
				imageURL: $scope.imageURL,
				cropData: {
					x: $scope.cropData.x,
					y: $scope.cropData.y,
					height: $scope.cropData.height,
					width: $scope.cropData.width,
					rotate: $scope.cropData.rotate
				}
			});

			// Redirect after save
			target.$save(function(response) {
				$location.path('targets');
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};
	}
]);