text:
<?php

/**
 * SampiCMS mobile API
 *
 * Handles requests for the mobile app.
 *
 * <p>
 * The app sends a tag with it's POST request.
 * The tag gets processed, the associated action is executed and the result gets returned as a JSON encoded string.
 * </p>
 *
 * @author Sven Dubbeld <sven.dubbeld1@gmail.com>
 */
/**
 * Namespace
 */
namespace SampiCMS\Admin\MobileAPI;
use SampiCMS;
use SampiCMS\Admin;

/**
 * Absolute path to the root of SampiCMS.
 * @ignore
 */
define ( 'SampiCMS\ROOT', substr ( dirname ( __FILE__ ), 0, - 22 ) );
/**
 * Relative (web) path to the root of SampiCMS.
 * @ignore
 */
define ( 'SampiCMS\REL_ROOT', substr ( $_SERVER ['SCRIPT_NAME'], 0, - 32 ) );
/**
 * Absolute path to the admin root.
 * @ignore
 */
define ( 'SampiCMS\ADMIN_ROOT', SampiCMS\ROOT . '/sampi/admin' );
/**
 * Relative (web) path to the root of SampiCMS.
 * @ignore
 */
define ( 'SampiCMS\ADMIN_REL_ROOT', SampiCMS\REL_ROOT . '/sampi/admin' );
/**
 * Absolute path to the mobile API root.
 * @ignore
 */
define ( 'SampiCMS\API_ROOT', SampiCMS\ADMIN_ROOT . '/mobileapi' );
/**
 * Relative (web) path to the mobile API root.
 * @ignore
 */
define ( 'SampiCMS\API_REL_ROOT', SampiCMS\ADMIN_REL_ROOT . '/mobileapi' );

require_once 'DbFunctions.php';

$db = new DbFunctions ();

$db->getSettings ();

if (isset ( $_POST ['tag'] ) && $_POST ['tag'] != '') {
	$tag = $_POST ['tag'];

	$response = array (
			'tag' => $tag,
			'success' => 0,
			'error' => 0
	);
	$security_key = $db->getSecurityKey ();

	$username = $_POST ['username'];
	$password = $_POST ['password'];

	$user = $db->checkAuth ( $username, $password );

	switch ($tag) {
		case 'login' : // User logs in
			if ($user != false) {
				$response ['success'] = 1;
				$response ['user'] ['id'] = $user ['id'];
				$response ['user'] ['username'] = $user ['username'];
				$response ['user'] ['password'] = $user ['password'];
				$response ['user'] ['full_name'] = $user ['full_name'];
				$response ['user'] ['rights'] = $user ['rights'];
				$response ['user'] ['twitter_user'] = $user ['twitter_user'];
				echo json_encode ( $response );
			} else {
				$response ['error'] = 1;
				$response ['error_msg'] = 'Error logging in. Are you sure you\'ve entered the correct credentials?';
				echo json_encode ( $response );
			}
			break;
		case 'new_post' : // User adds a post
			if ($user != false) {
				$title = @$_POST ['title'];
				$content = @$_POST ['content'];
				$keywords = @$_POST ['keywords'];
				if ($db->newPost ( $title, $content, $keywords, $username, $password ) == true) {
					$response ['success'] = 1;
				} else {
					$response ['error'] = 1;
					$response ['error_msg'] = 'Error adding post.';
				}
				echo json_encode ( $response );
			} else {
				$response ['error'] = 1;
				$response ['error_msg'] = 'Error logging in. Are you sure you\'ve entered the correct credentials?';
				echo json_encode ( $response );
			}
			break;
		case 'edit_post' : // User edits a post
			if ($user != false) {
				$post_nr = @$_POST ['post_nr'];
				$title = @$_POST ['title'];
				$content = @$_POST ['content'];
				$keywords = @$_POST ['keywords'];
				if ($db->editPost ( $post_nr, $title, $content, $keywords, $username, $password ) == true) {
					$response ['success'] = 1;
				} else {
					$response ['error'] = 1;
					$response ['error_msg'] = 'Error editing post.';
				}
				echo json_encode( $response );
			} else {
				$response ['error'] = 1;
				$response['error_msg'] = 'Error logging in. Are you sure you\'ve entered the correct credentials?';
				echo json_encode( $response );
			}
			break;
		case 'settings' : // User fetches settings
			if ($user != false) {
				$settings = $db->returnSettings ();
				$response ['success'] = 1;
				foreach ( $settings as $setting => $value ) {
					$response ['settings'] [$setting] = $value;
				}
				echo json_encode ( $response );
			} else {
				$response ['error'] = 1;
				$response ['error_msg'] = 'Error logging in. Are you sure you\'ve entered the correct credentials?';
				echo json_encode ( $response );
			}
			break;
		case 'fetch_posts' : // User fetches posts
			if ($user != false) {
				$posts = $db->getAllPosts ();
				$response ['success'] = 1;
				foreach ( $posts as $key => $val ) {
					$response ['posts'] [$val->getNr ()] ['post_nr'] = $val->getNr ();
					$response ['posts'] [$val->getNr ()] ['date'] = $val->getDate ();
					$response ['posts'] [$val->getNr ()] ['modified'] = $val->getDateUpdated();
					$response ['posts'] [$val->getNr ()] ['author'] = $val->getAuthor ( SampiCMS\Post::AUTHOR_USERNAME );
					$response ['posts'] [$val->getNr ()] ['title'] = $val->getTitle ();
					$response ['posts'] [$val->getNr ()] ['content'] = $val->getContent ();
					$response ['posts'] [$val->getNr ()] ['keywords'] = $val->getKeywords();
				}
				echo json_encode ( $response );
			} else {
				$response ['error'] = 1;
				$response ['error_msg'] = 'Error logging in. Are you sure you\'ve entered the correct credentials?';
				echo json_encode ( $response );
			}
			break;
		case 'fetch_authors' : // User fetches authors
			if ($user != false) {
				$authors = $db->getAuthors ();
				$response ['success'] = 1;
				foreach ( $authors as $key => $val ) {
					$response ['authors'] [$val->getId ()] ['id'] = $val->getId ();
					$response ['authors'] [$val->getId ()] ['username'] = $val->getUsername ();
					$response ['authors'] [$val->getId ()] ['full_name'] = $val->getName ();
					$response ['authors'] [$val->getId ()] ['twitter_user'] = $val->getTwitter ();
				}
				echo json_encode ( $response );
			} else {
				$response ['error'] = 1;
				$response ['error_msg'] = 'Error logging in. Are you sure you\'ve entered the correct credentials?';
				echo json_encode ( $response );
			}
			break;
		default : // User sends unknown request
			$response ['error'] = 1;
			$response ['error_msg'] = 'Invalid Request';
			echo json_encode ( $response );
			break;
	}
} else {
	$response ['error_msg'] = 'Access Denied';
	echo json_encode ( $response );
}


text:
/*
Reflection:

What is important to know when linking an external file (like a stylesheet) to
an HTML file?

You need to link it in the head section of your HTML file using the "<link>"
tag. You should specify what type of relationship the linked file has to the
current file using the "rel" attribute and you should define the type of file
it is using the "type" attribute. Most importantly, you need to link to your
external file using the "href" attrubute, making sure to navigate your file
structure carefully in order to link the files correctly.

What tricks did you use to help you with positioning? How hard was is it to
get the site as you wanted it?

We separated the bulleted list items into two separate divs, gave them class
names, then used "float: left" on both to place them side by side. We first
tried "float: right" on the second column, but that created too much space in
the middle. Also, the footer section jumped up alongside our floated sections,
so we used "clear: left" on the footer to push it down below our floated sections.

What CSS did you use to modify the element style (like size, color, etc.)?

For modifying text, We used "color" to modify the text and link colors,
"font-weight" to create bold font, and "font-size" to create various font sizes.
We also used "border" to create the horizontal lines.

Did you modify the HTML to use classes or ids? If so, which did you choose and
why? If you didn't, how would you know which one to add to your HTML?

Yes, we used class in a few places. We chose class instead of id because there
was a potential that we would use it in more than one place. id should be reserved
for when you know that there will only be one item that you will use the id for.

When you compared your site to the actual code base, which do you think had
cleaner code that followed best practices and why?

I think ours is cleaner because it is more semantically structured and we didn't
use tables for formatting. We separated the HTML structural elements from the CSS
that we used for presentation and styling. Don't get me wrong... Ours still needs
work! But we're on the right track.

*/

body {
  color: #000080;
  background-color: #fff;
}
a:link {
    color: #800080;
}
a:visited {
    color: #ff0000;
}
header {
  font-weight: bold;
  font-size: 1.25em;
  text-align: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #999;
}
.bh {
  font-size: 1.75em;
}
.header_address {
  display: block;
}
.col_a, .col_b {
  float: left;
}
li {
  line-height: 2em;
}
.bullet_notes {
  font-size: .85em;
}
footer {
  clear: left;
}
.geico_info {
  border-top: 1px solid #999;
  border-bottom: 1px solid #999;
  text-align: center;
}
.geico_info img {
  display: block;
  margin: 0 auto;
}
.contact_info {
  border-bottom: 1px solid #999;
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

/**
 * General performance benchmarks
 */

var util = require('util'),
    crypto = require('crypto'),
    RedisMetrics = require('../lib/metrics');

var metrics = new RedisMetrics();
var simpleCounter = metrics.counter('simple');
var hourCounter = metrics.counter('hour', {
  timeGranularity: 'hour'
});

var eventObjectCounter = metrics.counter('event');
var eventObjectHourCounter = metrics.counter('eventHour', {
  timeGranularity: 'hour'
});

function Test(options) {
  this.name = options.name;
  this.iterations = options.iterations;
  this.testFunction = options.testFunction;
  this.commandsCalled = 0;
}

Test.prototype.run = function(onComplete) {
  var _this = this;
  var start = process.hrtime();

  var testCallback = function() {
    _this.commandsCalled++;

    // If the number of completed commands equal the number of iterations
    // then report the result.
    if (_this.commandsCalled >= _this.iterations) {
      var diff = process.hrtime(start);
      var ms = diff[0] * 1000.0 + diff[1] / 1000000;
      var ops = parseInt(_this.iterations / ms * 1000.0);
      var result = util.format('%s took %d milliseconds, %d ops/sec',
        _this.name, ms, ops);
      onComplete(result);
    }
  };

  for (var i = 0; i < this.iterations; i++) {
    this.testFunction(testCallback, i);
  }
};

// Simple counter increment and count

var tests = [];
tests.push(new Test({
  name: 'incr simple 10000',
  iterations: 10000,
  testFunction: function(callback) {
    simpleCounter.incr(callback);
  }
}));

tests.push(new Test({
  name: 'count simple 10000',
  iterations: 10000,
  testFunction: function(callback) {
    simpleCounter.incr(callback);
  }
}));

// Counter with hourly time granularity

tests.push(new Test({
  name: 'incr hour 10000',
  iterations: 10000,
  testFunction: function(callback) {
    hourCounter.incr(callback);
  }
}));

tests.push(new Test({
  name: 'count hour 10000',
  iterations: 10000,
  testFunction: function(callback) {
    hourCounter.count(callback);
  }
}));

// Counter per user

var users = [];
for (var i = 0; i < 10000; i++) {
  users.push(crypto.pseudoRandomBytes(16).toString('hex'));
}

tests.push(new Test({
  name: 'incr user counter simple 10000',
  iterations: 10000,
  testFunction: function(callback, iteration) {
    metrics
      .counter(users[iteration])
      .incr(callback);
  }
}));

tests.push(new Test({
  name: 'incr user counter hour 10000',
  iterations: 10000,
  testFunction: function(callback, iteration) {
    metrics
      .counter(users[iteration], {
        timeGranularity: 'hour'
      })
      .incr(callback);
  }
}));

tests.push(new Test({
  name: 'incr counter sorted user set 10000',
  iterations: 10000,
  testFunction: function(callback, iteration) {
    eventObjectCounter.incr(users[iteration], callback);
  }
}));

tests.push(new Test({
  name: 'incr hour counter sorted user set 10000',
  iterations: 10000,
  testFunction: function(callback, iteration) {
    eventObjectHourCounter.incr(users[iteration], callback);
  }
}));

function nextTest() {
  var test = tests.shift();
  if (test) {
    test.run(function(result) {
      console.log(result);
      nextTest();
    });
  } else {
    metrics.client.info('memory', function(err, res) {
      console.log(res);
      console.log('All done!');
      process.exit(0);
    });
  }
}

metrics.client.flushall(function() {
  nextTest();
});


text:
django-utils
============

Common Django utilities/scripts used in various projects. Experimental and not recommended for production use as is.


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


text:
test_file(){
  FILE=$1
  echo "> insert-type" "$@"
  assert_ok "$FLOW" autofix insert-type --in-place "$@"
  assert_ok "$FLOW" force-recheck "$FILE"
  echo "> cat $FILE"
  cat "$FILE"
}

test_file a.js 6 15
test_file b.js 6 15 --strategy=generalize
test_file c.js 6 15 --strategy=specialize

echo "> flow status"
assert_errors "$FLOW" status --strip-root


text:
"""
Login page
"""

import requests
from bs4 import BeautifulSoup
try:
    from urllib.parse import urljoin
except ImportError:
    from urlparse import urljoin

URL = 'https://login.yahoo.com'
DESKTOP_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1)\
    AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36'

