text:
namespace charls {

// Default threshold values for JPEG-LS statistical modeling as defined in ISO/IEC 14495-1, Table C.3
// for the case MAXVAL = 255 and NEAR = 0.
// Can be overridden at compression time, however this is rarely done.
constexpr int default_threshold1{3};  // BASIC_T1
constexpr int default_threshold2{7};  // BASIC_T2
constexpr int default_threshold3{21}; // BASIC_T3

constexpr int default_reset_value{64}; // Default RESET value as defined in ISO/IEC 14495-1, table C.2

constexpr int maximum_component_count{255};
constexpr int minimum_bits_per_sample{2};
constexpr int maximum_bits_per_sample{16};
constexpr int maximum_near_lossless{255};
constexpr int32_t minimum_application_data_id{0};
constexpr int32_t maximum_application_data_id{15};

constexpr int max_k_value{16}; // This is an implementation limit (theoretical limit is 32)

constexpr int compute_maximum_near_lossless(const int maximum_sample_value) noexcept
{
    return std::min(maximum_near_lossless, maximum_sample_value / 2); // As defined by ISO/IEC 14495-1, C.2.3
}

// Computes the initial value for A. See ISO/IEC 14495-1, A.8, step 1.d and A.2.1
constexpr int32_t initialization_value_for_a(const int32_t range) noexcept
{
    return std::max(2, (range + 32) / 64);
}

// ISO/IEC 14495-1, section 4.8.1 defines the SPIFF version numbers to be used for the SPIFF header in combination with
// JPEG-LS.
constexpr uint8_t spiff_major_revision_number{2};
constexpr uint8_t spiff_minor_revision_number{};

constexpr uint8_t spiff_end_of_directory_entry_type{1};

// The size of a SPIFF header when serialized to a JPEG byte stream.
constexpr size_t spiff_header_size_in_bytes{34};

// The special value to indicate that the stride should be calculated.
constexpr size_t auto_calculate_stride{};

// The size in bytes of the segment length field.
constexpr size_t segment_length_size{sizeof(uint16_t)};

// The maximum size of the data bytes that fit in a segment.
constexpr size_t segment_max_data_size{std::numeric_limits<uint16_t>::max() - segment_length_size};

// Number of bits in an int32_t data type.
constexpr size_t int32_t_bit_count{sizeof(int32_t) * 8};

} // namespace charls


text:
/**
 *  Test Lock
 */
package com.ciaoshen.thinkinjava.chapter21;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;

public class TestLock{
    private volatile int num=0;
    public void increment(){
        //synchronized(this){   //可以锁这里
            num++; Thread.yield(); num++;
        //}
    }
    public int getNum(){
        //synchronized(this){   //可以锁这里
            return num;
        //}
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.Network.Models
{
    /// <summary> The request for a VIP swap. </summary>
    public partial class LoadBalancerVipSwapRequest
    {
        /// <summary> Initializes a new instance of LoadBalancerVipSwapRequest. </summary>
        public LoadBalancerVipSwapRequest()
        {
            FrontendIPConfigurations = new ChangeTrackingList<LoadBalancerVipSwapRequestFrontendIPConfiguration>();
        }

        /// <summary> A list of frontend IP configuration resources that should swap VIPs. </summary>
        public IList<LoadBalancerVipSwapRequestFrontendIPConfiguration> FrontendIPConfigurations { get; }
    }
}


text:
<!DOCTYPE HTML>

	<meta charset="UTF-8">
	<title>C4</title>
	<link rel="stylesheet" href="css/query.css" type="text/css">

	<?php
	include_once "header.php";
	?>

Welcome, please select a query to interrogate the networks:

				<?php
				if($settings['gene_set']){
				 echo 'Query a Gene Set
';
				}
				if($settings['module']){
					echo 'Identify Genes by Modular Membership
';
				}
				if($settings['expression']){
					echo 'View Gene Expression
';
				}
				if($settings['expression_prof']){
					echo 'Identify Genes by Expression Profile
';
				}
				if($settings['ortholog']){
					echo 'Query Orthologs
';
				}
				if($settings['annotation']){
				 	echo 'Query Annotation
';
				}
				if($settings['functional']){
					echo 'View Functional Enrichment
';
				}
				if($settings['plasticity']){
					echo 'Query Genes by Plasticity
';
					echo 'Compare Gene Expression';
				}
				?>

	<?php
	include_once "footer.php";
	?>


text:
@interface SMLPetsTableViewController : UITableViewController

@end


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
<meta charset="utf-8">
<title>Phing API Documentation » phing\tasks\ext\creole</title>
<meta name="author" content="Mike van Riel">
<meta name="description" content="">
<link href="../css/template.css" rel="stylesheet" media="all">
<link rel="shortcut icon" href="../img/favicon.ico">
<link rel="apple-touch-icon" href="../img/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="../img/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="../img/apple-touch-icon-114x114.png">

Phing API Documentation

                                    API Documentation

Packages

 Default

 JSMin

 Parallel

 Phing

 phing

                                    Charts

 Class hierarchy diagram

                                    Reports

 Errors
                2573

 Markers

todo
                15

fixme
                8

 Deprecated elements
                11

Back to top

                            Javascript is disabled; several features are only available
                            if Javascript is enabled.

<button class="btn details" title="Show descriptions and method names"></button><button class="btn simple" title="Show only method names"></button>

 Packages

creole

 Classes

CreoleSQLExecTask

SQLExecTransaction

\
phing

\tasks

\ext

\creole

 Classes and interfaces

CreoleSQLExecTask¶

Executes a series of SQL statements on a database using Creole.

« More »

SQLExecTransaction¶

"Inner" class that contains the definition of a new transaction element.

« More »

            Template is built using Twitter Bootstrap 2 and icons provided by Glyphicons.

            Documentation is powered by phpDocumentor 2.0.0a11 and

            generated on 2012-11-20T07:50:15+01:00.


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <php.h>
#include <ext/standard/base64.h>
#include <Zend/zend_interfaces.h>
#include <Zend/zend_operators.h>
#include <ext/standard/php_var.h>
#if PHP_VERSION_ID >= 70000
#include <zend_smart_str.h>
#else
#include <ext/standard/php_smart_str.h>
#endif

#include "phongo_compat.h"
#include "php_phongo.h"

#define PHONGO_BINARY_UUID_SIZE 16

zend_class_entry* php_phongo_binary_ce;

/* Initialize the object and return whether it was successful. An exception will
 * be thrown on error. */
static bool php_phongo_binary_init(php_phongo_binary_t* intern, const char* data, phongo_zpp_char_len data_len, phongo_long type TSRMLS_DC) /* {{{ */
{
	if (type < 0 || type > UINT8_MAX) {
		phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected type to be an unsigned 8-bit integer, %" PHONGO_LONG_FORMAT " given", type);
		return false;
	}

	if ((type == BSON_SUBTYPE_UUID_DEPRECATED || type == BSON_SUBTYPE_UUID) && data_len != PHONGO_BINARY_UUID_SIZE) {
		phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected UUID length to be %d bytes, %d given", PHONGO_BINARY_UUID_SIZE, data_len);
		return false;
	}

	intern->data     = estrndup(data, data_len);
	intern->data_len = data_len;
	intern->type     = (uint8_t) type;

	return true;
} /* }}} */

/* Initialize the object from a HashTable and return whether it was successful.
 * An exception will be thrown on error. */
static bool php_phongo_binary_init_from_hash(php_phongo_binary_t* intern, HashTable* props TSRMLS_DC) /* {{{ */
{
#if PHP_VERSION_ID >= 70000
	zval *data, *type;

	if ((data = zend_hash_str_find(props, "data", sizeof("data") - 1)) && Z_TYPE_P(data) == IS_STRING &&
		(type = zend_hash_str_find(props, "type", sizeof("type") - 1)) && Z_TYPE_P(type) == IS_LONG) {

		return php_phongo_binary_init(intern, Z_STRVAL_P(data), Z_STRLEN_P(data), Z_LVAL_P(type) TSRMLS_CC);
	}
#else
	zval **data, **type;

	if (zend_hash_find(props, "data", sizeof("data"), (void**) &data) == SUCCESS && Z_TYPE_PP(data) == IS_STRING &&
		zend_hash_find(props, "type", sizeof("type"), (void**) &type) == SUCCESS && Z_TYPE_PP(type) == IS_LONG) {

		return php_phongo_binary_init(intern, Z_STRVAL_PP(data), Z_STRLEN_PP(data), Z_LVAL_PP(type) TSRMLS_CC);
	}
#endif

	phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"data\" string and \"type\" integer fields", ZSTR_VAL(php_phongo_binary_ce->name));
	return false;
} /* }}} */

/* {{{ proto void MongoDB\BSON\Binary::__construct(string $data, int $type)
   Construct a new BSON binary type */
static PHP_METHOD(Binary, __construct)
{
	php_phongo_binary_t* intern;
	zend_error_handling  error_handling;
	char*                data;
	phongo_zpp_char_len  data_len;
	phongo_long          type;

	zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
	intern = Z_BINARY_OBJ_P(getThis());

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sl", &data, &data_len, &type) == FAILURE) {
		zend_restore_error_handling(&error_handling TSRMLS_CC);
		return;
	}
	zend_restore_error_handling(&error_handling TSRMLS_CC);

	php_phongo_binary_init(intern, data, data_len, type TSRMLS_CC);
} /* }}} */

/* {{{ proto void MongoDB\BSON\Binary::__set_state(array $properties)
*/
static PHP_METHOD(Binary, __set_state)
{
	php_phongo_binary_t* intern;
	HashTable*           props;
	zval*                array;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) {
		RETURN_FALSE;
	}

	object_init_ex(return_value, php_phongo_binary_ce);

	intern = Z_BINARY_OBJ_P(return_value);
	props  = Z_ARRVAL_P(array);

	php_phongo_binary_init_from_hash(intern, props TSRMLS_CC);
} /* }}} */

/* {{{ proto string MongoDB\BSON\Binary::__toString()
   Return the Binary's data string. */
static PHP_METHOD(Binary, __toString)
{
	php_phongo_binary_t* intern;

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	intern = Z_BINARY_OBJ_P(getThis());

	PHONGO_RETURN_STRINGL(intern->data, intern->data_len);
} /* }}} */

/* {{{ proto string MongoDB\BSON\Binary::getData()
*/
static PHP_METHOD(Binary, getData)
{
	php_phongo_binary_t* intern;

	intern = Z_BINARY_OBJ_P(getThis());

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	PHONGO_RETURN_STRINGL(intern->data, intern->data_len);
} /* }}} */

/* {{{ proto integer MongoDB\BSON\Binary::getType()
*/
static PHP_METHOD(Binary, getType)
{
	php_phongo_binary_t* intern;

	intern = Z_BINARY_OBJ_P(getThis());

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	RETURN_LONG(intern->type);
} /* }}} */

/* {{{ proto array MongoDB\BSON\Binary::jsonSerialize()
*/
static PHP_METHOD(Binary, jsonSerialize)
{
	php_phongo_binary_t* intern;
	char                 type[3];
	int                  type_len;

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	intern = Z_BINARY_OBJ_P(getThis());

	array_init_size(return_value, 2);

#if PHP_VERSION_ID >= 70000
	{
		zend_string* data = php_base64_encode((unsigned char*) intern->data, intern->data_len);
		ADD_ASSOC_STRINGL(return_value, "$binary", ZSTR_VAL(data), ZSTR_LEN(data));
		zend_string_free(data);
	}
#else
	{
		int            data_len = 0;
		unsigned char* data     = php_base64_encode((unsigned char*) intern->data, intern->data_len, &data_len);
		ADD_ASSOC_STRINGL(return_value, "$binary", (char*) data, data_len);
		efree(data);
	}
#endif

	type_len = snprintf(type, sizeof(type), "%02x", intern->type);
	ADD_ASSOC_STRINGL(return_value, "$type", type, type_len);
} /* }}} */