def authenticated_session(username, password):
    """
    Given username and password, return an authenticated Yahoo `requests`
    session that can be used for further scraping requests.

    Throw an AuthencationError if authentication fails.
    """
    session = requests.Session()
    session.headers.update(headers())

    response = session.get(url())
    login_path = path(response.text)
    login_url = urljoin(response.url, login_path)
    login_post_data = post_data(response.text, username, password)

    response = session.post(login_url, data=login_post_data)
    if response.headers['connection'] == 'close':
        raise Exception('Authencation failed')

    return session

def url():
    """
    Return the URL for the login page
    """
    return URL

def headers():
    """
    Return the headers necessary to get expected version of the login page
    """
    return {
        'user-agent': DESKTOP_USER_AGENT
    }

def path(page):
    """
    Return the required path for login
    """
    soup = BeautifulSoup(page)
    try:
        return soup.find(id='mbr-login-form')['action']
    except:
        return None

def post_data(page, username, password):
    """
    Given username and password, return the post data necessary for login
    """
    soup = BeautifulSoup(page)
    try:
        inputs = soup.find(id='hiddens').findAll('input')
        post_data = {input['name']: input['value'] for input in inputs}
        post_data['username'] = username
        post_data['passwd'] = password
        return post_data
    except:
        return None


text:
# Escopo em JavaScript
Vamos iniciar estudando qual o comportamento do JavaScript no que se refere à delimitação de seus escopos, então, mão à obra!

## Variáveis Globais
Em JS, o escopo de variáveis é **delimitado pela criação de funções**, vamos ver alguns exemplos práticos disso:
```
var globally = 'a';

console.log('Global: ' + globally);
```
Tudo certo, varíavel definida globalmente então seu acesso é garantido em todos escopos!

```
function localScope(){
  var locally = 'b';

  console.log('Dentro do local: ' + globally); // O escopo local tem acesso à variável global normalmente
  console.log('Dentro do local: ' + locally); // E também à variável dentro de seu escopo
}

localScope();
```
O escopo local tem acesso garantido à variável global `globally` normalmente, e também à variável `locally` que faz parte do seu escopo.

```
console.log('Global: ' + locally);
```
Já o **escopo global não pode acessar uma variável declarada e inicializada dentro de um escopo local** (como a variável `locally` de nosso exemplo), por esta não fazer parte de seu contexto.

Em suma, variáveis globais são as variáveis declaradas fora de quaisquer funções.

## Hoisting
Hoisting, ou *Elevação*, é o termo dado para a capacidade que o JS tem de identificar todas as funções e variáveis declaradas ao longo do código antes de sua execução, acabando com erros de referência pela posição das declarações e instâncias das mesmas.

**Importante:** Somente as declarações de variáveis sofrem elevação, não a inicialização (atribuição de valor) das mesmas.

Vamos a um exemplo:
```
x = 10; // Inicialização da variável

console.log(x);

var x; // Declaração de variável
```
Neste caso, o hoisting se aplica perfeitamente, elevando a declaração de `x` para o início do código, parece mágica!

Agora uma outra possibilidade:
```
console.log(y);

var y = 5; // Declaração e inicialização após chamada
```
Já  aqui, a variável `y` é declarada, sua declaração é elevada mas não o seu valor, pois a inicialização não sofre hoisting!

Vale ressaltar que **funções também sofrem hoisting**:
```
doSomething();

function doSomething() {
  console.log('Hello there!');
}
```
O JS, ao contrário de outras linguagens, primeiro varre o código todo antes de sua execução, trazendo para o ínicio as declarações de variáveis e funções extinguindo assim os temíveis *"Uncaught ReferenceError: foo is not defined"*.

## Variáveis por parâmetro
Sempre que passamos uma variável via parâmetro pra uma função (como em `function foo(bar);` por exemplo), enviamos seu valor para a assinatura desta função. Variáveis que são passadas por parâmetro só podem ser acessadas dentro do escopo da função em questão.

Vamos ver um exemplo pra ficar mais claro:
```
function somando(parametro1, parametro2) {
  console.log(parametro1 + parametro2);
}

somando(50, 25);
```
A saída de `somando(50, 25)` será `75`, pois os valores dos parâmetros são passados para o escopo da função `somando` que cria variáveis "invisiveis" dentro de seu escopo.

Podemos enviar variáveis globais como parâmetros para uma função, mas precisamos nos atentar ao fato de que estamos enviando apenas seu valor, portanto na realidade criamos uma nova variável local e atribuímos à ela o valor passado como parâmetro da variável global.

Vejamos o exemplo:
```
var globally = 200;

function newScope(a) {
  a = 1;
}

newScope(globally); // enviamos a variável global como parâmetro para newScope
console.log(globally);
```
O código acima produz a saída de `200`, pois somente o valor foi enviado para newScope, que atribuiu este valor a uma variável local sua.

## Closure
Closures (ou clausuras, em tradução literal) são funções criadas dentro de outras funções. Como vimos anteriormente, o que delimita o escopo do JS são as funções, portando closures têm acesso a três tipos de variáveis:

1. Variáveis do escopo global;
2. Variáveis do escopo da função em que estão inseridas;
3. Variáveis de seu próprio escopo.

Vejamos um exemplo:
```
var message = 'Ei, encontramos erros nos dados inseridos em '; //variável de escopo global

function errorMessage(field) { // cria-se o escopo de errorMessage

  function firstClosure() { // cria-se o escopo de firstClosure que está inserido no contexto de errorMessage
    var action = ", confira e tente novamente";

    console.log(message + field + action);
  }

  firstClosure();
}

errorMessage('email');
```
O código acima produzirá a saída `Ei, encontramos erros nos dados inseridos em email, confira e tente novamente`, ou seja, a função `firstClosure` teve acesso à variável global `message`, à variável `field` do escopo de `errorMessage` e também à variável `action` de seu próprio escopo.

## IIFE - Immediately-Invoked Function Expression
As IIFEs (ou *Funções Imediatas*) são utilizadas para **criar escopos** dentro do código, principalmente com a finalidade de **encapsulamento** de atributos (variáveis no caso do JS).

Uma IIFE é caracterizada por um par de abre-e-fecha parênteses, e devem ser precedidas por um operador para serem interpretadas como uma expressão e não a declaração de uma função.

Exemplo:
```
function foo(){
  // corpo de foo
}();
```
O que nos retorna um erro, pois o parser identifica como uma função, e não uma expressão.

Certo, e se tentarmos uma função anônima?
```
function(){
  // corpo da função anônima
}();
```
Mesmo erro, pois o parser ainda identifica como uma função e não uma expressão.

Para solucionarmos esse entrave, precisamos invocar a expressão após um operador, como no exemplo:
```
(function bar(){
  // corpo de bar
})();
```
O que nos retorna `undefined`, então deu certo, YES!

Que tal com anônima?
```
(function(){
  // corpo da função anônima
})());
```
Funcionando! :)

E se eu precisar de parâmetros? Tá na mão:
```
(function lorem(x) {
  console.log(x);
})('ipsum');

// Anônima também:
(function (x){
  console.log(x);
})('dolor sit amet');
```
Quer economizar alguns bytes no seu código? Vamos usar operadores unários para declarar a IIFE:
```
!function(){/* corpo */}();
~function(){/* corpo */}();
-function(){/* corpo */}();
+function(){/* corpo */}();
```

Agora ficou fácil entender como funciona o escopo em JS, não acha? ;)


text:
/**
 * THIS FILE IS AUTO-GENERATED
 * DON'T MAKE CHANGES HERE
 */
import { BigNumberDependencies } from './dependenciesBigNumberClass.generated';
import { createInfinity } from '../../factoriesAny.js';
export var InfinityDependencies = {
  BigNumberDependencies: BigNumberDependencies,
  createInfinity: createInfinity
};