/* {{{ proto string MongoDB\BSON\Binary::serialize()
*/
static PHP_METHOD(Binary, serialize)
{
	php_phongo_binary_t* intern;
	ZVAL_RETVAL_TYPE     retval;
	php_serialize_data_t var_hash;
	smart_str            buf = { 0 };

	intern = Z_BINARY_OBJ_P(getThis());

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

#if PHP_VERSION_ID >= 70000
	array_init_size(&retval, 2);
	ADD_ASSOC_STRINGL(&retval, "data", intern->data, intern->data_len);
	ADD_ASSOC_LONG_EX(&retval, "type", intern->type);
#else
	ALLOC_INIT_ZVAL(retval);
	array_init_size(retval, 2);
	ADD_ASSOC_STRINGL(retval, "data", intern->data, intern->data_len);
	ADD_ASSOC_LONG_EX(retval, "type", intern->type);
#endif

	PHP_VAR_SERIALIZE_INIT(var_hash);
	php_var_serialize(&buf, &retval, &var_hash TSRMLS_CC);
	smart_str_0(&buf);
	PHP_VAR_SERIALIZE_DESTROY(var_hash);

	PHONGO_RETVAL_SMART_STR(buf);

	smart_str_free(&buf);
	zval_ptr_dtor(&retval);
} /* }}} */

/* {{{ proto void MongoDB\BSON\Binary::unserialize(string $serialized)
*/
static PHP_METHOD(Binary, unserialize)
{
	php_phongo_binary_t* intern;
	zend_error_handling  error_handling;
	char*                serialized;
	phongo_zpp_char_len  serialized_len;
#if PHP_VERSION_ID >= 70000
	zval props;
#else
	zval* props;
#endif
	php_unserialize_data_t var_hash;

	intern = Z_BINARY_OBJ_P(getThis());

	zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &serialized, &serialized_len) == FAILURE) {
		zend_restore_error_handling(&error_handling TSRMLS_CC);
		return;
	}
	zend_restore_error_handling(&error_handling TSRMLS_CC);

#if PHP_VERSION_ID < 70000
	ALLOC_INIT_ZVAL(props);
#endif
	PHP_VAR_UNSERIALIZE_INIT(var_hash);
	if (!php_var_unserialize(&props, (const unsigned char**) &serialized, (unsigned char*) serialized + serialized_len, &var_hash TSRMLS_CC)) {
		zval_ptr_dtor(&props);
		phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE TSRMLS_CC, "%s unserialization failed", ZSTR_VAL(php_phongo_binary_ce->name));

		PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
		return;
	}
	PHP_VAR_UNSERIALIZE_DESTROY(var_hash);

#if PHP_VERSION_ID >= 70000
	php_phongo_binary_init_from_hash(intern, HASH_OF(&props) TSRMLS_CC);
#else
	php_phongo_binary_init_from_hash(intern, HASH_OF(props) TSRMLS_CC);
#endif
	zval_ptr_dtor(&props);
} /* }}} */

/* {{{ MongoDB\BSON\Binary function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Binary___construct, 0, 0, 2)
	ZEND_ARG_INFO(0, data)
	ZEND_ARG_INFO(0, type)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(ai_Binary___set_state, 0, 0, 1)
	ZEND_ARG_ARRAY_INFO(0, properties, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(ai_Binary_unserialize, 0, 0, 1)
	ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(ai_Binary_void, 0, 0, 0)
ZEND_END_ARG_INFO()

static zend_function_entry php_phongo_binary_me[] = {
	/* clang-format off */
	PHP_ME(Binary, __construct, ai_Binary___construct, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Binary, __set_state, ai_Binary___set_state, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
	PHP_ME(Binary, __toString, ai_Binary_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Binary, jsonSerialize, ai_Binary_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Binary, serialize, ai_Binary_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Binary, unserialize, ai_Binary_unserialize, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Binary, getData, ai_Binary_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Binary, getType, ai_Binary_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_FE_END
	/* clang-format on */
};
/* }}} */

/* {{{ MongoDB\BSON\Binary object handlers */
static zend_object_handlers php_phongo_handler_binary;

static void php_phongo_binary_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
	php_phongo_binary_t* intern = Z_OBJ_BINARY(object);

	zend_object_std_dtor(&intern->std TSRMLS_CC);

	if (intern->data) {
		efree(intern->data);
	}

	if (intern->properties) {
		zend_hash_destroy(intern->properties);
		FREE_HASHTABLE(intern->properties);
	}

#if PHP_VERSION_ID < 70000
	efree(intern);
#endif
} /* }}} */

static phongo_create_object_retval php_phongo_binary_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
	php_phongo_binary_t* intern = NULL;

	intern = PHONGO_ALLOC_OBJECT_T(php_phongo_binary_t, class_type);

	zend_object_std_init(&intern->std, class_type TSRMLS_CC);
	object_properties_init(&intern->std, class_type);

#if PHP_VERSION_ID >= 70000
	intern->std.handlers = &php_phongo_handler_binary;

	return &intern->std;
#else
	{
		zend_object_value retval;
		retval.handle   = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_binary_free_object, NULL TSRMLS_CC);
		retval.handlers = &php_phongo_handler_binary;

		return retval;
	}
#endif
} /* }}} */

static int php_phongo_binary_compare_objects(zval* o1, zval* o2 TSRMLS_DC) /* {{{ */
{
	php_phongo_binary_t *intern1, *intern2;

	intern1 = Z_BINARY_OBJ_P(o1);
	intern2 = Z_BINARY_OBJ_P(o2);

	/* MongoDB compares binary types first by the data length, then by the type
	 * byte, and finally by the binary data itself. */
	if (intern1->data_len != intern2->data_len) {
		return intern1->data_len < intern2->data_len ? -1 : 1;
	}

	if (intern1->type != intern2->type) {
		return intern1->type < intern2->type ? -1 : 1;
	}

	return zend_binary_strcmp(intern1->data, intern1->data_len, intern2->data, intern2->data_len);
} /* }}} */

static HashTable* php_phongo_binary_get_gc(zval* object, phongo_get_gc_table table, int* n TSRMLS_DC) /* {{{ */
{
	*table = NULL;
	*n     = 0;

	return Z_BINARY_OBJ_P(object)->properties;
} /* }}} */

static HashTable* php_phongo_binary_get_properties_hash(zval* object, bool is_debug TSRMLS_DC) /* {{{ */
{
	php_phongo_binary_t* intern;
	HashTable*           props;

	intern = Z_BINARY_OBJ_P(object);

	PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_debug, intern, props, 2);

	if (!intern->data) {
		return props;
	}

#if PHP_VERSION_ID >= 70000
	{
		zval data, type;

		ZVAL_STRINGL(&data, intern->data, intern->data_len);
		zend_hash_str_update(props, "data", sizeof("data") - 1, &data);

		ZVAL_LONG(&type, intern->type);
		zend_hash_str_update(props, "type", sizeof("type") - 1, &type);
	}
#else
	{
		zval *data, *type;

		MAKE_STD_ZVAL(data);
		ZVAL_STRINGL(data, intern->data, intern->data_len, 1);
		zend_hash_update(props, "data", sizeof("data"), &data, sizeof(data), NULL);

		MAKE_STD_ZVAL(type);
		ZVAL_LONG(type, intern->type);
		zend_hash_update(props, "type", sizeof("type"), &type, sizeof(type), NULL);
	}
#endif

	return props;
} /* }}} */

static HashTable* php_phongo_binary_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
	*is_temp = 1;
	return php_phongo_binary_get_properties_hash(object, true TSRMLS_CC);
} /* }}} */

static HashTable* php_phongo_binary_get_properties(zval* object TSRMLS_DC) /* {{{ */
{
	return php_phongo_binary_get_properties_hash(object, false TSRMLS_CC);
} /* }}} */
/* }}} */

void php_phongo_binary_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
	zend_class_entry ce;

	INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Binary", php_phongo_binary_me);
	php_phongo_binary_ce                = zend_register_internal_class(&ce TSRMLS_CC);
	php_phongo_binary_ce->create_object = php_phongo_binary_create_object;
	PHONGO_CE_FINAL(php_phongo_binary_ce);

	zend_class_implements(php_phongo_binary_ce TSRMLS_CC, 1, php_phongo_binary_interface_ce);
	zend_class_implements(php_phongo_binary_ce TSRMLS_CC, 1, php_phongo_json_serializable_ce);
	zend_class_implements(php_phongo_binary_ce TSRMLS_CC, 1, php_phongo_type_ce);
	zend_class_implements(php_phongo_binary_ce TSRMLS_CC, 1, zend_ce_serializable);

	memcpy(&php_phongo_handler_binary, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
	php_phongo_handler_binary.compare_objects = php_phongo_binary_compare_objects;
	php_phongo_handler_binary.get_debug_info  = php_phongo_binary_get_debug_info;
	php_phongo_handler_binary.get_gc          = php_phongo_binary_get_gc;
	php_phongo_handler_binary.get_properties  = php_phongo_binary_get_properties;
#if PHP_VERSION_ID >= 70000
	php_phongo_handler_binary.free_obj = php_phongo_binary_free_object;
	php_phongo_handler_binary.offset   = XtOffsetOf(php_phongo_binary_t, std);
#endif

	zend_declare_class_constant_long(php_phongo_binary_ce, ZEND_STRL("TYPE_GENERIC"), BSON_SUBTYPE_BINARY TSRMLS_CC);
	zend_declare_class_constant_long(php_phongo_binary_ce, ZEND_STRL("TYPE_FUNCTION"), BSON_SUBTYPE_FUNCTION TSRMLS_CC);
	zend_declare_class_constant_long(php_phongo_binary_ce, ZEND_STRL("TYPE_OLD_BINARY"), BSON_SUBTYPE_BINARY_DEPRECATED TSRMLS_CC);
	zend_declare_class_constant_long(php_phongo_binary_ce, ZEND_STRL("TYPE_OLD_UUID"), BSON_SUBTYPE_UUID_DEPRECATED TSRMLS_CC);
	zend_declare_class_constant_long(php_phongo_binary_ce, ZEND_STRL("TYPE_UUID"), BSON_SUBTYPE_UUID TSRMLS_CC);
	zend_declare_class_constant_long(php_phongo_binary_ce, ZEND_STRL("TYPE_MD5"), BSON_SUBTYPE_MD5 TSRMLS_CC);
	zend_declare_class_constant_long(php_phongo_binary_ce, ZEND_STRL("TYPE_USER_DEFINED"), BSON_SUBTYPE_USER TSRMLS_CC);
} /* }}} */

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */


text:
package com.hazelcast.simulator.worker.testcontainer;

import com.hazelcast.simulator.common.TestCase;
import com.hazelcast.simulator.protocol.Server;
import com.hazelcast.simulator.test.annotations.TimeStep;
import org.junit.Test;

import java.util.concurrent.atomic.AtomicLong;

import static com.hazelcast.simulator.common.TestPhase.SETUP;
import static org.mockito.Mockito.mock;

public class TestContainer_TimeStep_UnusedProbabilityTest extends TestContainer_AbstractTest {

    @Test(expected = IllegalTestException.class)
    public void test() throws Exception {
        UnusedProbabilityTest testInstance = new UnusedProbabilityTest();
        TestCase testCase = new TestCase("stopRun")
                .setProperty("threadCount", 1)
                .setProperty("iterations", 100)
                .setProperty("unusedProb", "0.2")
                .setProperty("class", testInstance.getClass());

        TestContextImpl testContext = new TestContextImpl(
                testCase.getId(), "localhost", mock(Server.class));
        TestContainer container = new TestContainer(testContext, testInstance, testCase);
        container.invoke(SETUP);
    }

    public static class UnusedProbabilityTest {
        private final AtomicLong runCount = new AtomicLong(0);

        @TimeStep
        public void timeStep() {
            runCount.incrementAndGet();
        }
    }
}


text:
Draw bounding boxes on a batch of images.

Outputs a copy of `images` but draws on top of the pixels zero or more bounding
boxes specified by the locations in `boxes`. The coordinates of the each
bounding box in `boxes` are encoded as `[y_min, x_min, y_max, x_max]`. The
bounding box coordinates are floats in `[0.0, 1.0]` relative to the width and
height of the underlying image.

For example, if an image is 100 x 200 pixels and the bounding box is
`[0.1, 0.5, 0.2, 0.9]`, the bottom-left and upper-right coordinates of the
bounding box will be `(10, 40)` to `(50, 180)`.

Parts of the bounding box may fall outside the image.

##### Args:

*  <b>`images`</b>: A `Tensor`. Must be one of the following types: `float32`, `half`.
    4-D with shape `[batch, height, width, depth]`. A batch of images.
*  <b>`boxes`</b>: A `Tensor` of type `float32`.
    3-D with shape `[batch, num_bounding_boxes, 4]` containing bounding
    boxes.
*  <b>`name`</b>: A name for the operation (optional).

##### Returns:

  A `Tensor`. Has the same type as `images`.
  4-D with the same shape as `images`. The batch of input images with
  bounding boxes drawn on the images.


text:
package cn.itcast.zt;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.statemachine.StateMachine;

@SpringBootApplication
public class SpringootStatemachineApplication implements CommandLineRunner {

	public static void main(String[] args) {
		SpringApplication.run(SpringootStatemachineApplication.class, args);
	}

	@Autowired(required = false)
	private StateMachine<States, Events> stateMachine ;

	@Override
	public void run(String... args) throws Exception {
		stateMachine.start();
		stateMachine.sendEvent(Events.PAY);
		stateMachine.sendEvent(Events.RECEIVE);
	}
}


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

<title>HWPFOutputStream (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD

org.apache.poi.hwpf.model.io

Class HWPFOutputStream

java.lang.Object

java.io.OutputStream

java.io.ByteArrayOutputStream

org.apache.poi.hwpf.model.io.HWPFOutputStream

All Implemented Interfaces:

java.io.Closeable, java.io.Flushable

@Internal
public final class HWPFOutputStream
extends java.io.ByteArrayOutputStream

Field Summary

Fields inherited from class java.io.ByteArrayOutputStream

buf, count

Constructor Summary

Constructors

Constructor and Description

HWPFOutputStream()

Method Summary

Methods

Modifier and Type
Method and Description

int
getOffset()

void
reset()

void
write(byte[] buf,
     int off,
     int len)

void
write(int b)

Methods inherited from class java.io.ByteArrayOutputStream

close, size, toByteArray, toString, toString, toString, writeTo

Methods inherited from class java.io.OutputStream

flush, write

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

HWPFOutputStream

public HWPFOutputStream()

Method Detail

getOffset

public int getOffset()

reset

public void reset()

Overrides:

reset in class java.io.ByteArrayOutputStream

write

public void write(byte[] buf,
         int off,
         int len)

Overrides:

write in class java.io.ByteArrayOutputStream

write

public void write(int b)

Overrides:

write in class java.io.ByteArrayOutputStream

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD

                Copyright 2014 The Apache Software Foundation or
        its licensors, as applicable.


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

class Applications extends Admin_context {

	/**
	 * Constructor
	 *
	 */
	public function __construct()
	{
		parent::__construct();

		// load lang files
		$this->load->model('client_model');
		$this->load->model('application_model');
		$this->load->model('client_application_model');

		// set the page title
		$this->page_title[] = lang('admin_users_title');
	}

	/**
	 * Default class method - lists applications
	 *
	 */
	public function index()
	{
		// add the required JS assets
		$this->js_assets[] = 'admin/data_rows.js';
		$this->js_assets[] = 'admin/app_search.js';
		$this->js_assets[] = 'super_admin/applications.js';

		$this->content['applications'] = $this->client_application_model->get_all();

		//getting $applications_colors options
		$this->content['applications_colors'] = $this->application_model->get_application_colors_options();

		// check if start or end date/time not set , make start - today, end - today + 1 week;
		date_default_timezone_set($this->client->time_zone);

		foreach($this->client->applications as $value)
		{
			$value->commence = $value->commence ? $value->commence : strtotime('today 0:00');
			$value->expire = $value->expire ? $value->expire :	strtotime('+1 week 0:00');
		}

		$this->wrap_views[] = $this->load->view('admin/applications/index', $this->content, TRUE);

		$this->render();
	}

	/**
	 * Build add client application form
	 *
	 * @return	function
	 */
	public function add_application()
	{
		return $this->application_op('add', $this->client->id);
	}

	/**
	 * Build add/edit client application form
	 *
	 * @param	int
	 * @return	function
	 */
	public function edit_application( $application_id)
	{
		$this->confirm_valid_application($application_id);

		return $this->application_op('edit',$application_id);
	}

	/**
	 * Build add/edit client application form
	 *
	 * @param	string
	 * @param	int
	 * @return	function
	 */
	public function application_op($action = 'add', $application_id = NULL)
	{
		if ($action === 'add')
		{
			$application = $this->client_application_model->create_prototype($this->client->id);

			$this->content['action_title'] = 'Add a new application';
		}
		else // edit
		{
			$application = $this->client_application_model->get($application_id);

			$this->content['action_title'] = "Edit <span>{$application->name}</span>";
		}

		$this->content['action'] = $action;
		$this->content['row'] = $application;
		$this->content['applications'] = $this->application_model->get_application_options();
		$this->content['applications_colors'] = $this->application_model->get_application_colors_options();

		// check if start or end date/time not set , make start - today, end - today + 1 week;
		date_default_timezone_set($this->client->time_zone);

		$this->content['row']->commence = $this->content['row']->commence ? $this->content['row']->commence : strtotime('today 0:00');
		$this->content['row']->expire = $this->content['row']->expire ? $this->content['row']->expire :	 strtotime('+1 week 0:00');

        $this->load->model('client_group_model');
        $groups = $this->client_group_model->get_client_group($this->client->id);
        foreach($groups as $group) {
            foreach($group as $key => $val) {
                if($key == "name"){
                    $groups_arr[$group->id] = $val;
                }
            }
        }
        $this->content['user_groups_options'] = $groups_arr;

        $this->load->model('user_model');

        $users = $this->user_model->get_many(explode(',',$application->user_id));

        $this->content['user_arr'] = $users;

        $groups = $this->client_group_model->get_many(explode(',',$application->group_id));

        $this->content['group_arr'] = $groups;

        $facilitators = $this->user_model->get_many(explode(',',$application->facilitator_id));

        $this->content['facilitator_arr'] = $facilitators;

		$this->json['content'] = $this->load->view('admin/applications/partials/application_add_edit_row', $this->content, TRUE);

		return $this->ajax_response();
	}

	/**
	 * Insert a new client application on add form submission
	 *
	 * @return	function
	 */
	public function put_application()
	{
		$data = $this->input->post();
        // attempt to insert the new user
        $group_ids = explode(',',$data['group_id']);
        unset($data['group_id']);

        $insert = $this->client_application_model->insert($data);

        if(!empty($group_ids) && $insert ){
            $this->load->model('client_application_group_model');
            $group_data['application_id'] = $insert;
            foreach($group_ids as $group_id){
                $group_data['group_id'] = $group_id;
                $insert_group_id[] = $this->client_application_group_model->insert($group_data);
            }
        }

		if ( ! $insert )
		{
			$this->json['status'] = 'error';
			$this->json['message'] = 'There errors when attempting to add the application.';
			return $this->add_application($this->client->id);
		}

		$this->set_flash_message('success', 'Application successfully added.');

		$this->json['redirect'] = 'admin/applications/' . $this->client->id;

		return $this->ajax_response();
	}

	/**
	 * Update a client application on edit form submission
	 *
	 * @param	int
	 * @return	function
	 */
	public function update_application($application_id)
	{
		$this->confirm_valid_application($application_id);

		$data = $this->input->post();

        $this->load->model('client_application_group_model');
        $group_data['application_id'] = $application_id;

        $application_groups = $this->client_application_group_model->get_many_by('application_id',$application_id);
        $deleted_groups = $this->client_application_group_model->delete_application_groups($application_groups);

        if(!in_array(0,$deleted_groups)){
            $delete = true;
        }
        $data['group_id'] = explode(',',$data['group_id']);
        if($delete){
            foreach($data['group_id'] as $group_id){
                $group_data['group_id'] = $group_id;
                $insert_group_id[] = $this->client_application_group_model->insert($group_data);
            }
        }

        // attempt to update the user
        unset($data['group_id']);

		$update = $this->client_application_model->update($application_id, $data);

		if ( ! $update )
		{
			$this->json['status'] = 'error';
			$this->json['message'] = 'There errors when attempting to update the application.';
			return $this->edit_application($application_id);
		}

		$this->content['row'] = $this->client_application_model->get($application_id);
		$this->content['applications'] = $this->client_application_model->get_all();

		//getting $applications_colors options
		$this->content['applications_colors'] = $this->application_model->get_application_colors_options();

		$this->json['message'] = 'Application successfully updated.';
		$this->json['content'] = $this->load->view('admin/applications/partials/application_row', $this->content, TRUE);

		return $this->ajax_response();
	}

	/**
	 * Delete a client application
	 *
	 * @param	int
	 * @return	function
	 */
	public function delete_application($application_id)
	{
		$this->confirm_valid_application($application_id);

		$delete = $this->client_application_model->delete($application_id);

		if ( ! $delete )
		{
			$this->set_flash_message('error', 'An error occurred whilst attempting to delete the application.');
		}
		else
		{
			$this->set_flash_message('success', 'Application successfully deleted.');
		}

		return redirect('admin/applications/' . $this->client->id);
	}

	/**
	 * Sort client applications
	 *
	 * @param	string
	 * @return	function
	 */
	public function sort_applications($application_ids)
	{
		$this->client_application_model->update_sort_order($this->client->id, $application_ids);

		$this->json['message'] = 'Applications sort-order updated.';

		return $this->ajax_response();
	}

	/**
	 * Check that client is valid (exists)
	 *
	 * @return	function or void
	 */
	protected function confirm_valid_client()
	{
		$client = $this->client_model->get($this->client->id);

		if ( ! $client )
		{
			$this->set_flash_message('error', 'This client does not appear to exist.');

			$redirect = 'admin/clients';

			if ( $this->input->is_ajax_request() )
			{
				$this->json['redirect'] = $redirect;
				return $this->ajax_response();
			}

			return redirect($redirect);
		}
	}

    public function searchUsers() {

        $keyword = isset($_GET['keyword']) ? $_GET['keyword'] : '';
        $ids = isset($_GET['ids']) && !empty($_GET['ids']) ? $_GET['ids'] : '';

        if($keyword){

            $users = $this->client_application_model->search_users($keyword,$ids);

            echo json_encode($users);
        }else{
            $users = [];
            echo json_encode($users);
        }

    }

    public function searchGroups() {

        $keyword = isset($_GET['keyword']) ? $_GET['keyword'] : '';
        $ids = isset($_GET['ids']) && !empty($_GET['ids']) ? $_GET['ids'] : '';

        if($keyword){

            $groups = $this->client_application_model->search_groups($keyword,$ids);

            echo json_encode($groups);
        }else{
            $groups = [];
            echo json_encode($groups);
        }

    }

    public function searchFacilitators() {

        $keyword = isset($_GET['keyword']) ? $_GET['keyword'] : '';
        $ids = isset($_GET['ids']) && !empty($_GET['ids']) ? $_GET['ids'] : '';

        if($keyword){

            $facilitators = $this->client_application_model->search_facilitators($keyword,$ids);

            echo json_encode($facilitators);
        }else{
            $facilitators = [];
            echo json_encode($facilitators);
        }

    }

	/**
	 * Check that application is valid (exists)
	 *
	 * @param	int
	 * @return	function or void
	 */
	protected function confirm_valid_application($application_id)
	{
		$application = $this->client_application_model->get_by(array(
			'id'			=> $application_id,
			'client_id'		=> $this->client->id,
		));

		if ( ! $application )
		{
			$this->set_flash_message('error', 'This application does not appear to exist.');

			$redirect = 'admin/applications/' . $this->client->id;

			if ( $this->input->is_ajax_request() )
			{
				$this->json['redirect'] = $redirect;
				return $this->ajax_response();
			}

			return redirect($redirect);
		}
	}

}


text:
using System;

namespace CSharpGL
{
    /// <summary>
    ///
    /// </summary>
    public partial class Renderbuffer : IDisposable
    {
        /// <summary>
        ///
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        ///
        /// </summary>
        ~Renderbuffer()
        {
            this.Dispose(false);
        }

        private bool disposedValue = false;

        private void Dispose(bool disposing)
        {
            if (this.disposedValue == false)
            {
                if (disposing)
                {
                    // Dispose managed resources.
                }

                // Dispose unmanaged resources.
                IntPtr context = GL.Instance.GetCurrentContext();
                if (context != IntPtr.Zero)
                {
                    glDeleteRenderbuffers(this.renderbuffer.Length, this.renderbuffer);
                    this.renderbuffer[0] = 0;
                }
            }

            this.disposedValue = true;
        }
    }
}


text:
(function(exports, parent) {

    "use strict";

    exports.MatcherManager = MatcherManager;

    /**
     * ## MatcherManager constructor
     *
     * Creates a new instance of role mapper
     */
    function MatcherManager(node) {

        /**
         * ### MatcherManager.node
         *
         * Reference to the node object
         */
        this.node = node;

        /**
         * ### MatcherManager.roler
         *
         * The roler object
         *
         * @see Roler
         */
        this.roler = new parent.Roler();

        /**
         * ### MatcherManager.matcher
         *
         * The matcher object
         *
         * @see Matcher
         */
        this.matcher = new parent.Matcher({ roler: this.roler });

        /**
         * ### MatcherManager.lastSettings
         *
         * Reference to the last settings parsed
         */
        this.lastSettings = null;

        /**
         * ### MatcherManager.lastMatches
         *
         * Reference to the last matches
         */
        this.lastMatches = null;

        /**
         * ### MatcherManager.lastMatchesById
         *
         * Reference to the last matches organized by id of client
         */
        this.lastMatchesById = {};
    }

    /**
     * ### MatcherManager.clear
     *
     * Clears current matches and roles
     *
     * @param {string} mod Optional. Modifies what must be cleared.
     *    Values: 'roles', 'matches', 'all'. Default: 'all'
     */
    MatcherManager.prototype.clear = function(mod) {

        this.lastMatches = null;
        this.lastSettings = null;
        this.lastMatchesById = {};

        switch(mod) {
        case 'roles':
            this.roler.clear();
            break;
        case 'matches':
            this.matcher.clear();
            break;
        default:
            this.roler.clear();
            this.matcher.clear();
        }
    };

    /**
     * ### MatcherManager.match
     *
     * Parses a conf object and returns the desired matches of roles and players
     *
     * Stores references of last settings and matches.
     *
     * Returned matches are in a format which is ready to be sent out as
     * remote options. That is:
     *
     *     matches = [
     *         {
     *             id: 'playerId',
     *             options: {
     *                 role: "A", // Optional.
     *                 partner: "partnerId", // Optional.
     *                 group: "yyy" // For future use.
     *             }
     *         },
     *         // More matches...
     *     ];
     *
     * @param {object} settings The settings to generate the matches.
     *   The object is passed to `Matcher.match`
     *
     * @return {array} Array of matches ready to be sent out as remote options.
     *
     * @see randomPairs
     * @see MatcherManager.lastMatches
     * @see MatcherManager.lastMatchesById
     * @see MatcherManager.lastSettings
     * @see Matcher.match
     * @see Game.gotoStep
     */
    MatcherManager.prototype.match = function(settings) {
        var matches;

        // String is turned into object. Might still fail.
        if ('string' === typeof settings) settings = { match: settings };

        if ('object' !== typeof settings || settings === null) {
            throw new TypeError('MatcherManager.match: settings must be ' +
                                'object or string. Found: ' + settings);
        }

        if (settings.match === 'random_pairs' ||
            (settings.match === 'round_robin' ||
             settings.match === 'roundrobin')) {

            matches = randomPairs.call(this, settings);
        }
        else {
            throw new Error('MatcherManager.match: only "random_pairs" and ' +
                            '"round_robin" algorithms supported. Found: ' +
                            settings.match);
        }

        if (!matches || !matches.length) {
            throw new Error('MatcheManager.match: "' + settings.match +
                            '" did not return matches.');
        }

        return matches;
    };

    /**
     * ### MatcherManager.getMatches
     *
     * Returns all the matches in a round in the requested format
     *
     * Accepts two parameters to specify a round, and a modifier for
     * the return value. Important! Both parameters are optional and
     * they can be passed in either order.
     *
     * Valid modifiers and return values:
     *
     *  - 'ARRAY' (default): [ [ 'id1', 'id2' ], [ 'id3', 'id4' ], ... ]
     *
     *  - 'ARRAY_ROLES': [ [ 'ROLE1', 'ROLE2' ], [ 'ROLE1', 'ROLE2' ] ]
     *
     *  - 'ARRAY_ROLES_ID': [ { ROLE1: 'id1', ROLE2: 'id2' },
     *                     { ROLE1: 'id3', ROLE2: 'id4' }, ... ]
     *
     *  - 'ARRAY_ID_ROLES': [ { id1: 'ROLE1', id2: 'ROLE2' },
     *                        { id3: 'ROLE1', id4: 'ROLE4' }, ... ]
     *
     *  - 'OBJ': { id1: 'id2', id2: 'id1', id3: 'id4', id4: 'id3' }
     *
     *  - 'OBJ_ROLES_ID': { ROLE1: [ 'id1', 'id3' ], ROLE2: [ 'id2', 'id4' ] }
     *
     *  - 'OBJ_ID_ROLES': { id1: 'ROLE1', id2: 'ROLE2',
     *                      id3: 'ROLE1', id4: 'ROLE2' }
     *
     * @param {string} mod Optional. A valid modifier (default: 'ARRAY')
     * @param {number} round Optional. The round of the matches
     *   (default: current game round).
     *
     * @return {array|object|null} The requested matches in the requested
     *   format, or null matches are not yet set
     *
     * @see round2Index
     * @see Matcher.getMatch
     * @see Matcher.getMatchObject
     * @see Roler.getRoleObj
     * @see Roler.getIdRoleObj
     */
    MatcherManager.prototype.getMatches = function(mod, round) {

        if ('string' !== typeof mod) {
            if ('undefined' !== typeof mod) {
                throw new TypeError('MatcherManager.getMatches: mod must be ' +
                                    'undefined or string. Found: ' + mod);
            }
            mod = 'ARRAY';
        }

        if ('undefined' !== typeof round && 'number' !== typeof round) {
            throw new TypeError('MatcherManager.getMatches: round ' +
                                'must be undefined or number. Found: ' + round);
        }

        if (!this.matcher.getMatches()) return null;

        round = round2Index.call(this, 'getMatches', round);

        if (mod === 'ARRAY') return this.matcher.getMatch(round);
        if (mod === 'ARRAY_ROLES') return this.roler.getRoleMatch(round);
        if (mod === 'ARRAY_ID_ROLES') return this.roler.getId2RoleMatch(round);
        if (mod === 'ARRAY_ROLES_ID') return this.roler.getRole2IdMatch(round);

        if (mod === 'OBJ') return this.matcher.getMatchObject(round);
        if (mod === 'OBJ_ROLES_ID') return this.roler.getRole2IdRoundMap(round);
        if (mod === 'OBJ_ID_ROLES') return this.roler.getId2RoleRoundMap(round);

        throw new Error('MatcherManager.getMatches: unknown modifier: ' + mod);
    };

    /**
     * ### MatcherManager.getMatchFor
     *
     * Returns the match for the specified id
     *
     * @param {string} id The id to search a match for
     * @param {number} round Optional. Specifies a round other
     *   than current (will be normalized if there are more
     *   rounds than matches)
     *
     * @return {string|null} The current match for the id, or null
     *    if the id is not found or matches are not set
     *
     * @see Matcher.getMatchFor
     * @see round2Index
     */
    MatcherManager.prototype.getMatchFor = function(id, round) {
        if (!this.matcher.getMatches()) return null;
        round = round2Index.call(this, 'getMatchFor', round);
        return this.matcher.getMatchFor(id, round);
    };

    /**
     * ### MatcherManager.getRoleFor
     *
     * Returns the role for the specified id
     *
     * @param {string} id The id to search a role for
     * @param {number} round Optional. Specifies a round other
     *   than current (will be normalized if there are more
     *   rounds than matches)
     *
     * @return {string|null} The role hold by id at the
     *    specified round or null if matches are not yet set
     *
     * @see Roler.getRolerFor
     * @see round2Index
     */
    MatcherManager.prototype.getRoleFor = function(id, round) {
        if (!this.matcher.getMatches()) return null;
        round = round2Index.call(this, 'getRoleFor', round);
        return this.roler.getRoleFor(id, round);
    };

    /**
     * ### Roler.getIdForRole
     *
     * Returns the id/s holding a roles at round x
     *
     * @param {string} role The role to check
     * @param {number} round Optional. Specifies a round other
     *   than current (will be normalized if there are more
     *   rounds than matches)
     *
     * @return {array|null} Array of id/s holding the role at round x, or
     *   null if matches are not yet set
     *
     * @see Roler.getIdForRole
     * @see round2Index
     */
    MatcherManager.prototype.getIdForRole = function(role, round) {
        if (!this.matcher.getMatches()) return null;
        round = round2Index.call(this, 'getIdForRole', round);
        return this.roler.getIdForRole(role, round);
    };

    /**
     * ### MatcherManager.getIterationRound
     *
     * Returns the pointer the round in the matcher (matches are cycled through)
     *
     * @return {number} The current iteration round
     *
     * @see Matcher.x
     * @see Matcher.hasNext
     */
    MatcherManager.prototype.getIterationRound = function() {
        return this.matcher.x || 0;
    };

    /**
     * ### MatcherManager.replaceId
     *
     * Replaces an id with a new one in all roles and matches
     *
     * If the number of players and rounds is large,
     * this operation becomes costly. Consider replacing the ID
     * manually after being returned.
     *
     * @param {string} oldId The id to be replaced
     * @param {string} newId The replacing id
     *
     * @return {boolean} TRUE, if the oldId was found and replaced
     *
     * @see Matcher.replaceId
     * @see Roler.replaceId
     *
     * @experimental
     *
     * TODO: this does not scale up. Maybe have another registry of
     * substituted ids.
     *
     * TODO: maybe return info about the replaced id, e.g. current
     * options, instead of boolean.
     */
    MatcherManager.prototype.replaceId = function(oldId, newId) {
        var res;
        res = this.matcher.replaceId(oldId, newId);
        res = res && this.roler.replaceId(oldId, newId);
        return res;
    };

    /**
     * ### MatcherManager.getSetupFor
     *
     * Returns the setup object (partner and role options) for a specific id
     *
     * @param {string} id The id to get the setup object for
     *
     * @return {object|null} The requested setup object or null if not found
     *
     * @see Matcher.match
     * @see round2index
     */
    MatcherManager.prototype.getSetupFor = function(id) {
        var out;
        if ('string' !== typeof id) {
            throw new TypeError('MatcherManager.getSetupFor: id must be ' +
                                'string. Found: ' + id);
        }
        out = this.lastMatchesById[id];
        return out || null;
    };

    // ## Helper Methods.

    /**
     * ### round2Index
     *
     * Parses a round into corresponding index of matches
     *
     * Important! Matches are 0-based, but rounds are 1-based.
     * `Matcher.normalizeRound` takes care of it.
     *
     * @param {number} round Optional. The round to parse to an index.
     *   Default: current game round.
     *
     * @return {number} The normalized round
     *
     * @see Matcher.normalizeRound
     * @see Matcher.x
     * @see Game.getCurrentGameStage
     */
    function round2Index(method, round) {
        if ('undefined' === typeof round) {
            round = this.node.game.getRound();
            if (round === 0) {
                throw new Error('MatcherManager.' + method + ': game stage ' +
                                'is 0.0.0, please specify a valid round');
            }
        }
        if ('number' === typeof round) {
            round = this.matcher.normalizeRound(round);
        }
        return round;
    }

    /**
     * ### randomPairs
     *
     * Matches players and/or roles in random pairs
     *
     * Supports odd number of players, if 3 roles are given in settings.
     *
     * @param {object} settings The settings object
     *
     * @return {array} The array of matches.
     */
    function randomPairs(settings) {
        var r1, r2;
        var ii, i, len;
        var roundMatches, nMatchesIdx, match, id1, id2, missId;
        var matches, matchesById, sayPartner, doRoles;
        var opts, roles, matchedRoles;

        var game, n;
        var nRounds;

        // Delete previous results.
        this.lastMatches = null;
        this.lastMatchesById = null;

        // Init local variables.

        matchesById = {};

        sayPartner = 'undefined' === typeof settings.sayPartner ?
            true : !!settings.sayPartner;

        doRoles = !!settings.roles;

        game = this.node.game;
        n = game.pl.size();

        // Settings the number of rounds.
        if ('undefined' !== typeof settings.rounds) {
            nRounds = settings.rounds;
        }
        else {
            nRounds = game.plot.getRound(game.getNextStep(), 'total');
        }
        if (nRounds > n-1) nRounds = n-1;

        // Algorithm: random.
        if (settings.match === 'random') {
            if (doRoles) {
                this.roler.clear();
                this.roler.setRoles(settings.roles, 2);
                this.matcher.init({ doRoles: doRoles });
            }
            this.matcher.generateMatches('random', n, {
                rounds: nRounds,
                // cycle: settings.cycle,
                skipBye: settings.skipBye,
                bye: settings.bye,
                fixedRoles: settings.fixedRoles,
                canMatchSameRole: settings.canMatchSameRole
            });
            this.matcher.setIds(game.pl.id.getAllKeys());
            // Generates new random matches for this round.
            this.matcher.match(true);
        }

        // Algorithm: round robin (but only if not already initialized
        // or if reInit = true).
        else {
            if (!this.matcher.matches || settings.reInit) {
                if (doRoles) {
                    this.roler.clear();
                    this.roler.setRoles(settings.roles, 2);
                    this.matcher.init({ doRoles: doRoles });
                }
                // Make a manual copy of settings object, and generate matches.
                this.matcher.generateMatches('roundrobin', n, {
                    rounds: nRounds,
                    cycle: settings.cycle,
                    skipBye: settings.skipBye,
                    bye: settings.bye,
                    fixedRoles: settings.fixedRoles,
                    canMatchSameRole: settings.canMatchSameRole
                });
                if (settings.assignerCb) {
                    this.matcher.setAssignerCb(settings.assignerCb);
                }
                this.matcher.setIds(game.pl.id.getAllKeys());
                // Generates matches.
                this.matcher.match(true);
            }
            // Cycle through the matches, if we do not have enough.
            else if (!this.matcher.hasNext()) {
                this.matcher.init( { x: null, y: null });
            }
        }

        // Get all the matches for round x, and increments x.
        nMatchesIdx = 'number' === typeof this.matcher.x ?
            (this.matcher.x + 1) : 0;
        // This also increments the index matcher.x.
        roundMatches = this.matcher.getMatch(nMatchesIdx);

        len = roundMatches.length;

        // Contains one remoteOptions object per player.
        matches = ((n % 2) === 0) ?
            new Array((len*2)) :
            (settings.skipBye ? new Array((len*2)-2) : new Array((len*2)-1));

        // The id in case the number of player is odd.
        missId = this.matcher.missingId;

        matchedRoles = this.roler.getRolifiedMatches();

        // While we have matches, send them to clients.
        ii = i = -1;
        for ( ; ++i < len ; ) {
            ii++;
            match = roundMatches[i];
            id1 = match[0];
            id2 = match[1];

            // Verify that id1 and id2 are still connected.
            if (!game.pl.exist(id1)) id1 = missId;
            if (!game.pl.exist(id2)) id2 = missId;

            // If both id1 and id2 are disconnected, skip matching them.
            if (id1 === id2) {
                // Reduce matches array length.
                len--;
                matches.length--;
                continue;
            }

            if (doRoles) {
                roles = matchedRoles[nMatchesIdx][i];

                // Prepare options to send to player 1, if role1 is defined.
                r1 = roles[0];

                if (r1) {
                    if (!sayPartner) {
                        opts = { id: id1, options: { role: r1 } };
                    }
                    else {
                        opts = { id: id1, options: { role: r1, partner: id2 } };
                    }
                    // Add options to array.
                    matches[ii] = opts;

                    // Keep reference.
                    matchesById[id1] = opts.options;
                }

                // Prepare options to send to player 2, if role2 is defined.
                r2 = roles[1];

                if (r2) {

                    // Increment ii index if both r1 and r2 are defined.
                    if (r1) ii++;

                    if (!sayPartner) {
                        opts = { id: id2, options: { role: r2 } };
                    }
                    else {
                        opts = { id: id2, options: { role: r2, partner: id1 } };
                    }
                    // Add options to array.
                    matches[ii] = opts;

                    // Keep reference.
                    matchesById[id2] = opts.options;
                }
            }
            else if (sayPartner) {
                if (id1 !== missId) {
                    opts = { id: id1, options: { partner: id2 } };
                    matches[ii] = opts;
                    matchesById[id1] = opts.options;
                }
                if (id2 !== missId) {
                    if (id1 !== missId) ii++;
                    opts = { id: id2, options: { partner: id1 } };
                    matches[ii] = opts;
                    matchesById[id2] = opts.options;
                }
            }
        }

        // Store references.
        this.lastMatches = matches;
        this.lastMatchesById = matchesById;
        this.lastSettings = settings;

        return matches;
    }

    // ## Closure
})(
    'undefined' != typeof node ? node : module.exports,
    'undefined' != typeof node ? node : module.parent.exports
);


text:
package com.fflorio.solutions;

import java.math.BigInteger;

/**
 * Created by francesco on 2017-04-26.
 */
public class SolutionV4 implements Solution {

    @Override
    public String label() {
        return "[V4]";
    }

    @Override
    public int findMissingValue(int[] collection) {
        BigInteger sum = getTriangularNumber(collection.length+1);
        for(int item : collection){
            sum = sum.subtract(BigInteger.valueOf(item));
        }
        return sum.intValue();
    }

    private final BigInteger getTriangularNumber(final long n){
        BigInteger bigN = BigInteger.valueOf(n);
        BigInteger bigNPlus1 = BigInteger.valueOf(n+1);
        return bigN.multiply(bigNPlus1).divide(BigInteger.valueOf(2));
    }
}


text:
/*****************************************************************************************************************************************
Author: Michael Shoots
Email: michael.shoots@live.com
Project: Open Space 4x
License: MIT License
Notes:
******************************************************************************************************************************************/

using UnityEngine;
using System.Collections;

public class MainStationyardScreen : StationyardBaseScreen
{
    #region Variables
    #endregion

    public MainStationyardScreen()
    {
        Initialize();
    }

    public override void Update()
    {
        base.Update();
    }

    public override void Draw()
    {
        base.Draw();
    }

    protected override void CloseScreen()
    {
        if (unitModel != null)
            Object.Destroy(unitModel);
        //GameManager.instance.ChangeScreen(new MainMenuScreen());
    }
}


text:
package com.thinkbiganalytics.policy;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.HashMap;
import java.util.Map;

/**
 * Annotation that is used to display input form elements
 * the angular directive 'policy-input-form' along with the angular service 'PolicyInputFormService' are used to render these elements
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface PolicyProperty {

    /**
     * internal name for the property
     * @return String
     */
    String name();

    /**
     * The label for the form item
     * @return String
     */
    String displayName() default "";

    /**
     * The value of the input.  The form will default to this value if it is supplied
     * @return String
     */
    String value() default "";

    /**
     * Input placeholder with text indicating what should be entered
     * @return String
     */
    String placeholder() default "";

    /**
     * Determines how the property should be rendered:
     * number, string, select, regex, date, chips, feedChips, currentFeed, currentFeedCronSchedule, feedSelect, email, cron
     * type of {@link PolicyPropertyTypes.PROPERTY_TYPE#string} will be rendered as a standard input box.
     * You can enforce specific text expressions using the property passing in the valid Regexp
     * @return PolicyPropertyTypes.PROPERTY_TYPE
     */
    PolicyPropertyTypes.PROPERTY_TYPE type() default PolicyPropertyTypes.PROPERTY_TYPE.string;

    /**
     * Helpful text that will be rendered below the input entry
     * @return String
     */
    String hint() default "";

    /**
     * For Select inputs this is a list of the options that will be available.  This cannot be used with the {@code selectableValues()}
     * @return PropertyLabelValue[]
     */
    PropertyLabelValue[] labelValues() default {};

    /**
     * For a select input this is the list of optoins that will be available.  This cannot be used with the {@code labelValues()}
     * @return PropertyLabelValue[]
     */
    String[] selectableValues() default {};

    /**
     * Used for rendering {@link PolicyPropertyTypes.PROPERTY_TYPE#chips} where the input has multiple values
     * @return PropertyLabelValue[]
     */
    PropertyLabelValue[] values() default {};

    /**
     * requires input from the user.
     * @return boolean
     */
    boolean required() default false;

    /**
     * Indicates the input will be hidden
     * @return boolean
     */
    boolean hidden() default false;

    /**
     * A arbitrary string used to group inputs together.
     * Items with the same group name will be displayed together in the same row
     * @return String
     */
    String group() default "";

    /**
     * Regexp used to evaluate the input.
     * This should not include the beginning and ending slashes
     * Example. To validate a Numeric input one should use: ^\d+$  instead of this: /^\d+$/
     * @return String
     */
    String pattern() default "";

    /**
     * The message to be displayed if the pattern is supplied and the user enters something invalid
     * @return String
     */
    String patternInvalidMessage() default "Invalid Input";

    PropertyLabelValue[] additionalProperties() default {};

}