text:
package edu.indiana.lib.twinpeaks.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class StringUtils {

	/**
	 * Minimum length supported by truncateAtWhitespace()
	 */
	private static final int MINIMUM_SUPPORTED_LENGTH	= 4;

	private StringUtils() {
	}

  /**
   * Replace all occurances of the target text with the provided replacement
   * text.  Both target and replacement may be regular expressions - see
   * java.util.regex.Matcher.
   * @param text Text to modify
   * @param targetText Text to find and replace
   * @param newText New text
   * @return Updated text
   */
	public static String replace(String text, String targetText, String newText) {
  	  	Pattern pattern = Pattern.compile(targetText, Pattern.CASE_INSENSITIVE);
  	  	Matcher matcher = pattern.matcher(text);
  	  	return matcher.replaceAll(newText);
	}

	/**
	 * Null (or zero-length) String?
	 */
	public static boolean isNull(String string) {
	 	return (string == null) || (string.length() == 0);
	}

	/**
	 * Truncate text on a whitespace boundary (near a specified length).
	 * The length of the resultant string will be in the range:

	 *    (requested-length * .25) ~ (requested-length * 1.5)
	 * @param text Text to truncate
	 * @param length Target length
	 * @return Truncated text
	 */
	public static String truncateAtWhitespace(String text, int length) {
		int	desired, lowerBound, upperBound;
		/*
		 * Make sure we have a reasonable length to work with
		 */
		if (length < MINIMUM_SUPPORTED_LENGTH) {
			 throw new IllegalArgumentException("Requested length too short (must be "
			 																	+ MINIMUM_SUPPORTED_LENGTH
			 																	+ " or greated)");
		}
		/*
		 * No need to truncate - the original string "fits"
		 */
		if (text.length() <= length) {
			return text;
		}
		/*
		 * Try to find whitespace befor the requested maximum
		 */
		lowerBound 	= length / 4;
		upperBound	= length + (length / 2);

		for (int i = length - 1; i > lowerBound; i--) {
			if (Character.isWhitespace(text.charAt(i))) {
				return text.substring(0, i);
			}
		}
		/*
		 * No whitespace - look beyond the desired maximum
		 */
		for (int i = (length); i < upperBound; i++) {
			if (Character.isWhitespace(text.charAt(i))) {
				return text.substring(0, i);
			}
		}
		/*
		 * No whitespace, just truncate the text at the requested length
		 */
		return text.substring(0, length);
  }

	/**
	 * Trim specified charcater from front of string
	 * @param text Text
	 * @param character Character to remove
	 * @return Trimmed text
	 */
	public static String trimFront(String text, char character) {
		String 	normalizedText;
		int			index;

		if (StringUtils.isNull(text)) {
			return text;
		}

		normalizedText = text.trim();
		index	= 0;

		while (normalizedText.charAt(index) == character) {
			if (++index >= normalizedText.length()) break;
		}
		return normalizedText.substring(index).trim();
	}

	/**
	 * Trim specified charcater from end of string
	 * @param text Text
	 * @param character Character to remove
	 * @return Trimmed text
	 */
	public static String trimEnd(String text, char character) {
		String 	normalizedText;
		int			index;

		if (StringUtils.isNull(text)) {
			return text;
		}

		normalizedText = text.trim();
		index	= normalizedText.length() - 1;

		while (normalizedText.charAt(index) == character) {
			if (--index < 0) {
				return "";
			}
		}
		return normalizedText.substring(0, index + 1).trim();
	}

	/**
	 * Trim specified charcater from both ends of a String
	 * @param text Text
	 * @param character Character to remove
	 * @return Trimmed text
	 */
	public static String trimAll(String text, char character) {
		String normalizedText = trimFront(text, character);

		return trimEnd(normalizedText, character);
	}

	/**
	 * Capitlize each word in a string (journal titles, etc)
	 * @param text Text to inspect
	 * @return Capitalized text
	 */
	public static String capitalize(String text) {
		StringBuilder	resultText;
		char 					previousC;

    resultText	= new StringBuilder();
    previousC 	= '.';

    for (int i = 0;  i < text.length();  i++ ) {
       char c = text.charAt(i);

       if (Character.isLetter(c) && !Character.isLetter(previousC)) {
          resultText.append(Character.toUpperCase(c));
       } else {
          resultText.append(c);
       }
       previousC = c;
    }
    return resultText.toString();
  }

	/**
	 * Remove a character (or range of characters) from a string.  If the
	 * character is in a word, remove the entire word.
	 * @param source String to edit
	 * @param pattern Character (or range) to remove.  Range is a regular
	 *				expression: [\u002c-\u002f] or [,-/]
	 * @return Modified text
	 */
	public static String removeCharacterOrRangeAsWord(String source, String pattern) {
		return removeCharacterOrRange(source, pattern, true);
	}

	/**
	 * Remove a character (or range of characters) from a string.  If the
	 * character is at the start or end of a word, remove the character only
	 * (leave the word in place).
	 * @param source String to edit
	 * @param pattern Character (or range) to remove.  Range is a regular
	 *				expression: [\u002c-\u002f] or [,-/]
	 * @return Modified text
	 */
	public static String removeCharacterOrRangeAsCharacter(String source, String pattern) {
		return removeCharacterOrRange(source, pattern, false);
	}

	/*
	 * Helpers
	 */

	/**
	 * Remove a character (or range of characters) from a string.
	 * [optional] If a character is embedded in a word, remove the entire word.
	 * @param source String to edit
	 * @param pattern Character (or range) to remove.  Range is a regular
	 *				expression: [\u002c-\u002f] or [,-/]
	 * @param removeAsWord Always remove entire word?
	 * @return Modified text
	 */
	private static String removeCharacterOrRange(String source, String pattern,
								 														  boolean removeAsWord) {
		StringBuilder 	patternBuffer	= new StringBuilder();
		String 				rangePattern, result;

		patternBuffer.append('[');
		patternBuffer.append(pattern);
		patternBuffer.append(']');

		rangePattern = patternBuffer.toString();

		result = StringUtils.replace(source, "\\S+" + rangePattern + "\\S+", "");

		if (removeAsWord) {
			result = StringUtils.replace(result, rangePattern + "\\S+", "");
			result = StringUtils.replace(result, "\\S+" + rangePattern, "");
		}
		return StringUtils.replace(result, rangePattern, " ");
	}

	/*
	 * Test
	 */
  public static void main(String[] args)
                         throws Exception {
		log.debug(StringUtils.replace(args[0], args[1], args[2]));
	}
}


text:
package org.encog.ml.ea.rules;

import org.encog.ml.ea.genome.Genome;

/**
 * Defines a constraint.  A constraint specifies if a genome is invalid.
 */
public interface ConstraintRule {
	/**
	 * Is this genome valid?
	 * @param genome The genome.
	 * @return True, if valid.
	 */
	boolean isValid(Genome genome);
}


text:
WindUp
===========

WindUp allows you to do super simple background processing using Celluloid
Actors.

Installation
------------
```ruby
# Gemspec
gem 'wind_up'
```

Usage
-----

WindUp's `Delegator` allows us to use one queue to process multiple job types.
`Delegator#perform_with` will instantiate a class and run its `#perform`
method, passing any additional arguments provided.

Create a new `Delegator` queue using the WindUp Queue method. Use
`Delegator#perform_with` to send tasks to this queue. Asynchronous processing
is accomplished the same way you would with a WindUp Queue or Celluloid Pool;
`#sync`, `#async`, and `#future` all continue to work as expected.

```ruby
# Create a Delegator queue; these are equivalent
queue = WindUp::Delegator.queue size: 3
queue = WindUp.queue size: 3

# Create a job class
class GreetingJob
  def perform(name = "Bob")
    "Hello, #{name}!"
  end
end

# Send the delayed action to the Delegator queue
queue.perform_with GreetingJob, "Hurried Harry" # => "Hello, Hurried Harry!", completed synchronously
queue.async.perform_with GreetingJob, "Mellow Mary" # => nil, work completed in background
queue.future.perform_with GreetingJob, "Telepathic Tim" # => Celluloid::Future, with value "Hello, Telepathic Tim!"

# Store this queue for later usage
Celluloid::Actor[:background] = queue
# Later...
Celluloid::Actor[:background].async.perform_with GreetingJob, "Tina"

```

Tips
----

* Don't share state from your current thread with your Jobs!

  With WindUp, your jobs will be *eventually* processed, but we have no idea
  how long it'll be. As such, your jobs and messages should not share state.
  I.e., don't pass a User object; pass a user.id and recreates the user from
  the database within your job.

* Use JSON serializable arguments for your jobs

  Not only is it a good way to prevent yourself from accidentally sharing
  state (see previous point), but if you want to use a persistant job store
  you cannot pass in any objects that can't be dumped to JSON.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
const ghpages = require('gh-pages');

ghpages.publish('dist/angular-ngx-treeview', {
  repo: 'https://' + process.env.GH_TOKEN + '@github.com/' + process.env.TRAVIS_REPO_SLUG + '.git'
}, function (err) {
  if (err) {
    console.log(err);
  } else {
    console.log('published gh-pages');
  }
});


text:
//
//  YCAudioPlayer.m
//  TestAVAudioPlyer
//
//  Created by 超杨 on 15/11/9.
//  Copyright © 2015年 超杨. All rights reserved.
//

#import "YCAudioPlayer.h"
#import <AVFoundation/AVFoundation.h>
/** 为了让停止按钮的热区响应范围更大,如果有切图的可以直接设置item的image,不必导入此类 */
static BOOL knowHowToPlay = NO;
static const NSTimeInterval kBeginTransitionDuration = 1.0f;
static const NSTimeInterval kEndTransitionDuration = 0.6f;
static NSTimeInterval kTitleDisplayDutation = 10;
@interface YCAudioPlayer ()<AVAudioPlayerDelegate>
/** 主window */
@property (nonatomic, strong) UIWindow *keyWindow;
/** 起始时间 */
@property (weak, nonatomic) IBOutlet UILabel *benginTimeLbl;
@property (nonatomic, copy) NSString *beginTime;
/** 截止时间 */
@property (weak, nonatomic) IBOutlet UILabel *endTimeLbl;
@property (nonatomic, copy) NSString *endTime;
/** 进度条 */
@property (weak, nonatomic) IBOutlet UIProgressView *showPrograss;
/** 进度控制 */
@property (weak, nonatomic) IBOutlet UISlider *playControlPrograss;
/** 记录进度条是否被点击 */
@property (nonatomic, assign) BOOL prograssTapped;
/** 背景按钮 */
@property (nonatomic, strong) UIButton *bgView;
/** 播放器 */
@property (nonatomic, strong) AVAudioPlayer *avAudioPlayer;
/** 刷新进度条使用 */
@property (nonatomic, strong) NSTimer *timer;
/** 播放路径 */
@property (nonatomic, strong) NSURL *url;
/** 控制面板 */
@property (weak, nonatomic) IBOutlet UIButton *tapControlBtn;
/** 引导文字 */
@property (nonatomic, strong) IBOutlet UILabel *tipsLbl;
/** 工具条 */
@property (weak, nonatomic) IBOutlet UIToolbar *toolsBar;
/** 双击手势 */
@property (nonatomic, strong) UITapGestureRecognizer *tapGes;
/** 音乐标题 */
@property (weak, nonatomic) IBOutlet UILabel *musicTitle;
/** titleLeading约束 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *musicTitleLeading;

@end

@implementation YCAudioPlayer

+ (instancetype)audioPlayerWithUrl:(NSURL *)url{
    UINib *nib = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil];
    NSArray *arr = [nib instantiateWithOwner:nil options:nil];
    YCAudioPlayer *player = [arr firstObject];
    player.url = url;
    player.musicTitle.text = url.lastPathComponent;
//    player.musicTitle.text = @"daskjndsalnfjksdfnkasdbhjsabdgasjkdjnsahbdjasfn";
//    kTitleDisplayDutation = 1.2 * player.musicTitle.text.length;
    player.playControlPrograss.hidden = !player.prograssTapped;
    player.layer.cornerRadius = 5;
    player.layer.masksToBounds = YES;
    UITapGestureRecognizer *doubleTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:player action:@selector(prograssTap:)];
    player.tapGes = doubleTapGestureRecognizer;
    [doubleTapGestureRecognizer setNumberOfTapsRequired:2];
    [player.tapControlBtn addGestureRecognizer:doubleTapGestureRecognizer];
    player.endTimeLbl.text = player.endTime;
    /** 放大播放录制的声音的音量 */
    if (player.playRecordVoice) {
        AVAudioSession*audioSession=[AVAudioSession sharedInstance];
        NSError*err=nil;
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:&err];
    }
    return player;
}

#pragma mark 事件
- (IBAction)stopMusic:(UIButton *)sender {
//    NSLog(@"%s", __func__);
    [self.avAudioPlayer stop];
    [self.timer setFireDate:[NSDate distantFuture]];
    self.avAudioPlayer.currentTime = 0;
    self.showPrograss.progress = self.playControlPrograss.value = 0;
    self.benginTimeLbl.text = @"00:00";
}

- (IBAction)playMusic:(UIBarButtonItem *)sender {
//    NSLog(@"%s", __func__);
    /** 打开定时器 */
    [self.timer setFireDate:[NSDate date]];
    if (self.showPrograss.progress == 1) {
        self.showPrograss.progress = self.playControlPrograss.value = 0;
    }
    [self.avAudioPlayer play];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self.timer setFireDate:[NSDate date]];
//    });
}

- (IBAction)pauseMusic:(UIBarButtonItem *)sender {
//    NSLog(@"%s", __func__);
    [self.timer setFireDate:[NSDate distantFuture]];
    [self.avAudioPlayer pause];
}

- (IBAction)prograssTap:(UITapGestureRecognizer *)ges {
    knowHowToPlay = YES;
    self.prograssTapped = !self.prograssTapped;
    self.playControlPrograss.hidden = !self.prograssTapped;
    self.tipsLbl.text = @"长按滑动滑钮 双击隐藏滑钮";
    [self insertSubview:self.playControlPrograss aboveSubview:self.tipsLbl];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:1.0 animations:^{
            self.tipsLbl.alpha = 0.0f;
        } completion:^(BOOL finished) {
            self.tipsLbl.hidden = YES;
            [self.tipsLbl removeFromSuperview];
        }];
    });
}