text:
import fs from 'fs'

import aws from 'aws-sdk'
import { promisify, promisifyAll } from 'bluebird'
import gm from 'gm'
import meta from 'musicmetadata'
import mmm from 'mmmagic'
import _ from 'lodash'
import mv from 'mv';

import { load as configLoader } from '../../config/config'

const config = configLoader()
promisifyAll(fs)
const mvAsync = promisify(mv);

const mimeMagic = new mmm.Magic(mmm.MAGIC_MIME_TYPE)
const detectMime = promisify(mimeMagic.detectFile, { context: mimeMagic })

const magic = new mmm.Magic()
const detectFile = promisify(magic.detectFile, { context: magic })

async function detectMimetype(filename) {
  const mimeType = await detectMime(filename)

  if (mimeType === 'application/octet-stream') {
    const fileType = await detectFile(filename)

    if (fileType.startsWith('Audio file with ID3')) {
      return 'audio/mpeg'
    }
  }

  return mimeType
}

export function addModel(dbAdapter) {
  /**
   * @constructor
   */
  const Attachment = function (params) {
    this.id = params.id
    this.file = params.file // FormData File object
    this.fileName = params.fileName // original file name, e.g. 'cute-little-kitten.jpg'
    this.fileSize = params.fileSize // file size in bytes
    this.mimeType = params.mimeType // used as a fallback, in case we can't detect proper one
    this.fileExtension = params.fileExtension // jpg|png|gif etc.
    this.mediaType = params.mediaType // image | audio | general

    this.noThumbnail = params.noThumbnail // if true, image thumbnail URL == original URL
    this.imageSizes = params.imageSizes || {} // pixel sizes of thumbnail(s) and original image, e.g. {t: {w: 200, h: 175}, o: {w: 600, h: 525}}

    this.artist = params.artist  // filled only for audio
    this.title = params.title   // filled only for audio

    this.userId = params.userId
    this.postId = params.postId

    if (parseInt(params.createdAt, 10))
      this.createdAt = params.createdAt
    if (parseInt(params.updatedAt, 10))
      this.updatedAt = params.updatedAt
  }

  Attachment.className = Attachment
  Attachment.namespace = 'attachment'

  Reflect.defineProperty(Attachment.prototype, 'imageSizes', {
    get: function () { return this.imageSizes_ },
    set: function (newValue) {
      if (_.isString(newValue)) {
        newValue = JSON.parse(newValue)
      }

      this.imageSizes_ = newValue
    }
  })

  Attachment.prototype.validate = async function () {
    const valid = this.file
               && Object.keys(this.file).length > 0
               && this.file.path
               && this.file.path.length > 0
               && this.userId
               && this.userId.length > 0

    if (!valid)
      throw new Error('Invalid')
  }

  Attachment.prototype.create = async function () {
    this.createdAt = new Date().getTime()
    this.updatedAt = new Date().getTime()
    this.postId = this.postId || ''

    await this.validate()

    this.id = await dbAdapter.createAttachment({
      postId:    this.postId,
      createdAt: this.createdAt.toString(),
      updatedAt: this.updatedAt.toString()
    })

    this.fileName = this.file.name
    this.fileSize = this.file.size
    this.mimeType = this.file.type

    // Determine initial file extension
    // (it might be overridden later when we know MIME type from its contents)
    // TODO: extract to config
    const supportedExtensions = /\.(jpe?g|png|gif|mp3|m4a|ogg|wav|txt|pdf|docx?|pptx?|xlsx?)$/i

    if (this.fileName && this.fileName.match(supportedExtensions) !== null) {
      this.fileExtension = this.fileName.match(supportedExtensions)[1].toLowerCase()
    } else {
      this.fileExtension = ''
    }

    await this.handleMedia()

    // Save record to DB
    const params = {
      fileName:      this.fileName,
      fileSize:      this.fileSize,
      mimeType:      this.mimeType,
      mediaType:     this.mediaType,
      fileExtension: this.fileExtension,
      noThumbnail:   this.noThumbnail,
      imageSizes:    JSON.stringify(this.imageSizes),
      userId:        this.userId,
      postId:        this.postId,
      createdAt:     this.createdAt.toString(),
      updatedAt:     this.updatedAt.toString()
    }

    if (this.mediaType === 'audio') {
      params.artist = this.artist
      params.title = this.title
    }

    await dbAdapter.updateAttachment(this.id, params)

    return this
  }

  Reflect.defineProperty(Attachment.prototype, 'url', {
    get: function () {
      return config.attachments.url + config.attachments.path + this.getFilename()
    }
  })

  Reflect.defineProperty(Attachment.prototype, 'thumbnailUrl', {
    get: function () {
      if (this.noThumbnail === '1') {
        return this.url
      }
      return this.getResizedImageUrl('t')
    }
  })

  // Get user who created the attachment (via Promise, for serializer)
  Attachment.prototype.getCreatedBy = function () {
    return dbAdapter.getUserById(this.userId)
  }

  // Get public URL of attachment (via Promise, for serializer)
  Attachment.prototype.getUrl = async function () {
    return config.attachments.url + config.attachments.path + this.getFilename()
  }

  // Get public URL of attachment's thumbnail (via Promise, for serializer)
  Attachment.prototype.getThumbnailUrl = async function () {
    if (this.noThumbnail === '1') {
      return this.getUrl()
    }

    return this.getResizedImageUrl('t')
  }

  // Get public URL of resized image attachment
  Attachment.prototype.getResizedImageUrl = function (sizeId) {
    return config.attachments.url + config.attachments.imageSizes[sizeId].path + this.getFilename()
  }

  // Get local filesystem path for original file
  Attachment.prototype.getPath = function () {
    return config.attachments.storage.rootDir + config.attachments.path + this.getFilename()
  }

  // Get local filesystem path for resized image file
  Attachment.prototype.getResizedImagePath = function (sizeId) {
    return config.attachments.storage.rootDir + config.attachments.imageSizes[sizeId].path + this.getFilename()
  }

  // Get file name
  Attachment.prototype.getFilename = function () {
    if (this.fileExtension) {
      return `${this.id}.${this.fileExtension}`
    }

    return this.id
  }

  // Store the file and process its thumbnail, if necessary
  Attachment.prototype.handleMedia = async function () {
    const tmpAttachmentFile = this.file.path

    const supportedImageTypes = {
      'image/jpeg':    'jpg',
      'image/png':     'png',
      'image/gif':     'gif',
      'image/svg+xml': 'svg'
    }
    const supportedAudioTypes = {
      'audio/mpeg':  'mp3',
      'audio/x-m4a': 'm4a',
      'audio/mp4':   'm4a',
      'audio/ogg':   'ogg',
      'audio/x-wav': 'wav'
    }

    // Check a mime type
    try {
      this.mimeType = await detectMimetype(tmpAttachmentFile)
    } catch (e) {
      if (_.isEmpty(this.mimeType)) {
        throw e
      }
      // otherwise, we'll use the fallback provided by the user
    }

    if (supportedImageTypes[this.mimeType]) {
      // Set media properties for 'image' type
      this.mediaType = 'image'
      this.fileExtension = supportedImageTypes[this.mimeType]
      this.noThumbnail = '1' // this may be overriden below

      let originalImage = promisifyAll(gm(tmpAttachmentFile))

      // Fix EXIF orientation for original image, if JPEG
      if (this.mimeType === 'image/jpeg') {
        // orientation() returns a string. Possible values are:
        // unknown, Unknown, TopLeft, TopRight, BottomRight, BottomLeft, LeftTop, RightTop, RightBottom, LeftBottom
        // The first three options are fine, the rest should be fixed.
        const orientation = await originalImage.orientationAsync()

        if (!['unknown', 'Unknown', 'TopLeft'].includes(orientation)) {
          const img = originalImage
            .profile(`${__dirname}/../../lib/assets/sRGB.icm`)
            .autoOrient()
            .quality(95)

          await img.writeAsync(tmpAttachmentFile)

          originalImage = promisifyAll(gm(tmpAttachmentFile))
        }
      }

      // Store original image size
      const originalSize = await originalImage.sizeAsync()
      this.imageSizes.o = {
        w:   originalSize.width,
        h:   originalSize.height,
        url: await this.getUrl()
      }

      // Create resized images, unless SVG
      // (SVG is a vector image, so doesn't need resizing)
      if (this.mimeType !== 'image/svg+xml') {
        // Iterate over image sizes old-fashioned (and very synchronous) way
        // because gm is acting up weirdly when writing files in parallel mode
        for (const sizeId in config.attachments.imageSizes) {
          if (config.attachments.imageSizes.hasOwnProperty(sizeId)) {
            const sizeConfig = config.attachments.imageSizes[sizeId]
            await this.resizeAndSaveImage(originalImage, originalSize, sizeConfig, sizeId)  // eslint-disable-line babel/no-await-in-loop
          }
        }
      }
    } else if (supportedAudioTypes[this.mimeType]) {
      // Set media properties for 'audio' type
      this.mediaType = 'audio'
      this.fileExtension = supportedAudioTypes[this.mimeType]
      this.noThumbnail = '1'

      // Analyze metadata to get Artist & Title
      const readStream = fs.createReadStream(tmpAttachmentFile)
      const asyncMeta = promisify(meta)
      const metadata = await asyncMeta(readStream)

      this.title = metadata.title

      if (_.isArray(metadata.artist)) {
        this.artist = metadata.artist[0]
      } else {
        this.artist = metadata.artist
      }
    } else {
      // Set media properties for 'general' type
      this.mediaType = 'general'
      this.noThumbnail = '1'
    }

    // Store an original attachment
    if (config.attachments.storage.type === 's3') {
      await this.uploadToS3(tmpAttachmentFile, config.attachments.path)
      await fs.unlinkAsync(tmpAttachmentFile)
    } else {
      await mvAsync(tmpAttachmentFile, this.getPath(), {})
    }
  }

  Attachment.prototype.resizeAndSaveImage = async function (originalImage, originalSize, sizeConfig, sizeId) {
    if (originalSize.width > sizeConfig.bounds.width || originalSize.height > sizeConfig.bounds.height) {
      const tmpImageFile = `${this.file.path}.resized.${sizeId}`

      // Resize image
      const img = originalImage
        .resize(sizeConfig.bounds.width, sizeConfig.bounds.height)
        .profile(`${__dirname}/../../lib/assets/sRGB.icm`)
        .autoOrient()
        .quality(95)

      // Save image (temporarily)
      await img.writeAsync(tmpImageFile)

      // Get image size
      const resizedImage = promisifyAll(gm(tmpImageFile))
      const resizedImageSize = await resizedImage.sizeAsync()
      this.imageSizes[sizeId] = {
        w:   resizedImageSize.width,
        h:   resizedImageSize.height,
        url: this.getResizedImageUrl(sizeId)
      }
      this.noThumbnail = '0'

      // Save image (permanently)
      if (config.attachments.storage.type === 's3') {
        await this.uploadToS3(tmpImageFile, sizeConfig.path)
        await fs.unlinkAsync(tmpImageFile)
      } else {
        await mvAsync(tmpImageFile, this.getResizedImagePath(sizeId), {})
      }
    }
  }

  // Upload original attachment or its thumbnail to the S3 bucket
  Attachment.prototype.uploadToS3 = async function (sourceFile, destPath) {
    const s3 = new aws.S3({
      'accessKeyId':     config.attachments.storage.accessKeyId || null,
      'secretAccessKey': config.attachments.storage.secretAccessKey || null
    })
    const putObject = promisify(s3.putObject, { context: s3 })
    await putObject({
      ACL:                'public-read',
      Bucket:             config.attachments.storage.bucket,
      Key:                destPath + this.getFilename(),
      Body:               fs.createReadStream(sourceFile),
      ContentType:        this.mimeType,
      ContentDisposition: this.getContentDisposition()
    })
  }

  // Get cross-browser Content-Disposition header for attachment
  Attachment.prototype.getContentDisposition = function () {
    // Old browsers (IE8) need ASCII-only fallback filenames
    const fileNameAscii = this.fileName.replace(/[^\x00-\x7F]/g, '_');

    // Modern browsers support UTF-8 filenames
    const fileNameUtf8 = encodeURIComponent(this.fileName)

    // Inline version of 'attfnboth' method (http://greenbytes.de/tech/tc2231/#attfnboth)
    return `inline; filename="${fileNameAscii}"; filename*=utf-8''${fileNameUtf8}`
  }

  return Attachment
}