- (IBAction)playPrograssControl:(UISlider *)sender {
    if (knowHowToPlay && !self.tipsLbl.hidden) {
        self.tipsLbl.hidden = YES;
    }
    self.showPrograss.progress = sender.value;
    self.avAudioPlayer.currentTime = sender.value * self.avAudioPlayer.duration;
    self.benginTimeLbl.text = self.beginTime;
//    self.endTimeLbl.text = [NSString stringWithFormat:@"%.2d:%.2d", (int)self.avAudioPlayer.duration/60, (int)self.avAudioPlayer.duration % 60];
}

#pragma mark 公开方法
- (void)showPlayerWithPlayerFrameOnWindow:(CGRect)frame{
    [self transitionWithType:@"rippleEffect" WithSubtype:kCATransitionFromBottom ForView:self.keyWindow duration:kBeginTransitionDuration];
    [self animateTitle];
    self.frame = frame;
    [self.keyWindow addSubview:self.bgView];
    [self.bgView addSubview:self];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self
                                            selector:@selector(playProgress)
                                            userInfo:nil repeats:YES];;
    [self.timer setFireDate:[NSDate distantFuture]];
    [UIView animateWithDuration:0.2f animations:^{
        self.bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6f];
    } completion:nil];

    if (!knowHowToPlay) {
        /** 添加提示框 */
        self.tipsLbl.frame = _tipsLbl.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height - self.toolsBar.frame.size.height);
        [UIView animateWithDuration:1.0 delay:2.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{

            self.tipsLbl.hidden = NO;
            self.tipsLbl.alpha = 0.6f;

        } completion:^(BOOL finished) {
            if (finished) {

            }
//
        }];
    }

}

#pragma 私有方法
- (void)hidePlayer {
    [self transitionWithType:@"suckEffect" WithSubtype:kCATransitionFromBottom ForView:self.keyWindow duration:kEndTransitionDuration];
    [UIView animateWithDuration:0.2f animations:^{
        self.bgView.alpha = 0.0f;
    } completion:^(BOOL finished) {
        [self.avAudioPlayer stop];
        [self.timer invalidate];
        [self.bgView removeFromSuperview];
    }];
}

//播放进度条刷新
- (void)playProgress
{
    //通过音频播放时长的百分比,给progressview进行赋值;
    if (self.avAudioPlayer.currentTime < self.avAudioPlayer.duration) {
        self.showPrograss.progress = self.playControlPrograss.value = self.avAudioPlayer.currentTime/self.avAudioPlayer.duration;
        self.benginTimeLbl.text = self.beginTime;
    }
//    else {
//        self.benginTimeLbl.text = @"00:00";
//        self.showPrograss.progress = self.playControlPrograss.value = 0;
//    }
}

#pragma CATransition动画
- (void) transitionWithType:(NSString *) type WithSubtype:(NSString *) subtype ForView:(UIView *)view duration:(CFTimeInterval)duration
{
    //创建CATransition对象
    CATransition *animation = [CATransition animation];
    //设置运动时间
    animation.duration = duration;
    //设置运动type
    animation.type = type;
    if (subtype != nil) {
        //设置子类
        animation.subtype = subtype;
    }
    //设置运动速度
    animation.timingFunction = UIViewAnimationOptionCurveEaseInOut;
    [view.layer addAnimation:animation forKey:@"animation"];
}

/** 标题可动 */
- (void)animateTitle {
    [self.musicTitle sizeToFit];
    /** 动画偏移量 */
    CGFloat OffsetX = 0.0f;
    CGFloat beginX = 0.0f;
    CGSize sizeName = [self.musicTitle.text sizeWithFont:self.musicTitle.font
                          constrainedToSize:CGSizeMake(MAXFLOAT, 0.0)
                              lineBreakMode:NSLineBreakByWordWrapping];
    CGFloat distance = fabs(sizeName.width - self.frame.size.width);
    CGFloat titleLeftInset = 5;
    if (self.frame.size.width > sizeName.width) {
        beginX = 0.0f + titleLeftInset;
        OffsetX = distance - titleLeftInset;
    } else {
        beginX = -distance - titleLeftInset;
        OffsetX = 0.0f + titleLeftInset;
    }

    self.musicTitleLeading.constant = beginX;
    [self.musicTitle layoutIfNeeded];
//    kTitleDisplayDutation = 1.2 * OffsetX;
    [UIView animateWithDuration:kTitleDisplayDutation delay:1 options:(UIViewAnimationOptionRepeat|UIViewAnimationOptionCurveLinear|UIViewAnimationOptionAutoreverse) animations:^{
        self.musicTitleLeading.constant = OffsetX;
        [self.musicTitle layoutIfNeeded];
    } completion:^(BOOL finished) {

    }];
}

#pragma mark 播放音频
//播放完成时调用的方法  (代理里的方法),需要设置代理才可以调用
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
//    [self.timer invalidate]; //NSTimer暂停   invalidate  使...无效;
    [self.timer setFireDate:[NSDate distantFuture]];
}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer*)player error:(NSError *)error{
    //解码错误执行的动作
}
- (void)audioPlayerBeginInteruption:(AVAudioPlayer*)player{
    //处理中断的代码
}
- (void)audioPlayerEndInteruption:(AVAudioPlayer*)player{
    //处理中断结束的代码
}
#pragma mark setter & getter
- (UIButton *)bgView
{
    if (_bgView == nil) {

        _bgView = [[UIButton alloc] init];
        _bgView.frame = self.keyWindow.bounds;
        _bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.0f];
        [_bgView addTarget:self action:@selector(hidePlayer) forControlEvents:(UIControlEventTouchUpInside)];

    }
    return _bgView;
}
- (UIWindow *)keyWindow
{
    if (_keyWindow == nil) {
        _keyWindow = [UIApplication sharedApplication].keyWindow;
    }
    return _keyWindow;
}

- (AVAudioPlayer *)avAudioPlayer
{
    if (_avAudioPlayer == nil) {
        _avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:self.url error:nil];
        //设置代理
        _avAudioPlayer.delegate = self;
        //设置初始音量大小
         _avAudioPlayer.volume = 1.0;
        //设置音乐播放次数  -1为一直循环
        _avAudioPlayer.numberOfLoops = 0;
        //预播放
        [_avAudioPlayer prepareToPlay];
    }
    return _avAudioPlayer;
}

- (UILabel *)tipsLbl
{
    if (_tipsLbl == nil) {
        _tipsLbl = [[UILabel alloc] init];
        _tipsLbl.layer.cornerRadius = 5;
        _tipsLbl.layer.masksToBounds = YES;
        _tipsLbl.layer.borderWidth = 1.0;
        _tipsLbl.layer.borderColor = [UIColor whiteColor].CGColor;
        _tipsLbl.backgroundColor = [UIColor blackColor];
        _tipsLbl.textColor = [UIColor whiteColor];
        _tipsLbl.textAlignment = NSTextAlignmentCenter;
        _tipsLbl.alpha = 0.0;
        _tipsLbl.hidden = YES;
        _tipsLbl.text = @"双击这里显示调整进度条";
//        [_tipsLbl addGestureRecognizer:self.tapGes];
        [self addSubview:_tipsLbl];
    }
    return _tipsLbl;
}
- (NSString *)beginTime
{
    return [NSString stringWithFormat:@"%.2d:%.2d", (int)self.avAudioPlayer.currentTime / 60 , (int)self.avAudioPlayer.currentTime % 60];
}

- (NSString *)endTime {
    return [NSString stringWithFormat:@"%.2d:%.2d", (int)self.avAudioPlayer.duration/60, (int)self.avAudioPlayer.duration % 60];
}
@end


text:
class SpecMetadata:
    def __init__(self, name) -> None:
        super().__init__()
        self.name = name
        self.owning_module = None
        self.features = []
        self.feature_blocks = {}
        self.feature_variables = {}
        self.where_functions = {}

    def set_owning_module(self, owning_module):
        self.owning_module = owning_module

    def add_feature(self, feature_name):
        self.features.append(feature_name)
        self.feature_blocks[feature_name] = []
        self.feature_variables[feature_name] = {}

    def add_feature_block(self, feature_name, block_type):
        self.feature_blocks[feature_name].append(block_type)

    def add_feature_variable(self, feature_name, variable_name):
        if not self.feature_variables[feature_name]:
            self.feature_variables[feature_name] = []
        self.feature_variables[feature_name].append(variable_name)

    def add_where_function(self, feature_name, where_function):
        self.where_functions[feature_name] = where_function


text:
package com.appdirect.sdk.exception;

/**
 * Exception thrown when the Marketplace cannot process requests
 */
public class UserSyncTooManyRequestsException extends RuntimeException {