text:
/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#define NO_SDL_H
#import "VBoxSDL.h"
#import <Cocoa/Cocoa.h>

void *VBoxSDLGetDarwinWindowId(void)
{
    NSView            *pView = nil;
    NSAutoreleasePool *pPool = [[NSAutoreleasePool alloc] init];
    {
        NSApplication *pApp = NSApp;
        NSWindow *pMainWnd;
        pMainWnd = [pApp mainWindow];
        if (!pMainWnd)
            pMainWnd = pApp->_mainWindow; /* UGLY!! but mApp->_AppFlags._active = 0, so mainWindow() fails. */
        pView = [pMainWnd contentView];
    }
    [pPool release];
    return pView;
}


text:
package com.microsoft.azure.management.recoveryservices.backup.v2016_12_01;

import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;

/**
 * Azure VM workload-specific workload item representing SQL Instance.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "workloadItemType")
@JsonTypeName("SQLInstance")
public class AzureVmWorkloadSQLInstanceWorkloadItem extends AzureVmWorkloadItem {
    /**
     * Data Directory Paths for default directories.
     */
    @JsonProperty(value = "dataDirectoryPaths")
    private List<SQLDataDirectory> dataDirectoryPaths;

    /**
     * Get data Directory Paths for default directories.
     *
     * @return the dataDirectoryPaths value
     */
    public List<SQLDataDirectory> dataDirectoryPaths() {
        return this.dataDirectoryPaths;
    }

    /**
     * Set data Directory Paths for default directories.
     *
     * @param dataDirectoryPaths the dataDirectoryPaths value to set
     * @return the AzureVmWorkloadSQLInstanceWorkloadItem object itself.
     */
    public AzureVmWorkloadSQLInstanceWorkloadItem withDataDirectoryPaths(List<SQLDataDirectory> dataDirectoryPaths) {
        this.dataDirectoryPaths = dataDirectoryPaths;
        return this;
    }

}