	public UserSyncTooManyRequestsException(String message) {
		super(message);
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:app="http://schemas.android.com/apk/res-auto"
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:layout_marginLeft="35dp"
	android:layout_marginRight="35dp"
	android:padding="20dp"
	android:background="@drawable/dialog_background"
	android:orientation="vertical">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    	android:layout_gravity="center_horizontal"
    	android:gravity="center"
    	android:textSize="20sp"
    	android:textColor="@color/blue_text"
    	android:text="发现新版本"/>

    <View
        android:layout_width="match_parent"
    	android:layout_height="2px"
    	android:layout_marginTop="10dp"
    	android:background="@color/blue_text"/>
    <TextView
        android:id="@+id/tv_version"
        android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    	android:layout_marginTop="25dp"
    	android:textSize="16sp"
    	android:textColor="#555555"
    	android:text="最新版本:1.0.3"/>

    <TextView
        android:id="@+id/tv_size"
        android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    	android:visibility="gone"
    	android:layout_marginTop="8dp"
    	android:textSize="16sp"
    	android:textColor="#555555"
    	android:text="新版本大小:8.76MB"/>

    <TextView
        android:id="@+id/tv_time"
        android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    	android:visibility="gone"
    	android:layout_marginTop="8dp"
    	android:textSize="16sp"
    	android:textColor="#555555"
    	android:text="时间"/>
    <TextView
        android:id="@+id/tv_content"
        android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    	android:layout_marginTop="8dp"
    	android:textSize="16sp"
    	android:textColor="#555555"
    	android:text="更新内容:"/>

    <TextView
        android:id="@+id/tv_content_text"
        android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    	android:layout_marginTop="5dp"
    	android:textSize="14sp"
    	android:textColor="#777777"
    	android:text="1.增加红包相关功能\n2.keyi\n3.keyi\n4.keyi"/>

    <LinearLayout
        android:layout_width="match_parent"
    	android:layout_height="40dp"
    	android:orientation="horizontal"
    	android:layout_marginTop="25dp">

		<mehdi.sakout.fancybuttons.FancyButton
			android:id="@+id/btn_fouse"
			style="@style/bespeak_submit_btn"
			android:layout_weight="1"
			android:layout_height="wrap_content"
			android:padding="10dp"
			android:visibility="gone"
			app:fb_borderColor="@color/white"
			app:fb_borderWidth="0dp"
			app:fb_defaultColor="@color/blue_15a5"
			app:fb_focusColor="@color/blue_1447"
			app:fb_radius="5dp"
			app:fb_text="立即更新"
			app:fb_textSize="14sp"
			app:fb_textColor="@color/white" >
		</mehdi.sakout.fancybuttons.FancyButton>

		<mehdi.sakout.fancybuttons.FancyButton
			android:id="@+id/btn_sure"
			style="@style/bespeak_submit_btn"
			android:layout_width="0dp"
			android:layout_weight="1"
			android:layout_height="wrap_content"
			android:padding="12dp"
			android:visibility="visible"
			app:fb_borderColor="@color/white"
			app:fb_borderWidth="1dp"
			app:fb_defaultColor="@color/blue_text"
			app:fb_radius="5dp"
			app:fb_text="立即更新"
			app:fb_textSize="14sp"
			app:fb_textColor="@color/white" >
		</mehdi.sakout.fancybuttons.FancyButton>

		<mehdi.sakout.fancybuttons.FancyButton
			android:id="@+id/btn_cancle"
			style="@style/bespeak_submit_btn"
			android:layout_width="0dp"
			android:layout_weight="1"
			android:layout_height="wrap_content"
			android:layout_marginLeft="@dimen/dimen_10dp"
			android:padding="12dp"
			android:visibility="visible"
			app:fb_borderColor="@color/grey_default"
			app:fb_borderWidth="1dp"
			app:fb_defaultColor="@color/white"
			app:fb_focusColor="@color/grey_default"
			app:fb_radius="5dp"
			app:fb_text="以后再说"
			app:fb_textSize="14sp"
			app:fb_textColor="@color/blue_text" >
		</mehdi.sakout.fancybuttons.FancyButton>
    </LinearLayout>
</LinearLayout>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using Ploeh.Samples.Commerce.BasketPowerShellModel;

namespace Ploeh.Samples.Commerce.BasketPowerShell
{
    [Cmdlet(VerbsCommon.Remove, "Basket")]
    public class RemoveBasketCmdlet : Cmdlet
    {
        private readonly BasketManager basketManager;

        public RemoveBasketCmdlet()
        {
            this.basketManager = BasketContainer.ResolveManager();
        }

        [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
        public string Owner { get; set; }

        protected override void ProcessRecord()
        {
            this.basketManager.RemoveBasket(this.Owner);
        }
    }
}


text:
/**
 * npm modules
 */
var crypto = require('crypto');

exports.avatar = function(email){
	if(!email) return '';

	email = crypto.createHash('md5').update(email).digest('hex');

	return 'http://www.gravatar.com/avatar/' + email + '?s=92';
};


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>An article with code</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./../public/font-awesome-4.0.3/css/font-awesome.min.css">
    <link rel="stylesheet" href="./../public/styles.css">
    <link rel="stylesheet" href="./../public/prism/prism.css" />
    <link rel='stylesheet' href='http://fonts.googleapis.com/css?family=Open+Sans:400,800,700' type='text/css'>
    <link rel="shortcut icon" type="image/png" href="./../public/img/favicon.png" />

An article with code

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quidem temporibus eveniet sapiente aspernatur qui veniam ut molestiae mollitia! Voluptatum, unde molestias distinctio est sit omnis qui aperiam. Veniam, eum, assumenda.

module.exports = function(template, max) {
    template = template || 'partials/article-home.md';
    var articles = this.pages('articles', 'date');
    var html = '', to = max || articles.length;
    for(var i=0; i<to; i++) {
        var article = articles[i];
        html += this.template(template, {
            title: article.get('title'),
            preface: article.get('preface'),
            link: this.linkto(article),
            date: article.get('date'),
            tags: article.get('tags').join(', ')
        });
    }
    return html;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quidem temporibus eveniet sapiente aspernatur qui veniam ut molestiae mollitia! Voluptatum, unde molestias distinctio est sit omnis qui aperiam. Veniam, eum, assumenda.

module.exports = function(tag) {
    var template = 'partials/article-home.md';
    var articles = this.pages('articles', 'date');
    var html = '', to = articles.length;
    for(var i=0; i<to; i++) {
        var article = articles[i];
        var tags = article.get('tags');
        if(tags && tags.indexOf(tag) >= 0) {
            html += this.template(template, {
                title: article.get('title'),
                preface: article.get('preface'),
                link: this.linkto(article),
                date: article.get('date'),
                tags: article.get('tags').join(', ')
            });
        }
    }
    return html;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quidem temporibus eveniet sapiente aspernatur qui veniam ut molestiae mollitia! Voluptatum, unde molestias distinctio est sit omnis qui aperiam. Veniam, eum, assumenda.

About the Author:

name: John Black

interests: front-end, gaming

Latest blog posts:

 Dolor sit amet

 An article with code

 omnis qui aperiam

 Quidem temporibus eveniet sapiente aspernatur qui veniam ut molestiae mollitia!

 Quidem temporibus eveniet sapiente aspernatur qui veniam ut molestiae mollitia!

Tags:

                    JavaScript
                    Node.js
                    CSS3
                    HTML5
                    Design

 Home
                 All articles


text:
import frappe, random

settings = frappe._dict(
	prob = {
		"default": { "make": 0.6, "qty": (1,5) },
	}
)

def add_random_children(doc, fieldname, rows, randomize, unique=None):
	nrows = rows
	if rows > 1:
		nrows = random.randrange(1, rows)

	for i in range(nrows):
		d = {}
		for key, val in randomize.items():
			if isinstance(val[0], str):
				d[key] = get_random(*val)
			else:
				d[key] = random.randrange(*val)

		if unique:
			if not doc.get(fieldname, {unique:d[unique]}):
				doc.append(fieldname, d)
		else:
			doc.append(fieldname, d)

def get_random(doctype, filters=None, doc=False):
	condition = []
	if filters:
		for key, val in filters.items():
			condition.append("%s='%s'" % (key, str(val).replace("'", "\'")))
	if condition:
		condition = " where " + " and ".join(condition)
	else:
		condition = ""

	out = frappe.db.multisql({
		'mariadb': """select name from `tab%s` %s
		order by RAND() limit 1 offset 0""" % (doctype, condition),
		'postgres': """select name from `tab%s` %s
		order by RANDOM() limit 1 offset 0""" % (doctype, condition)
	})

	out = out and out[0][0] or None

	if doc and out:
		return frappe.get_doc(doctype, out)
	else:
		return out

def can_make(doctype):
	return random.random() < settings.prob.get(doctype, settings.prob["default"])["make"]

def how_many(doctype):
	return random.randrange(*settings.prob.get(doctype, settings.prob["default"])["qty"])


text:
module Volt
  class Environment
    def initialize
      # Use VOLT_ENV or RACK_ENV to set the environment
      @env = ENV['VOLT_ENV'] || ENV['RACK_ENV']

      # If we're in opal, we can set the env from JS before opal loads
      if RUBY_PLATFORM == 'opal'
        unless @env
          `if (window.start_env) {`
          @env = `window.start_env`
          `}`
        end
      end

      @env ||= 'development'
    end

    def ==(val)
      @env == val
    end

    def production?
      self.==('production')
    end

    def test?
      self.==('test')
    end

    def development?
      self.==('development')
    end

    def inspect
      @env.inspect
    end

    def to_s
      @env
    end
  end
end


text:
var AlienHunter = {};

AlienHunter.initialize = function(alienCount) {
  //Setup three.js WebGL renderer
  this.renderer = new THREE.WebGLRenderer({ antialias: true });
  this.renderer.setPixelRatio(window.devicePixelRatio);

  // Append the canvas element created by the renderer to document body element.
  document.body.appendChild(this.renderer.domElement);

  // Create a three.js scene.
  this.scene = new THREE.Scene();

  // Create a three.js camera.
  this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.3, 10000);

  // Apply VR headset positional data to camera.
  this.controls = new THREE.VRControls(this.camera);

  // Apply VR stereo rendering to renderer.
  this.effect = new THREE.VREffect(this.renderer);
  this.effect.setSize(window.innerWidth, window.innerHeight);

  // Create a VR manager helper to enter and exit VR mode.
  this.manager = new WebVRManager(this.renderer, this.effect);

  this.score = 0;
  this.alienMeshes = [];
  if(!alienCount) { alienCount = 5; }
  for(var i = 0;i<alienCount;i++) {
    this.alienMeshes.push(new Alien().build());
  }

  this.alienMeshes.forEach(function(alien) {
    this.scene.add(alien);
  }.bind(this));

  var ambientLight = new THREE.AmbientLight(0xbbbbbb);
  this.scene.add(ambientLight);

  this.raycaster = new THREE.Raycaster();
  this.raycaster.precision = 0.0005;

  var floorGeometry = new THREE.PlaneBufferGeometry(5000, 5000, 1, 1);
  var floorMaterial = new THREE.MeshBasicMaterial({
        color: 0x333333,
        side: THREE.DoubleSide
  });
  var floorMesh = new THREE.Mesh(floorGeometry, floorMaterial);
  floorMesh.rotation.x = Math.PI / -2; // rotate to be flat in the X-Z plane
  floorMesh.position.set(0, -100, 0);
  this.scene.add(floorMesh);

  var wallGeometry = new THREE.PlaneBufferGeometry(10000, 5000, 1, 1);
  var wallMaterial = new THREE.MeshBasicMaterial({
        color: 0x999999,
        side: THREE.DoubleSide
  });

  var wallMesh = new THREE.Mesh(wallGeometry, wallMaterial);
  wallMesh.rotation.x = Math.PI / -1; // rotate to be flat in the X-Z plane
  wallMesh.position.y = 2000;
  wallMesh.position.z = -5000;
  this.scene.add(wallMesh);

  var wallMesh2 = new THREE.Mesh(wallGeometry, wallMaterial);
  wallMesh2.rotation.x = Math.PI / -1; // rotate to be flat in the X-Z plane
  wallMesh2.position.y = 2000;
  wallMesh2.position.z = 5000;
  this.scene.add(wallMesh2);

  var sideWallMaterial = new THREE.MeshBasicMaterial({
        color: 0x777777,
        side: THREE.DoubleSide
  });
  var wallMesh3 = new THREE.Mesh(wallGeometry, sideWallMaterial);
  wallMesh3.rotation.x = Math.PI / -1; // rotate to be flat in the X-Z plane
  wallMesh3.rotation.y = Math.PI / -2; // rotate to be flat in the X-Z plane
  wallMesh3.position.x = 5000;
  wallMesh3.position.y = 2000;
  this.scene.add(wallMesh3);

  var wallMesh4 = new THREE.Mesh(wallGeometry, sideWallMaterial);
  wallMesh4.rotation.x = Math.PI / -1; // rotate to be flat in the X-Z plane
  wallMesh4.rotation.y = Math.PI / -2; // rotate to be flat in the X-Z plane
  wallMesh4.position.x = -5000;
  wallMesh4.position.y = 2000;
  this.scene.add(wallMesh4);

  var reticleGeometry = new THREE.SphereGeometry(0.02, 32, 32);
  this.reticleGreenMaterial = new THREE.MeshBasicMaterial({color: 0x00fc00});
  this.reticleRedMaterial = new THREE.MeshBasicMaterial({color: 0xff0000});
  this.reticleMesh = new THREE.Mesh(reticleGeometry, this.reticleGreenMaterial);
  this.reticleMesh.position.set(1,500,1);
  this.scene.add(this.reticleMesh);

  this.animate = function() {
    var coords = new THREE.Vector2();
    coords.x = 0;
    coords.y = 0;
    this.raycaster.setFromCamera(coords, this.camera);

    var intersections = this.raycaster.intersectObjects(this.alienMeshes);
    if(intersections.length > 0){
      this.reticleMesh.position.copy(intersections[0].point);
      this.reticleMesh.material = this.reticleGreenMaterial;
      var mesh = intersections[0].object;
      var alien = mesh.alien;
      if(alien.isAlien) {
        this.reticleMesh.material = this.reticleRedMaterial;
        alien.takeHit();
        if(alien.isDead()) {
          this.score += 1;
          var index = this.alienMeshes.indexOf(mesh);
          this.alienMeshes.splice(index, 1);
          this.scene.remove(mesh);
        }
      }
    } else {
      this.camera.updateProjectionMatrix();
      var zCamVec = new THREE.Vector3(0,0,-1);
      var position = this.camera.localToWorld(zCamVec);
      this.reticleMesh.position.set(position.x, position.y, position.z);
      this.reticleMesh.lookAt(this.camera.position);
      this.reticleMesh.material = this.reticleGreenMaterial;
    }

    var aliensRemaining = this.alienMeshes.some(function(mesh) {
      return mesh.alien.isAlien;
    });

    if(!aliensRemaining) {
      this.endGame();
    } else {
      var attacked = false;
      this.alienMeshes.forEach(function(mesh) {
        mesh.alien.advance();
        if(this.isAlienAttacking(mesh)) {
          if(mesh.alien.isAlien){
            this.score -= 2;
            attacked = true;
          } else {
            this.scene.remove(mesh);
          }
        };
      }.bind(this));

      if(attacked) {
        this.endGame({dead: true});
      } else {
        // Update VR headset position and apply to camera.
        this.controls.update();

        // Render the scene through the manager.
        this.manager.render(this.scene, this.camera);

        requestAnimationFrame(this.animate.bind(this));
      }
    }
  };

  this.isAlienAttacking = function(alien) {
    return alien.position.distanceTo(this.camera.position) <= 0.7;
  };

  this.endGame = function(options) {
    // Create a three.js scene.
    var endScene = new THREE.Scene();
    if(!this.endTextMesh) {
      var material = new THREE.MeshNormalMaterial();
      var endText = new THREE.TextGeometry('GAME OVER');
      this.endTextMesh = new THREE.Mesh(endText, material);
      this.endTextMesh.position.x = -400;
      this.endTextMesh.position.y = 100;
      this.endTextMesh.position.z = -500;
      this.endTextMesh.rotation.x = 0;
      this.endTextMesh.rotation.y = Math.PI * 2;

      if(options && options.dead && !this.deadTextMesh) {
        var deadText = new THREE.TextGeometry('YOU DIED');
        var deadMaterial = new THREE.MeshLambertMaterial({color: 0xff0000});
        this.deadTextMesh = new THREE.Mesh(deadText, deadMaterial);
        this.deadTextMesh.position.x = -300;
        this.deadTextMesh.position.y = 300;
        this.deadTextMesh.position.z = -500;
        this.deadTextMesh.rotation.x = Math.PI * .25;
        this.deadTextMesh.rotation.y = Math.PI * 2;
      }

      var scoreText = new THREE.TextGeometry('SCORE: ' + this.score);
      this.scoreTextMesh = new THREE.Mesh(scoreText, material);
      this.scoreTextMesh.position.x = -300;
      this.scoreTextMesh.position.y = -100;
      this.scoreTextMesh.position.z = -500;
      this.scoreTextMesh.rotation.x = 0;
      this.scoreTextMesh.rotation.y = Math.PI * 2;
    }

    var ambientLight = new THREE.AmbientLight(0xbbbbbb);
    endScene.add(ambientLight);
    endScene.add(this.endTextMesh);
    endScene.add(this.scoreTextMesh);
    if(this.deadTextMesh) {
      endScene.add(this.deadTextMesh);
    }

    this.controls.update();
    this.manager.render(endScene, this.camera);

    requestAnimationFrame(this.endGame.bind(this));
  };

  this.animate();
};


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

<title>The GNU Fortran Compiler: Hollerith constants support</title>

<meta name="description" content="The GNU Fortran Compiler: Hollerith constants support">
<meta name="keywords" content="The GNU Fortran Compiler: Hollerith constants support">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Option-Index.html#Option-Index" rel="index" title="Option Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Extensions-implemented-in-GNU-Fortran.html#Extensions-implemented-in-GNU-Fortran" rel="up" title="Extensions implemented in GNU Fortran">
<link href="Cray-pointers.html#Cray-pointers" rel="next" title="Cray pointers">
<link href="Implicitly-convert-LOGICAL-and-INTEGER-values.html#Implicitly-convert-LOGICAL-and-INTEGER-values" rel="prev" title="Implicitly convert LOGICAL and INTEGER values">

Next: Cray pointers, Previous: Implicitly convert LOGICAL and INTEGER values, Up: Extensions implemented in GNU Fortran   [Contents][Index]

6.1.13 Hollerith constants support

GNU Fortran supports Hollerith constants in assignments, function
arguments, and DATA and ASSIGN statements.  A Hollerith
constant is written as a string of characters preceded by an integer
constant indicating the character count, and the letter H or
h, and stored in bytewise fashion in a numeric (INTEGER,
REAL, or complex) or LOGICAL variable.  The
constant will be padded or truncated to fit the size of the variable in
which it is stored.

Examples of valid uses of Hollerith constants:

      complex*16 x(2)
      data x /16Habcdefghijklmnop, 16Hqrstuvwxyz012345/
      x(1) = 16HABCDEFGHIJKLMNOP
      call foo (4h abc)

Invalid Hollerith constants examples:

      integer*4 a
      a = 8H12345678 ! Valid, but the Hollerith constant will be truncated.
      a = 0H         ! At least one character is needed.

In general, Hollerith constants were used to provide a rudimentary
facility for handling character strings in early Fortran compilers,
prior to the introduction of CHARACTER variables in Fortran 77;
in those cases, the standard-compliant equivalent is to convert the
program to use proper character strings.  On occasion, there may be a
case where the intent is specifically to initialize a numeric variable
with a given byte sequence.  In these cases, the same result can be
obtained by using the TRANSFER statement, as in this example.

      INTEGER(KIND=4) :: a
      a = TRANSFER ("abcd", a)     ! equivalent to: a = 4Habcd


text:
How Hoodie Works
================

Hoodie has several components that work together in a somewhat atypical
way to deliver our promise of simplicity, out-of-the-box syncing, and
offline capability.

Everything starts in the frontend, with your app. This is your user
interface, your client side business logic, etc.

.. figure:: 1.jpg

The app code only talks to the Hoodie frontend API, never directly to
the server-side code, the database, or even the in-browser storage.

.. figure:: 2.jpg

Hoodie uses PouchDB for storing data locally, which uses IndexedDb or WebSQL,
whatever is available. Hoodie saves all data here first, before doing
anything else. So if you're offline, your data is safely stored locally.

.. figure:: 3.jpg

This, by itself, is already enough for an app. But if you want to save
your data remotely or send an email, for example, you'll need a bit
more.

Hoodie relies on CouchDB, the database that replicates. We use it to
sync data back and forth between the server and the clients, which is
something that CouchDB happens to be really good at.

.. figure:: 4.jpg

*A small aside: In CouchDB, each user has their own private database
which only they can access, so all user data is private by default. It
can be shared to the public if the user decides to do so, but it can't
happen by accident. This is why we'll often mention sharing and global
data as a separate feature.*

Behind the database, we have the actual server code in the form of a
small node.js core with various plugins running alongside it. These then
act upon the data in the CouchDB, which then replicates the changes back
to the clients.

.. figure:: 5.jpg

So Hoodie does **client ↔ database ↔ server** instead of the traditional
**client ↔ server ↔ database**, and this is where many of its
superpowers come from.

The clever bit is indicated by the dotted line in the middle; the
connection between clients and server can be severed at any time without
breaking the system. Frontend and backend never talk directly to each
other. They only leave each other messages and tasks. It's all very
loosely-coupled and event-based, and designed for eventual consistency.


text:
/**
 *
 * Product
 *
 */

import React, { PropTypes } from 'react';

// import styled from 'styled-components';

const Product = ({ name, colorRed, colorGreen, colorBlue }) => {
  return (

{name}

{colorRed ? '+' : '-'}

{colorGreen ? '+' : '-'}

{colorBlue ? '+' : '-'}

  );
};

Product.propTypes = {
  name: PropTypes.string,
  colorRed: PropTypes.bool,
  colorGreen: PropTypes.bool,
  colorBlue: PropTypes.bool,
};

export default Product;


text:
<?php

namespace Symfony\Component\Notifier\Bridge\Firebase\Notification;

use Symfony\Component\Notifier\Bridge\Firebase\FirebaseOptions;

/**
 * @experimental in 5.1
 */
final class IOSNotification extends FirebaseOptions
{
    public function sound(string $sound): self
    {
        $this->options['sound'] = $sound;

        return $this;
    }

    public function badge(string $badge): self
    {
        $this->options['badge'] = $badge;

        return $this;
    }

    public function clickAction(string $clickAction): self
    {
        $this->options['click_action'] = $clickAction;

        return $this;
    }

    public function subtitle(string $subtitle): self
    {
        $this->options['subtitle'] = $subtitle;

        return $this;
    }

    public function bodyLocKey(string $bodyLocKey): self
    {
        $this->options['body_loc_key'] = $bodyLocKey;

        return $this;
    }

    /**
     * @param string[] $bodyLocArgs
     */
    public function bodyLocArgs(array $bodyLocArgs): self
    {
        $this->options['body_loc_args'] = $bodyLocArgs;

        return $this;
    }

    public function titleLocKey(string $titleLocKey): self
    {
        $this->options['title_loc_key'] = $titleLocKey;

        return $this;
    }

    /**
     * @param string[] $titleLocArgs
     */
    public function titleLocArgs(array $titleLocArgs): self
    {
        $this->options['title_loc_args'] = $titleLocArgs;

        return $this;
    }
}


text:
from pydantic import validate_arguments, ValidationError

@validate_arguments
def repeat(s: str, count: int, *, separator: bytes = b'') -> bytes:
    b = s.encode()
    return separator.join(b for _ in range(count))

a = repeat('hello', 3)
print(a)

b = repeat('x', '4', separator=' ')
print(b)

try:
    c = repeat('hello', 'wrong')
except ValidationError as exc:
    print(exc)


text:
require 'net/http'
require 'json'
require 'ostruct'

require 'zoomba/error'
require 'zoomba/base'
require 'zoomba/collection'
require 'zoomba/configuration'
require 'zoomba/user'
require 'zoomba/version'

# :nodoc:
module Zoomba
  class << self
    attr_reader :configuration

    def configure
      @configuration ||= Configuration.new
      yield(@configuration)
    end

    def configuration
      if @configuration.nil? || !@configuration.complete?
        raise Zoomba::Error::NoConfiguration
      end
      @configuration
    end
  end
end


text:
<ion-view>
<ion-nav-title>Login</ion-nav-title>
    <ion-content>

                Username
                <input type="text" placeholder="Username" ng-model="username" id="username">

                Password
                <input type="password" placeholder="Password" ng-model="password" id="password">

        <button class="button button-block" ng-disabled="!ready" ng-click="login(username,password)">Log In</button>
    </ion-content>
    <ion-footer-bar ui-sref="signup" class="bar-dark">

Don't have an account ?

    </ion-footer-bar>
</ion-view>


text:
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Cloud.Tools.Common;
using Google.Cloud.Tools.ReleaseManager.History;
using LibGit2Sharp;
using System;
using System.IO;
using System.Linq;

namespace Google.Cloud.Tools.ReleaseManager
{
    public sealed class UpdateHistoryCommand : CommandBase
    {
        public UpdateHistoryCommand()
            : base("update-history", "Update the release history file for each changed version")
        {
        }

        protected override void ExecuteImpl(string[] args)
        {
            foreach (var diff in FindChangedVersions())
            {
                if (diff.NewVersion is null)
                {
                    Console.WriteLine($"{diff.Id} has been deleted; no history required.");
                }
                else
                {
                    Execute(diff.Id);
                }
            }
        }

        private static void Execute(string id)
        {
            var catalog = ApiCatalog.Load();
            var api = catalog[id];
            if (api.NoVersionHistory)
            {
                Console.WriteLine($"Skipping version history update for {id}");
                return;
            }
            string historyFilePath = HistoryFile.GetPathForPackage(id);

            var root = DirectoryLayout.DetermineRootDirectory();
            using var repo = new Repository(root);
            var releases = Release.LoadReleases(repo, catalog, api).ToList();
            var historyFile = HistoryFile.Load(historyFilePath);
            var sectionsInserted = historyFile.MergeReleases(releases, defaultMessage: null);
            if (sectionsInserted.Count != 0)
            {
                historyFile.Save(historyFilePath);
                var relativePath = Path.GetRelativePath(DirectoryLayout.DetermineRootDirectory(), historyFilePath)
                    .Replace('\\', '/');
                Console.WriteLine($"Updated version history file: {relativePath}");
                Console.WriteLine("New content:");
                Console.WriteLine();
                foreach (var line in sectionsInserted.SelectMany(section => section.Lines))
                {
                    Console.WriteLine(line);
                }
            }
        }
    }
}


text:
namespace Polarity {

void DoorBehavior::onBeginCollision(World *world, GameObject *self, b2Contact* contact) {
    GameObject *other = self->remoteObject(contact);
    if (other->getType() == GameObject::PLAYER) {
        ticksToNewWorld = (int) SDL_GetTicks() + 800;
        self->setAction(GameObject::OPEN);
        other->setAction(GameObject::OPEN);
        world->setBackgroundWorld(newWorld);
        //other->groundBody->SetGravityScale(0);
        //other->groundBody->SetLinearVelocity(
        //        (other->groundBody->GetPosition() - owner->groundBody->GetPosition()));
        std::cerr<<"We have CONTACT!"<< std::endl;
    }
}

void DoorBehavior::onEndCollision(World *world, GameObject *self, b2Contact* contact) {
}

void DoorBehavior::tick(World *world, GameObject *self) {
    if (!newWorld) {
        std::string dest = self->getProperty("level");
        if (!dest.empty()) {
            newWorld = world->loadNewWorld(dest);
        }
    }
    if (self->getAction() == GameObject::OPEN) {
        if ((int)SDL_GetTicks() > ticksToNewWorld && newWorld->isLoaded()) {
            world->switchToBackgroundWorld();
            self->setAction(GameObject::IDLE);
        }
    }
}

}


text:
package edu.gemini.dbTools.ephemeris

import edu.gemini.spModel.core.Coordinates
import edu.gemini.spModel.core.AlmostEqual
import edu.gemini.spModel.core.AlmostEqual._
import org.scalacheck.{Gen, Arbitrary}
import org.scalacheck.Arbitrary.arbitrary

import java.time.{LocalDateTime, Month, ZonedDateTime}
import java.time.ZoneOffset.UTC

import scalaz._, Scalaz._

trait Arbitraries extends edu.gemini.spModel.core.Arbitraries {
  implicit val arbEphemerisElement: Arbitrary[EphemerisElement] =
    Arbitrary {
      for {
        c <- arbitrary[Coordinates]
        r <- Gen.choose(-1000.0, 1000.0)
        d <- Gen.choose(-1000.0, 1000.0)
      } yield (c, r, d)
    }

  implicit val arbTime: Arbitrary[LocalDateTime] =
    Arbitrary {
      for {
        y <- Gen.choose(1000, 9999)
        m <- Gen.choose(1, 12).map(Month.of)
        d <- Gen.choose(1, 28)
        h <- Gen.choose(0, 23)
        n <- Gen.choose(0, 59)
      } yield LocalDateTime.of(y, m, d, h, n, 0)
    }

  implicit val arbEphemerisMap: Arbitrary[EphemerisMap] =
    Arbitrary {
      for {
        es <- arbitrary[List[EphemerisElement]]
        ts <- Gen.listOfN(es.size, arbitrary[LocalDateTime].map(ldt => ZonedDateTime.of(ldt, UTC).toInstant))
      } yield ==>>.fromList(ts.zip(es))
    }

  implicit val almostEqualEphemerisElement: AlmostEqual[EphemerisElement] =
    new AlmostEqual[(Coordinates, Double, Double)] {
      override def almostEqual(a: EphemerisElement, b: EphemerisElement): Boolean =
        (a._1 ~= b._1) && (a._2 ~= b._2) && (a._3 ~= b._3)
    }

  implicit val almostEqualEphemerisMap: AlmostEqual[EphemerisMap] =
    new AlmostEqual[EphemerisMap] {
      override def almostEqual(a: EphemerisMap, b: EphemerisMap): Boolean = {
        val aList = a.toList
        val bList = b.toList

        (aList.size == bList.size) && aList.zip(bList).forall {
          case ((aTime, aEph), (bTime, bEph)) =>
            (aTime === bTime) && (aEph ~= bEph)
        }
      }
    }

}


text:
'use strict'

module.exports = removegroup

function removegroup (graph, payload, conn) {
  this.logger.debug('GraphHandler', 'remove group', graph.id, conn)
// TODO
}


text:
SYNONYM

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

#### Published in
J. Bot. (Morot) 12:220. 1898

#### Original name
null

### Remarks
null


text:
This gem is no longer under development. Use [the MLB Stats API gem](//github.com/Fustrate/mlb_stats_api) instead.

# MLBGameday

TODO: Write a gem description

## Installation

Add this line to your application's Gemfile:

    gem 'mlb_gameday'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install mlb_gameday

## Usage

`require 'mlb_gameday' #=> true`
`gd2 = MLBGameday::API.new`

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package org.aplikator.client.local.widgets;

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

import org.aplikator.client.local.Aplikator;
import org.aplikator.server.NoRightForNewRecordException;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.Modal;
import org.gwtbootstrap3.client.ui.ModalBody;
import org.gwtbootstrap3.client.ui.ModalSize;
import org.gwtbootstrap3.client.ui.constants.ButtonSize;
import org.gwtbootstrap3.client.ui.constants.ModalBackdrop;
import org.gwtbootstrap3.client.ui.html.Div;
import org.gwtbootstrap3.client.ui.html.Span;
import org.gwtbootstrap3.extras.notify.client.constants.NotifyType;
import org.gwtbootstrap3.extras.notify.client.ui.Notify;
import org.gwtbootstrap3.extras.notify.client.ui.NotifySettings;
import org.jboss.errai.enterprise.client.jaxrs.api.ResponseException;

import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * @author vlahoda
 */
public class Messages {

    private static final int Z_INDEX = 99999;
    private static final int ERROR_TOP = 20;
    private static final int ERROR_OFFSET = 96;

    public static void success(String text) {
        NotifySettings go = NotifySettings.newSettings();
        go.setType(NotifyType.SUCCESS);
        go.setAllowDismiss(false);
        go.setZIndex(Z_INDEX);
        Notify.notify(text, go);
    }

    public static void error(String text) {
        NotifySettings go = NotifySettings.newSettings();
        go.setType(NotifyType.DANGER);
        go.setAllowDismiss(true);
        go.setDelay(0);
        go.setPauseOnMouseOver(true);
        go.setZIndex(Z_INDEX);
        Notify.notify(text, go);
    }

    public static void info(String text) {
        NotifySettings go = NotifySettings.newSettings();
        go.setType(NotifyType.INFO);
        go.setAllowDismiss(true);
        go.setDelay(10000);
        go.setZIndex(Z_INDEX);
        Notify.notify(text, go);
    }

    public static void warning(String text) {
        NotifySettings go = NotifySettings.newSettings();
        go.setType(NotifyType.WARNING);
        go.setDelay(10000);
        go.setPauseOnMouseOver(true);
        go.setAllowDismiss(false);
        go.setZIndex(Z_INDEX);
        Notify.notify(text, go);
    }

    public static void cleanAll() {
        Notify.hideAll();
    }

    public static void restError(String text, Throwable throwable) {
        try {
            throw throwable;
        } catch (ResponseException e) {
            Response response = e.getResponse();
            if (response.getText().contains("NoRightForNewRecordException")) {
                try {
                    String[] textPom = response.getText().split("##");
                    Messages.error(textPom[1]);
                } catch (Exception ex) {
                    showError(text, response.getText());
                }
            } else {
                showError(text, response.getText());
            }
        } catch (RuntimeException e) {
            Messages.error(text);
        } catch (Throwable t) {
            Messages.error(text + " " + t);
        }
    }

    /**
     * Simulate Notify behaviour for error messages, but with additional details button
     */
    private static List<Div> errorDivs = new ArrayList<>();
    private static void showError(final String message, final  String detail){
        final Div msg = new Div();
        msg.addStyleName("col-xs-11");
        msg.addStyleName("col-sm-4");
        msg.addStyleName("alert");
        msg.addStyleName("alert-danger");
        msg.addStyleName("animated");
        msg.addStyleName("fadeInDown");
        msg.getElement().setAttribute("data-notify","container");
        msg.getElement().setAttribute("data-notify-position","top-right");
        msg.getElement().getStyle().setZIndex(Z_INDEX-10);
        msg.getElement().getStyle().setDisplay(Style.Display.INLINE_BLOCK);
        msg.getElement().getStyle().setMargin(0, Style.Unit.PX);
        msg.getElement().getStyle().setPosition(Style.Position.FIXED);
        msg.getElement().getStyle().setTop(20, Style.Unit.PX);
        msg.getElement().getStyle().setRight(20, Style.Unit.PX);

        Button close = new Button("x");
        close.getElement().setAttribute("data-notify","dissmiss");
        close.getElement().setAttribute("type","button");
        close.getElement().setAttribute("aria-hidden","true");
        close.addStyleName("close");
        close.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                removeErrorDiv(msg);
            }
        });

        Button details = new Button(Aplikator.application.getConfigString("aplikator.error.details"));
        details.getElement().setAttribute("data-notify","dissmiss");
        details.getElement().setAttribute("type","button");
        details.getElement().setAttribute("aria-hidden","true");
        details.getElement().getStyle().setDisplay(Style.Display.BLOCK);
        details.setSize(ButtonSize.EXTRA_SMALL);
        details.setMarginTop(5);
        details.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                Modal dm = new Modal();
                dm.setSize(ModalSize.LARGE);
                dm.setTitle(message);
                dm.getElement().getStyle().setZIndex(Z_INDEX+10);
                dm.setClosable(true);
                dm.setDataBackdrop(ModalBackdrop.STATIC);
                ModalBody dmb = new ModalBody();
                dmb.add(new HTML(detail));
                dm.add(dmb);
                removeErrorDiv(msg);
                dm.show();
            }
        });
        msg.add(new Span(message));
        msg.add(close);
        msg.add(details);
        errorDivs.add(msg);
        repositionErrorDivs();
        RootPanel.get().add(msg);

    }
    private static void removeErrorDiv(Div msg){
        RootPanel.get().remove(msg);
        errorDivs.remove(msg);
        repositionErrorDivs();

    }

    private static void repositionErrorDivs(){
        for (int i = 0; i < errorDivs.size(); i++) {
            Div msg = errorDivs.get(i);
            msg.getElement().getStyle().setTop(ERROR_TOP+ i*ERROR_OFFSET, Style.Unit.PX);
        }
    }

}


text:
package org.winterblade.minecraft.harmony.entities.effects.matchers.calendar;

import net.minecraft.entity.Entity;
import org.winterblade.minecraft.harmony.api.BaseMatchResult;
import org.winterblade.minecraft.harmony.api.Component;
import org.winterblade.minecraft.harmony.api.PrioritizedObject;
import org.winterblade.minecraft.harmony.api.Priority;
import org.winterblade.minecraft.harmony.api.mobs.effects.IEntityMatcher;
import org.winterblade.minecraft.harmony.api.utility.CallbackMetadata;
import org.winterblade.minecraft.harmony.calendar.matchers.BaseDayOfYearMatcher;

import javax.annotation.Nullable;

/**
 * Created by Matt on 6/6/2016.
 */
@Component(properties = {"calendarMaxDayOfYear", "calendarProvider" })
@PrioritizedObject(priority = Priority.MEDIUM)
public class MaxDayOfYearMatcher extends BaseDayOfYearMatcher implements IEntityMatcher {
    public MaxDayOfYearMatcher(int day) {
        this(day, null);
    }

    public MaxDayOfYearMatcher(int day, @Nullable String provider) {
        super(Integer.MIN_VALUE, day, provider);
    }

    @Override
    public BaseMatchResult isMatch(Entity entity, CallbackMetadata iEntityMatcherData) {
        return matches(entity.getEntityWorld());
    }
}