text:
//Tested with BCEL-5.1
//http://jakarta.apache.org/builds/jakarta-bcel/release/v5.1/

package com.puppycrawl.tools.checkstyle.bcel.generic;

import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.GETSTATIC;

/**
 * Describe class GETSTATICReference
 * @author Rick Giles
 * @version 18-Jun-2003
 */
public class GETSTATICReference
    extends FieldReference
{

    /**
     * @param aInstruction
     * @param aPoolGen
     */
    public GETSTATICReference(
        GETSTATIC aInstruction,
        ConstantPoolGen aPoolGen)
    {
        super(aInstruction, aPoolGen);
    }
}


text:
struct _JsonItem {
	// Common fields
	JsonValueType value_type;
	union {
		wchar_t *as_string;
		int as_int;
		INT64 as_int64;
		double as_double;
		BOOL as_bool;
		JsonArray as_array;
		JsonObject as_object;
	} value;
	size_t value_as_string_len;
	struct _JsonItem *next;
};

struct _JsonObjectItem {
	// Common fields
	JsonValueType value_type;
	union {
		wchar_t *as_string;
		int as_int;
		double as_double;
		JsonArray as_array;
		JsonObject as_object;
	} value;
	size_t value_as_string_len;
	struct _JsonItem *next;
	// Specific fields
	wchar_t *tag;
	size_t tag_len;
};