text:
package org.apache.commons.pool2.impl;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.pool2.TestException;
import org.apache.commons.pool2.impl.TestGenericObjectPool.SimpleFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

/**
 */
public class TestBaseGenericObjectPool {

    BaseGenericObjectPool<String, TestException> pool;
    SimpleFactory factory;

    @BeforeEach
    public void setUp() {
        factory = new SimpleFactory();
        pool = new GenericObjectPool<>(factory);
    }

    @AfterEach
    public void tearDown() {
        pool.close();
        pool = null;
        factory = null;
    }

    @Test
    public void testActiveTimeStatistics() {
        for (int i = 0; i < 99; i++) { // must be < MEAN_TIMING_STATS_CACHE_SIZE
            pool.updateStatsReturn(Duration.ofMillis(i));
        }
        assertEquals(49, pool.getMeanActiveTimeMillis(), Double.MIN_VALUE);
    }

    @Test
    public void testBorrowWaitStatistics() {
        final DefaultPooledObject<String> p = (DefaultPooledObject<String>) factory.makeObject();
        pool.updateStatsBorrow(p, Duration.ofMillis(10));
        pool.updateStatsBorrow(p, Duration.ofMillis(20));
        pool.updateStatsBorrow(p, Duration.ofMillis(20));
        pool.updateStatsBorrow(p, Duration.ofMillis(30));
        assertEquals(20, pool.getMeanBorrowWaitTimeMillis(), Double.MIN_VALUE);
        assertEquals(30, pool.getMaxBorrowWaitTimeMillis(), 0);
    }