struct _JsonCursor {
	wchar_t *buf;
	size_t max;
	size_t pos;
};
typedef struct _JsonCursor JsonCursor;

static BOOL json_parse_array(JsonCursor *cursor, JsonArray array);
static BOOL json_parse_object(JsonCursor *cursor, JsonObject object);

static void json_init_cursor(wchar_t * buf, JsonCursor *cursor)
{
	memset((void *)cursor, 0, sizeof(JsonCursor));
	cursor->buf = buf;
	cursor->max = wcslen(buf);
}

static BOOL json_parse_string(JsonCursor *cursor, JsonItem item)
{
	wchar_t *buf = cursor->buf;
	BOOL escape;

	cursor->pos++; // Initial '"'
	item->value.as_string = buf + cursor->pos;
	while (cursor->pos < cursor->max) {
		if (buf[cursor->pos] == '"' && !escape) {
			cursor->pos++; // Trailing '"'
			break;
		}

		if (buf[cursor->pos] == '\\' && !escape)
			escape = TRUE;
		else
			escape = FALSE;

		cursor->pos++;
		item->value_as_string_len++;
	}

	return (cursor->pos == cursor->max) ? FALSE : TRUE;
}

static BOOL json_parse_number(JsonCursor *cursor, JsonItem item)
{
	wchar_t *buf = cursor->buf;
	wchar_t *value = buf + cursor->pos;
	size_t value_len = 0;
	BOOL has_dot = (buf[cursor->pos] == '.') ? TRUE : FALSE;
	INT64 val64;

	cursor->pos++;
	value_len++;
	while (cursor->pos < cursor->max) {
		if (buf[cursor->pos] == '.') {
			if (has_dot)
				return FALSE;
			else
				has_dot = TRUE;
		} else if (!iswdigit(buf[cursor->pos]))
			break;

		cursor->pos++;
		value_len++;
	}

	if (cursor->pos == cursor->max)
		return FALSE;

	item->value_type = (has_dot) ? JSON_VALUE_DOUBLE : JSON_VALUE_INT;
	if (item->value_type == JSON_VALUE_INT) {
		if (_snwscanf_s(value, value_len, L"%I64d", &val64) != 1)
			return FALSE;
		if (val64 > MAXINT) {
			item->value.as_int64 = val64;
			item->value_type = JSON_VALUE_INT64;
		} else
			item->value.as_int = (int) val64;
			item->value.as_int64 = val64;
	} else {
		if (_snwscanf_s(value, value_len, L"%f", &item->value.as_double) != 1)
			return FALSE;
	}

	return TRUE;
}

static BOOL json_parse_value(JsonCursor *cursor, JsonItem item)
{
	wchar_t *buf = cursor->buf;

	if (buf[cursor->pos] == '\"') {
		item->value_type = JSON_VALUE_STRING;
		return json_parse_string(cursor, item);
	} else if (iswdigit(buf[cursor->pos]) || buf[cursor->pos] == '-' || buf[cursor->pos] == '.') {
		return json_parse_number(cursor, item);
	} else if (buf[cursor->pos] == '[') {
		item->value_type = JSON_VALUE_ARRAY;
		item->value.as_array = (JsonArray) calloc(1, sizeof(struct _JsonItem));
		return json_parse_array(cursor, item->value.as_array);
	}  else if (buf[cursor->pos] == '{') {
		item->value_type = JSON_VALUE_OBJECT;
		item->value.as_object = (JsonObject) calloc(1, sizeof(struct _JsonObjectItem));
		return json_parse_object(cursor, item->value.as_object);
	} else if ((cursor->pos + wcslen(JSON_TRUE)) < cursor->max && !wcsncmp(buf + cursor->pos, JSON_TRUE, wcslen(JSON_TRUE))) {
		item->value_type = JSON_VALUE_BOOL;
		item->value.as_bool = TRUE;
		cursor->pos += wcslen(JSON_TRUE);
		return TRUE;
	} else if ((cursor->pos + wcslen(JSON_FALSE)) < cursor->max && !wcsncmp(buf + cursor->pos, JSON_FALSE, wcslen(JSON_FALSE))) {
		item->value_type = JSON_VALUE_BOOL;
		item->value.as_bool = FALSE;
		cursor->pos += wcslen(JSON_FALSE);
		return TRUE;
	} else if ((cursor->pos + wcslen(JSON_NULL)) < cursor->max && !wcsncmp(buf + cursor->pos, JSON_NULL, wcslen(JSON_NULL))) {
		item->value_type = JSON_VALUE_NULL;
		item->value.as_string = buf + cursor->pos;
		item->value_as_string_len = wcslen(JSON_NULL);
		cursor->pos += item->value_as_string_len;
		return TRUE;
	}

	return FALSE;
}

static BOOL json_parse_object(JsonCursor *cursor, JsonObject object)
{
	wchar_t *buf = cursor->buf;
	struct _JsonObjectItem *item = (struct _JsonObjectItem *) object;

	cursor->pos++;
	if (buf[cursor->pos] == '}') {
		cursor->pos++;
		item->value_type = JSON_VALUE_EMPTY;
		return TRUE;
	}

	while (cursor->pos < cursor->max) {
		if (buf[cursor->pos] != '\"')
			return FALSE;

		// Tag
		cursor->pos++;
		item->tag = buf + cursor->pos;
		while (cursor->pos < cursor->max && buf[cursor->pos] != '\"') {
			cursor->pos++;
			item->tag_len++;
		}
		if (cursor->pos == cursor->max)
			return FALSE;

		// Seprator
		cursor->pos++;
		if (buf[cursor->pos] != ':')
			return FALSE;

		// Value
		cursor->pos++;
		if(!json_parse_value(cursor, (JsonItem) item))
			return FALSE;

		// Next
		if (buf[cursor->pos] == '}') {
			cursor->pos++;
			break;
		}
		if (buf[cursor->pos] != ',')
			return FALSE;

		cursor->pos++;
		item->next = (JsonItem) calloc(1, sizeof(struct _JsonObjectItem));
		item = (JsonObjectItem) item->next;
	}

	return TRUE;
}

static BOOL json_parse_array(JsonCursor *cursor, JsonArray item)
{
	wchar_t *buf = cursor->buf;

	if (buf[cursor->pos] != '[')
		return FALSE;

	cursor->pos++;
	if (buf[cursor->pos] == ']') {
		cursor->pos++;
		item->value_type = JSON_VALUE_EMPTY;
		return TRUE;
	}

	while (cursor->pos < cursor->max) {
		if (!json_parse_value(cursor, (JsonItem) item))
			return FALSE;

		// Next
		if (buf[cursor->pos] == ']') {
			cursor->pos++;
			break;
		}
		if (buf[cursor->pos] != ',')
			return FALSE;

		cursor->pos++;
		item->next = (JsonItem) calloc(1, sizeof(struct _JsonItem));
		item = (JsonItem) item->next;
	}

	return TRUE;
}

BOOL json_parse_args(wchar_t * buf, JsonArray *item)
{
	JsonCursor cursor;
	BOOL success;

	json_init_cursor(buf, &cursor);

	*item = (JsonArray) calloc(1, sizeof(struct _JsonItem));
	success = json_parse_array(&cursor, *item);
	if (success && cursor.pos == cursor.max)
		return TRUE;

	return FALSE;
}

static void json_free_item(JsonItem item)
{
	JsonItem current;

	while (item != NULL) {
		current = item;
		switch (item->value_type) {
		case JSON_VALUE_ARRAY:
			json_free_item((JsonItem) current->value.as_array);
			break;
		case JSON_VALUE_OBJECT:
			json_free_item((JsonItem) current->value.as_object);
			break;
		default:
			break;
		}

		item = item->next;
		free(current);
	}
}

void json_free_args(JsonArray item)
{
	json_free_item((JsonItem) item);
}

JsonItem json_array_get_next(JsonItem item)
{
	return item->next;
}

JsonValueType json_get_value_type(JsonItem item)
{
	return item->value_type;
}

int json_get_int_value(JsonItem item)
{
	return item->value.as_int;
}

INT64 json_get_int64_value(JsonItem item)
{
	return item->value.as_int64;
}

BOOL json_get_bool_value(JsonItem item)
{
	return item->value.as_bool;
}

double json_get_double_value(JsonItem item)
{
	return item->value.as_double;
}

static wchar_t decode_unicode_char(const wchar_t *text)
{
	wchar_t val = 0;
	int i;
	const BYTE *buf = (const BYTE *) text;

	for(i = 1; i <= 4; i++) {
		BYTE c = buf[i];
		val <<= 4;
		if(isdigit(c))
			val += c - '0';
		else if(c >= 'a' && c <= 'f')
			val += c - 'a' + 10;
		else if(c >= 'A' && c <= 'F')
			val += c - 'A' + 10;
		else
			return 0;
	}

	return val;
}

wchar_t *json_get_string_value(JsonItem item)
{
	size_t src_index = 0;
	size_t val_index = 0;
	const wchar_t *text = item->value.as_string;

	wchar_t *val = (wchar_t*) malloc(sizeof(wchar_t) * (item->value_as_string_len + 1));

	while (src_index < item->value_as_string_len) {
		if (text[src_index] == '\\') {
			src_index++;
			if (src_index == item->value_as_string_len)
				break;

			switch(text[src_index]) {
			case 'u':
				if ((item->value_as_string_len - src_index) > 3) {
					wchar_t unicode_val = decode_unicode_char(text + src_index);
					if (val) {
						val[val_index] = unicode_val;
						src_index += 3;
					} else
						val[val_index] = text[src_index];
				} else
					val[val_index] = text[src_index];
				break;
			case '"':
			case '\\':
			case '/':
				val[val_index] = text[src_index];
				break;
			case 'b':
				val[val_index] = '\b';
				break;
			case 'f':
				val[val_index] = '\f';
				break;
			case 'n':
				val[val_index] = '\n';
				break;
			case 'r':
				val[val_index] = '\r';
				break;
			case 't':
				val[val_index] = '\t';
				break;
			default:
				val[val_index] = text[src_index];
			}

			val_index++;
			src_index++;
		} else
			val[val_index++] = text[src_index++];
	}

	val[val_index] = 0;

	return val;
}

JsonObject json_get_object_value(JsonItem item)
{
	return item->value.as_object;
}

JsonArray json_get_array_value(JsonItem item)
{
	return item->value.as_array;
}

static int json_container_item_count(JsonItem item)
{
	int count = 0;

	while (item != NULL) {
		item = item->next;
		count++;
	}

	return count;
}

static JsonItem json_container_item_at(JsonItem item, int position)
{
	while (item != NULL && position) {
		item = item->next;
		position--;
	}

	return item;
}

int json_array_item_count(JsonArray array)
{
	return json_container_item_count((JsonItem) array);
}

JsonItem json_array_item_at(JsonArray array, int position)
{
	return json_container_item_at((JsonItem) array, position);
}

static BOOL is_type_compatible(JsonValueType current, JsonValueType expected)
{
	if (expected & JSON_VALUE_INT64)
		return ((expected & current) || (JSON_VALUE_INT & current));

	return (expected & current);
}

static BOOL internal_json_array_validate_contents(JsonArray array, JsonValueType type, va_list args)
{
	while(type != JSON_VALUE_INVALID) {
		if (!array)
			return FALSE;
		if (!is_type_compatible(array->value_type, type))
			return FALSE;

		array = array->next;
		type = va_arg(args, JsonValueType);
	}

	return TRUE;
}

BOOL json_array_validate_contents(JsonArray array, JsonValueType type, ...)
{
	va_list args;

	va_start(args, type);
	return internal_json_array_validate_contents(array, type, args);
}

BOOL json_parse_and_validate_args(wchar_t * buf, JsonArray *array, JsonValueType type, ...)
{
	va_list args;

	if (!json_parse_args(buf, array))
		return FALSE;

	va_start(args, type);
	return internal_json_array_validate_contents(*array, type, args);
}

int json_object_prop_count(JsonObject object)
{
	return json_container_item_count((JsonItem) object);
}

JsonObjectItem json_object_prop_at(JsonObject object, int position)
{
	return (JsonObjectItem) json_container_item_at((JsonItem) object, position);
}

JsonObjectItem json_object_find_prop(JsonObject object, const wchar_t *id, JsonValueType type)
{
	while (object != NULL) {
		if (!wcsncmp(id, (wchar_t *) object->tag, wcslen(id)) &&
			wcslen(id) == object->tag_len && is_type_compatible(object->value_type, type))
				return (JsonObjectItem) object;
		object = (struct _JsonObjectItem *) object->next;
	}

	return NULL;
}

wchar_t *json_object_get_prop_id(JsonObject object)
{
	wchar_t *id = (wchar_t*) malloc(sizeof(wchar_t) * (object->tag_len + 1));

	wcsncpy_s(id, object->tag_len + 1, object->tag, object->tag_len);

	return id;
}

JsonObjectItem json_object_get_next(JsonObjectItem item)
{
	return (JsonObjectItem) item->next;
}


text:
package mpfluentd

import (
	"crypto/md5"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"regexp"
	"strings"

	mp "github.com/mackerelio/go-mackerel-plugin-helper"
)

// FluentdMetrics plugin for fluentd
type FluentdMetrics struct {
	Target          string
	Tempfile        string
	pluginType      string
	pluginIDPattern *regexp.Regexp

	plugins []FluentdPluginMetrics
}

// FluentdPluginMetrics metrics
type FluentdPluginMetrics struct {
	RetryCount            uint64 `json:"retry_count"`
	BufferQueueLength     uint64 `json:"buffer_queue_length"`
	BufferTotalQueuedSize uint64 `json:"buffer_total_queued_size"`
	OutputPlugin          bool   `json:"output_plugin"`
	Type                  string `json:"type"`
	PluginCategory        string `json:"plugin_category"`
	PluginID              string `json:"plugin_id"`
	normalizedPluginID    string
}

// FluentMonitorJSON monitor json
type FluentMonitorJSON struct {
	Plugins []FluentdPluginMetrics `json:"plugins"`
}

var normalizePluginIDRe = regexp.MustCompile(`[^-a-zA-Z0-9_]`)

func normalizePluginID(in string) string {
	return normalizePluginIDRe.ReplaceAllString(in, "_")
}

func (fpm FluentdPluginMetrics) getNormalizedPluginID() string {
	if fpm.normalizedPluginID == "" {
		fpm.normalizedPluginID = normalizePluginID(fpm.PluginID)
	}
	return fpm.normalizedPluginID
}

func (f *FluentdMetrics) parseStats(body []byte) (map[string]interface{}, error) {
	var j FluentMonitorJSON
	err := json.Unmarshal(body, &j)
	f.plugins = j.Plugins

	metrics := make(map[string]interface{})
	for _, p := range f.plugins {
		if f.nonTargetPlugin(p) {
			continue
		}
		pid := p.getNormalizedPluginID()
		metrics["fluentd.retry_count."+pid] = float64(p.RetryCount)
		metrics["fluentd.buffer_queue_length."+pid] = float64(p.BufferQueueLength)
		metrics["fluentd.buffer_total_queued_size."+pid] = float64(p.BufferTotalQueuedSize)
	}
	return metrics, err
}

func (f *FluentdMetrics) nonTargetPlugin(plugin FluentdPluginMetrics) bool {
	if plugin.PluginCategory != "output" {
		return true
	}
	if f.pluginType != "" && f.pluginType != plugin.Type {
		return true
	}
	if f.pluginIDPattern != nil && !f.pluginIDPattern.MatchString(plugin.PluginID) {
		return true
	}
	return false
}

// FetchMetrics interface for mackerelplugin
func (f FluentdMetrics) FetchMetrics() (map[string]interface{}, error) {
	req, err := http.NewRequest(http.MethodGet, f.Target, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("User-Agent", "mackerel-plugin-fluentd")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	return f.parseStats(body)
}

// GraphDefinition interface for mackerelplugin
func (f FluentdMetrics) GraphDefinition() map[string]mp.Graphs {
	return map[string]mp.Graphs{
		"fluentd.retry_count": {
			Label: "Fluentd retry count",
			Unit:  "integer",
			Metrics: []mp.Metrics{
				{Name: "*", Label: "%1", Diff: false},
			},
		},
		"fluentd.buffer_queue_length": {
			Label: "Fluentd queue length",
			Unit:  "integer",
			Metrics: []mp.Metrics{
				{Name: "*", Label: "%1", Diff: false},
			},
		},
		"fluentd.buffer_total_queued_size": {
			Label: "Fluentd buffer total queued size",
			Unit:  "integer",
			Metrics: []mp.Metrics{
				{Name: "*", Label: "%1", Diff: false},
			},
		},
	}
}

// Do the plugin
func Do() {
	host := flag.String("host", "localhost", "fluentd monitor_agent host")
	port := flag.String("port", "24220", "fluentd monitor_agent port")
	pluginType := flag.String("plugin-type", "", "Gets the metric that matches this plugin type")
	pluginIDPatternString := flag.String("plugin-id-pattern", "", "Gets the metric that matches this plugin id pattern")
	tempFile := flag.String("tempfile", "", "Temp file name")
	flag.Parse()

	var pluginIDPattern *regexp.Regexp
	var err error
	if *pluginIDPatternString != "" {
		pluginIDPattern, err = regexp.Compile(*pluginIDPatternString)
		if err != nil {
			fmt.Fprintf(os.Stderr, "failed to exec mackerel-plugin-fluentd: invalid plugin-id-pattern: %s\n", err)
			os.Exit(1)
		}
	}

	f := FluentdMetrics{
		Target:          fmt.Sprintf("http://%s:%s/api/plugins.json", *host, *port),
		Tempfile:        *tempFile,
		pluginType:      *pluginType,
		pluginIDPattern: pluginIDPattern,
	}

	helper := mp.NewMackerelPlugin(f)

	helper.Tempfile = *tempFile
	if *tempFile == "" {
		tempFileSuffix := []string{*host, *port}
		if *pluginType != "" {
			tempFileSuffix = append(tempFileSuffix, *pluginType)
		}
		if *pluginIDPatternString != "" {
			tempFileSuffix = append(tempFileSuffix, fmt.Sprintf("%x", md5.Sum([]byte(*pluginIDPatternString))))
		}
		helper.SetTempfileByBasename(fmt.Sprintf("mackerel-plugin-fluentd-%s", strings.Join(tempFileSuffix, "-")))
	}

	helper.Run()
}


text:
<?php

class ShowLostPasswordPage extends AbstractLoginPage
{
	public static $requireModule = 0;

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

	function show()
	{
		$universeSelect	= $this->getUniverseSelector();

		$this->assign(array(
			'universeSelect'	=> $universeSelect
		));

		$this->display('page.lostPassword.default.tpl');
	}

	function newPassword()
	{
		global $LNG;
		$userID			= HTTP::_GP('u', 0);
		$validationKey	= HTTP::_GP('k', '');

		$db = Database::get();

		$sql = "SELECT COUNT(*) as state FROM %%LOSTPASSWORD%% WHERE userID = :userID AND `key` = :validationKey AND `time` > :time AND hasChanged = 0;";
		$isValid = $db->selectSingle($sql, array(
			':userID'			=> $userID,
			':validationKey'	=> $validationKey,
			':time'				=> (TIMESTAMP - 1800)
		), 'state');

		if(empty($isValid))
		{
			$this->printMessage($LNG['passwordValidInValid'], array(array(
				'label'	=> $LNG['passwordBack'],
				'url'	=> 'index.php',
			)));
		}

		$newPassword	= uniqid();

		$sql = "SELECT username, email_2 as mail, universe FROM %%USERS%% WHERE id = :userID;";
		$userData = $db->selectSingle($sql, array(
			':userID'	=> $userID,
		));

		$config			= Config::get($userData['universe']);

		$MailRAW		= $LNG->getTemplate('email_lost_password_changed');
		$MailContent	= str_replace(array(
			'{USERNAME}',
			'{GAMENAME}',
			'{GAMEMAIL}',
			'{PASSWORD}',
		), array(
			$userData['username'],
			$config->game_name.' - '.$config->uni_name,
			$config->smtp_sendmail,
			$newPassword,
		), $MailRAW);

		$sql = "UPDATE %%USERS%% SET password = :newPassword WHERE id = :userID;";
		$db->update($sql, array(
			':userID'		=> $userID,
			':newPassword'	=> PlayerUtil::cryptPassword($newPassword)
		));

		require 'includes/classes/Mail.class.php';

		$subject	= sprintf($LNG['passwordChangedMailTitle'], $config->game_name);
		Mail::send($userData['mail'], $userData['username'], $subject, $MailContent);

		$sql = "UPDATE %%LOSTPASSWORD%% SET hasChanged = 1 WHERE userID = :userID AND `key` = :validationKey;";
		$db->update($sql, array(
			':userID'			=> $userID,
			':validationKey'	=> $validationKey
		));

		$this->printMessage($LNG['passwordChangedMailSend'], array(array(
			'label'	=> $LNG['passwordNext'],
			'url'	=> 'index.php',
		)));
	}

	function send()
	{
		global $LNG;
		$username	= HTTP::_GP('username', '', UTF8_SUPPORT);
		$mail		= HTTP::_GP('mail', '', true);

		$errorMessages	= array();

		if(empty($username))
		{
			$errorMessages[]	= $LNG['passwordUsernameEmpty'];
		}

		if(empty($mail))
		{
			$errorMessages[]	= $LNG['passwordErrorMailEmpty'];
		}

		$config	= Config::get();

		if ($config->capaktiv == 1)
		{
            require('includes/libs/reCAPTCHA/autoload.php');

            $recaptcha = new \ReCaptcha\ReCaptcha($config->capprivate);
            $resp = $recaptcha->verify(HTTP::_GP('g-recaptcha-response', ''), Session::getClientIp());
            if (!$resp->isSuccess())
            {
                $errorMessages[]	=  $LNG['registerErrorCaptcha'];
			}
		}

		if(!empty($errorMessages))
		{
			$message	= implode("<br>\r\n", $errorMessages);
			$this->printMessage($message, array(array(
				'label'	=> $LNG['passwordBack'],
				'url'	=> 'index.php?page=lostPassword',
			)));
		}

		$db = Database::get();

		$sql = "SELECT id FROM %%USERS%% WHERE universe = :universe AND username = :username AND email_2 = :mail;";
		$userID = $db->selectSingle($sql, array(
			':universe'	=> Universe::current(),
			':username'	=> $username,
			':mail'		=> $mail
		), 'id');

		if(empty($userID))
		{
			$this->printMessage($LNG['passwordErrorUnknown'], array(array(
				'label'	=> $LNG['passwordBack'],
				'url'	=> 'index.php?page=lostPassword',
			)));
		}

		$sql = "SELECT COUNT(*) as state FROM %%LOSTPASSWORD%% WHERE userID = :userID AND time > :time AND hasChanged = 0;";
		$hasChanged = $db->selectSingle($sql, array(
			':userID'	=> $userID,
			':time'		=> (TIMESTAMP - 86400)
		), 'state');

		if(!empty($hasChanged))
		{
			$this->printMessage($LNG['passwordErrorOnePerDay'], array(array(
				'label'	=> $LNG['passwordBack'],
				'url'	=> 'index.php?page=lostPassword',
			)));
		}

		$validationKey	= md5(uniqid());

		$MailRAW		= $LNG->getTemplate('email_lost_password_validation');

		$MailContent	= str_replace(array(
			'{USERNAME}',
			'{GAMENAME}',
			'{VALIDURL}',
		), array(
			$username,
			$config->game_name.' - '.$config->uni_name,
			HTTP_PATH.'index.php?page=lostPassword&mode=newPassword&u='.$userID.'&k='.$validationKey,
		), $MailRAW);

		require 'includes/classes/Mail.class.php';

		$subject	= sprintf($LNG['passwordValidMailTitle'], $config->game_name);

		Mail::send($mail, $username, $subject, $MailContent);

		$sql = "INSERT INTO %%LOSTPASSWORD%% SET userID = :userID, `key` = :validationKey, `time` = :timestamp, fromIP = :remoteAddr;";
		$db->insert($sql, array(
			':userID'		=> $userID,
			':timestamp'	=> TIMESTAMP,
			':validationKey'=> $validationKey,
			':remoteAddr'	=> Session::getClientIp()
		));

		$this->printMessage($LNG['passwordValidMailSend'], array(array(
			'label'	=> $LNG['passwordNext'],
			'url'	=> 'index.php',
		)));
	}
}