    public void testBorrowWaitStatisticsMax() {
        final DefaultPooledObject<String> p = (DefaultPooledObject<String>) factory.makeObject();
        assertEquals(0, pool.getMaxBorrowWaitTimeMillis(), Double.MIN_VALUE);
        pool.updateStatsBorrow(p, Duration.ZERO);
        assertEquals(0, pool.getMaxBorrowWaitTimeMillis(), Double.MIN_VALUE);
        pool.updateStatsBorrow(p, Duration.ofMillis(20));
        assertEquals(20, pool.getMaxBorrowWaitTimeMillis(), Double.MIN_VALUE);
        pool.updateStatsBorrow(p, Duration.ofMillis(20));
        assertEquals(20, pool.getMaxBorrowWaitTimeMillis(), Double.MIN_VALUE);
        pool.updateStatsBorrow(p, Duration.ofMillis(10));
        assertEquals(20, pool.getMaxBorrowWaitTimeMillis(), Double.MIN_VALUE);
    }

    @Test
    public void testEvictionTimerMultiplePools() throws InterruptedException {
        final AtomicIntegerFactory factory = new AtomicIntegerFactory();
        factory.setValidateLatency(50);
        try (final GenericObjectPool<AtomicInteger, RuntimeException> evictingPool = new GenericObjectPool<>(factory)) {
            evictingPool.setTimeBetweenEvictionRuns(Duration.ofMillis(100));
            evictingPool.setNumTestsPerEvictionRun(5);
            evictingPool.setTestWhileIdle(true);
            evictingPool.setMinEvictableIdleTime(Duration.ofMillis(50));
            for (int i = 0; i < 10; i++) {
                try {
                    evictingPool.addObject();
                } catch (final Exception e) {
                    e.printStackTrace();
                }
            }

            for (int i = 0; i < 1000; i++) {
                try (final GenericObjectPool<AtomicInteger, RuntimeException> nonEvictingPool = new GenericObjectPool<>(factory)) {
                    // empty
                }
            }

            Thread.sleep(1000);
            assertEquals(0, evictingPool.getNumIdle());
        }
    }
}


text:
class ImageComponent :
  public UIComponent
{
public:
  ImageComponent(void);
  virtual ~ImageComponent(void);
  virtual void paint(Gdiplus::Graphics& graphics);
  virtual void loadImage(std::wstring path);
private:
  std::shared_ptr<Gdiplus::Image> m_image;
};


text:
import unittest
import fizzbuzz
#from fizzbuzz import fizz_buzz

class fizzBuzzTest(unittest.TestCase):
	"""Testing the fizzbuzz"""
	""" """
	def test_returns_fizz_when_divisible_by_three(self):
		"""Test returns fizz when input is divisible by three"""
		self.assertEqual(fizzbuzz.fizz_buzz(3), 'fizz')
		#self.assertEqual(fizz_buzz(3), 'fizz')

	def test_returns_buzz_when_divisible_by_five(self):
		"""Test returns buzz when input is divisible by five"""
		self.assertEqual(fizzbuzz.fizz_buzz(3), 'fizz')
		#self.assertEqual(fizz_buzz(5), 'fizz')

#if __name__ == ('__main__'):
#	unittest()


text:
FILES=../experiment/*.dat*
for f in $FILES
do
    ln -s $f `basename $f`
done
context --path="$(cd ..; pwd)" board.tex


text:
'use strict';

angular.module('acrawlerApp')
  .config(function ($stateProvider) {
    $stateProvider
      .state('main', {
        url: '/',
        templateUrl: 'app/main/main.html',
        controller: 'MainCtrl'
      });
  });


text:
/*
 * BigUInt64Array description
 */

#if JERRY_BUILTIN_TYPEDARRAY
#if JERRY_BUILTIN_BIGINT

#define TYPEDARRAY_BYTES_PER_ELEMENT 8
#define TYPEDARRAY_MAGIC_STRING_ID LIT_MAGIC_STRING_BIGUINT64_ARRAY_UL
#define TYPEDARRAY_BUILTIN_ID ECMA_BUILTIN_ID_BIGUINT64ARRAY_PROTOTYPE
#include "ecma-builtin-typedarray-template.inc.h"

#endif /* JERRY_BUILTIN_BIGINT */
#endif /* JERRY_BUILTIN_TYPEDARRAY && JERRY_BUILTIN_BIGINT */


text:
<upgrade>
	<settings>
		<setting>
			<group>formatting</group>
			<module_id>core</module_id>
			<is_hidden>0</is_hidden>
			<type>boolean</type>
			<var_name>allow_html_in_activity_feed</var_name>
			<phrase_var_name>setting_allow_html_in_activity_feed</phrase_var_name>
			<ordering>6</ordering>
			<version_id>3.0.0beta3</version_id>
			<value>0</value>
		</setting>
		<setting>
			<group>server_settings</group>
			<module_id>core</module_id>
			<is_hidden>0</is_hidden>
			<type>boolean</type>
			<var_name>disable_hash_bang_support</var_name>
			<phrase_var_name>setting_disable_hash_bang_support</phrase_var_name>
			<ordering>14</ordering>
			<version_id>3.0.0beta3</version_id>
			<value>0</value>
		</setting>
	</settings>
	<phpfox_update_settings>
		<setting>
			<group>formatting</group>
			<module_id>core</module_id>
			<is_hidden>1</is_hidden>
			<type>boolean</type>
			<var_name>enabled_edit_area</var_name>
			<phrase_var_name>setting_enabled_edit_area</phrase_var_name>
			<ordering>5</ordering>
			<version_id>2.0.7</version_id>
			<value>0</value>
		</setting>
	</phpfox_update_settings>
	<phrases>
		<phrase>
			<module_id>core</module_id>
			<version_id>3.0.0beta3</version_id>
			<var_name>setting_allow_html_in_activity_feed</var_name>
			<added>1315510132</added>
			<value><![CDATA[<title>Allow HTML in Activity Feed</title><info>If you enable this option it will allow HTML in the activity feed and any comments connected to the feed.</info>]]></value>
		</phrase>
		<phrase>
			<module_id>core</module_id>
			<version_id>3.0.0beta3</version_id>
			<var_name>setting_disable_hash_bang_support</var_name>
			<added>1316512962</added>
			<value><![CDATA[<title>AJAX Browsing - Disable Hash-Bang URL</title><info>If you have "Site Wide AJAX Browsing" enabled we provide support for a function provided with HTML5 that allows the changing of the URL path without actually reloading the page. For browsers that do not have support for this function we use a fallback hash-bang URL. If you do not want to allow the usage of hash-bang URL's enable this option and for browsers that do not have HTML 5 support will not be able to use your sites AJAX browsing functionality. Currently all IE browsers do not have support for this HTML5 function so they by default use the fallback method.</info>]]></value>
		</phrase>
		<phrase>
			<module_id>core</module_id>
			<version_id>3.0.0beta3</version_id>
			<var_name>search_dot</var_name>
			<added>1316530308</added>
			<value>Search...</value>
		</phrase>
	</phrases>
</upgrade>


text:
import time
import urllib2
import socket
from lxml import html
from piratebay.utils import open_url_with_request
from piratebay.page import SearchPage, UserPage, PageCollection, PageItem
from piratebay.constants import search_page_url, user_page_url, order
from piratebay.parser import TorrentInfoParser

def search_main(term, category=0, page=0, order_by=order["seeders"],\
                timeout=None):
    """Search the main piratebay website for the term 'term'.

    *Arguments*
        term = search with term.
        category = category from piratebay.categories.categories dict.
        page = the number of the search page to visit.
        order_by = the order of which piratebay should order it's results.
                    (default being piratebay.page.order["seeders"])
    *Returns*
        a SearchPage() object.
    """
    if page < 0:
        page = 0
    form_data = {"q": term, "category": category,
                "page": page, "orderby": order_by}
    url = open_url_with_request(search_page_url, form_data=form_data,\
                                timeout=timeout)
    doc = html.parse(url).getroot()
    return SearchPage(doc, form_data=form_data)

def search_user(user, page=0, order_by=order["seeders"], timeout=None):
    """Search the entries on a users page on piratebay.

    It is not an actual search, it basically just queries the users page
    to get all the releases from that user. Then order it by seeders as
    default, but can be changed with the order_by argument.
    """
    url = open_url_with_request(user_page_url % (user, page, order_by),\
                                timeout=timeout)
    doc = html.parse(url).getroot()
    return UserPage(doc)

def search_main_pages(term, pages, category=0, order_by=order["seeders"],\
                        timeout=None, wait_time=3, callback=None):
    """Search the main piratebay website for the term 'term'.

    Search all the page numbers in `pages', and wait for `wait_time'
    seconds between each request. If callback is specified then call
    the callback with the page object. If timeout is specified,
    time out a request after `timeout' seconds.
    """
    collection = PageCollection()
    for page_number in pages:
        try:
            page = search_main(term, page=page_number, category=category,\
                                order_by=order_by, timeout=timeout)
        except socket.timeout, err:
            continue
        except urllib2.URLError, err:
            continue
        if callback is not None:
            callback(page)
        collection.add_page(page)
        # Don't sleep if we're at the last page
        if page_number != pages[-1]:
            time.sleep(wait_time)
    return collection

def query_torrent_info_page(url, timeout=None):
    """Query a torrent info page.

    Queries a torrent info page, returns a PageItem object with the result. It
    has for example the description of the torrent, if the uploader is a
    trusted user and alot more.
    """
    data = open_url_with_request(url, timeout)
    document = html.parse(data).getroot()
    parser = TorrentInfoParser(document)
    return PageItem(parser.run())