text:
namespace mozart { namespace boostenv {

class BoostVM;

//////////////////////////
// BaseSocketConnection //
//////////////////////////

template <typename T, typename Protocol>
class BaseSocketConnection: public std::enable_shared_from_this<T> {
public:
  typedef Protocol protocol;

public:
  typedef std::shared_ptr<T> pointer;

  static pointer create(BoostEnvironment& env, VMIdentifier vm) {
    return std::make_shared<T>(env, vm);
  }

public:
  inline
  BaseSocketConnection(BoostEnvironment& env, VMIdentifier vm);

public:
  typename protocol::socket& socket() {
    return _socket;
  }

  std::vector<char>& getReadData() {
    return _readData;
  }

  std::vector<char>& getWriteData() {
    return _writeData;
  }

  inline
  void startAsyncRead(const ProtectedNode& tailNode,
                      const ProtectedNode& statusNode);

  inline
  void startAsyncReadSome(const ProtectedNode& tailNode,
                          const ProtectedNode& statusNode);

  inline
  void startAsyncWrite(const ProtectedNode& statusNode);

protected:
  inline
  void readHandler(const boost::system::error_code& error,
                   size_t bytes_transferred,
                   const ProtectedNode& tailNode,
                   const ProtectedNode& statusNode);

protected:
  BoostEnvironment& env;
  VMIdentifier vm;
  typename protocol::socket _socket;

  std::vector<char> _readData;
  std::vector<char> _writeData;
};

} }

#endif // MOZART_BOOSTENVUTILS_DECL_H


text:
import logging
import sys
import warnings

from django         import http
from django.conf    import settings
from django.core    import exceptions

from log_handler import DatabaseLogHandler

DEFAULT_IGNORES = (http.Http404, exceptions.PermissionDenied)

class ExceptionLoggingMiddleware(object):
    def __init__(self):
        msg = "ExceptionLoggingMiddleware is deprecated; Remove it and " + \
            "add DatabaseLogHandler to your logging config instead"
        warnings.warn(msg, DeprecationWarning)
        if settings.DEBUG:
            raise exceptions.MiddlewareNotUsed
        self.log_handler = DatabaseLogHandler()

    def process_exception(self, request, _):
        record = logging.makeLogRecord({"exc_info": sys.exc_info(),
                                        "request": request})
        self.log_handler.emit(record)

redpajama_set_name: RedPajamaGithub


text:
node.override['smokepling']['slave_mode'] = true

apt_update 'update'
include_recipe 'smokeping::slave'


text:
'use strict'
/*global module, noneFn*/

var thunk = require('../thunks.js')()

thunk(function *() {
  // catch error by yourself
  try {
    yield function (callback) { noneFn() }
  } catch (err) {
    console.log('catched a error:', err)
  }

  yield function (callback) { throw new Error('some error') }
})(function (error, res) {
  // catch the second error by Thunk
  console.log(error, res)
})(function *() {
  yield function (callback) { throw new Error('some error2') }
})()
// throw error to system
// Error: some error2...


text:
#########################
Using CodeIgniter's Model
#########################

.. contents::
    :local:
    :depth: 2

Manual Model Creation
=====================

You do not need to extend any special class to create a model for your application. All you need is to get an
instance of the database connection and you're good to go.

::

	use \CodeIgniter\Database\ConnectionInterface;

	class UserModel
	{
		protected $db;

		public function __construct(ConnectionInterface &$db)
		{
			$this->db =& $db;
		}
	}

CodeIgniter's Model
===================

CodeIgniter does provide a model class that provides a few nice features, including:

- automatic database connection
- basic CRUD methods
- in-model validation
- automatic pagination
- and more

This class provides a solid base from which to build your own models, allowing you to
rapidly build out your application's model layer.

Creating Your Model
===================

To take advantage of CodeIgniter's model, you would simply create a new model class
that extends ``CodeIgniter\Model``::

	class UserModel extends \CodeIgniter\Model
	{

	}

This empty class provides convenient access to the database connection, the Query Builder,
and a number of additional convenience methods.

Connecting to the Database
--------------------------

When the class is first instantiated, if no database connection instance is passed to constructor,
it will automatically connect to the default database group, as set in the configuration. You can
modify which group is used on a per-model basis by adding the DBGroup property to your class.
This ensures that within the model any references to ``$this->db`` are made through the appropriate
connection.
::

	class UserModel extends \CodeIgniter\Model
	{
		protected $DBGroup = 'group_name';
	}

You would replace "group_name" with the name of a defined database group from the database
configuration file.

Configuring Your Model
----------------------

The model class has a few configuration options that can be set to allow the class' methods
to work seamlessly for you. The first two are used by all of the CRUD methods to determine
what table to use and how we can find the required records::

	class UserModel extends \CodeIgniter\Model
	{
		protected $table      = 'users';
		protected $primaryKey = 'id';

		protected $returnType = 'array';
		protected $useSoftDeletes = true;

		protected $allowedFields = ['name', 'email'];

		protected $useTimestamps = false;

		protected $validationRules    = [];
		protected $validationMessages = [];
		protected $skipValidation     = false;
	}

**$table**

Specifies the database table that this model primarily works with. This only applies to the
built-in CRUD methods. You are not restricted to using only this table in your own
queries.

**$primaryKey**

This is the name of the column that uniquely identifies the records in this table. This
does not necessarilly have to match the primary key that is specified in the database, but
is used with methods like ``find()`` to know what column to match the specified value to.

**$returnType**

The Model's CRUD methods will take a step of work away from you and automatically return
the resulting data, instead of the Result object. This setting allows you to define
the type of data that is returned. Valid values are 'array', 'object', or the fully
qualified name of a class that can be used with the Result object's getCustomResultObject()
method.

**$useSoftDeletes**

If true, then any delete* method calls will simply set a flag in the database, instead of
actually deleting the row. This can preserve data when it might be referenced elsewhere, or
can maintain a "recycle bin" of objects that can be restored, or even simply preserve it as
part of a security trail. If true, the find* methods will only return non-deleted rows, unless
the withDeleted() method is called prior to calling the find* method.

This requires an INT or TINYINT field to be present in the table for storing state.The default field name is  ``deleted`` however this name can be configured to any name of your choice by using $deletedField property.

**$allowedFields**

This array should be updated with the field names that can be set during save, insert, or
update methods. Any field names other than these will be discarded. This helps to protect
against just taking input from a form and throwing it all at the model, resulting in
potential mass assignment vulnerabilities.

**$useTimestamps**

This boolean value determines whether the current date is automatically added to all inserts
and updates. If true, will set the current time in the format specified by $dateFormat. This
requires that the table have columns named 'created_at' and 'updated_at' in the appropriate
data type.

**$dateFormat**

This value works with $useTimestamps to ensure that the correct type of date value gets
inserted into the database. By default, this creates DATETIME values, but valid options
are: datetime, date, or int (a PHP timestamp).

**$validationRules**

Contains either an array of validation rules as described in :ref:`validation-array`
or a string containing the name of a validation group, as described in the same section.
Described in more detail below.

**$validationMessages**

Contains an array of custom error messages that should be used during validation, as
described in :ref:`validation-custom-errors`. Described in more detail below.

**$skipValidation**

Whether validation should be skipped during all ``inserts`` and ``updates``. The default
value is false, meaning that data will always attempt to be validated. This is
primarily used by the ``skipValidation()`` method, but may be changed to ``true`` so
this model will never validate.

**$beforeInsert**
**$afterInsert**
**$beforeUpdate**
**$afterUpdate**
**afterFind**
**afterDelete**

These arrays allow you to specify callback methods that will be ran on the data at the
time specified in the property name.

Working With Data
=================

Finding Data
------------

Several functions are provided for doing basic CRUD work on your tables, including find(),
insert(), update(), delete() and more.

**find()**

Returns a single row where the primary key matches the value passed in as the first parameter::

	$user = $userModel->find($user_id);

The value is returned in the format specified in $returnType.

You can specify more than one row to return by passing an array of primaryKey values instead
of just one::

	$users = $userModel->find([1,2,3]);

**findWhere()**

Allows you to specify one or more criteria that must be matched against the data. Returns
all rows that match::

	// Use simple where
	$users = $userModel->findWhere('role_id >', '10');

	// Use array of where values
	$users = $userModel->findWhere([
		'status'  => 'active',
		'deleted' => 0
	]);

**findAll()**

Returns all results::

	$users = $userModel->findAll();

This query may be modified by interjecting Query Builder commands as needed prior to calling this method::

	$users = $userModel->where('active', 1)
	                   ->findAll();

You can pass in a limit and offset values as the first and second
parameters, respectively::

	$users = $userModel->findAll($limit, $offset);

**first()**

Returns the first row in the result set. This is best used in combination with the query builder.
::

	$user = $userModel->where('deleted', 0)
	                  ->first();

**withDeleted()**

If $useSoftDeletes is true, then the find* methods will not return any rows where 'deleted = 1'. To
temporarily override this, you can use the withDeleted() method prior to calling the find* method.
::

	// Only gets non-deleted rows (deleted = 0)
	$activeUsers = $userModel->findAll();

	// Gets all rows
	$allUsers = $userModel->withDeleted()
	                      ->findAll();

**onlyDeleted()**

Whereas withDeleted() will return both deleted and not-deleted rows, this method modifies
the next find* methods to return only soft deleted rows::

	$deletedUsers = $userModel->onlyDeleted()
	                          ->findAll();

Saving Data
-----------

**insert()**

An associative array of data is passed into this method as the only parameter to create a new
row of data in the database. The array's keys must match the name of the columns in $table, while
the array's values are the values to save for that key::

	$data = [
		'username' => 'darth',
		'email'    => 'd.vader@theempire.com'
	];

	$userModel->insert($data);

**update()**

Updates an existing record in the database. The first parameter is the $primaryKey of the record to update.
An associative array of data is passed into this method as the second parameter. The array's keys must match the name
of the columns in $table, while the array's values are the values to save for that key::

	$data = [
		'username' => 'darth',
		'email'    => 'd.vader@theempire.com'
	];

	$userModel->update($id, $data);

**save()**

This is a wrapper around the insert() and update() methods that handles inserting or updating the record
automatically, based on whether it finds an array key matching the $primaryKey value::

	// Defined as a model property
	$primaryKey = 'id';

	// Does an insert()
	$data = [
		'username' => 'darth',
		'email'    => 'd.vader@theempire.com'
	];

	$userModel->save($data);

	// Performs an update, since the primary key, 'id', is found.
	$data = [
		'id'       => 3,
		'username' => 'darth',
		'email'    => 'd.vader@theempire.com'
	];
	$userModel->save($data);

The save method also can make working with custom class result objects much simpler by recognizing a non-simple
object and grabbing its public and protected values into an array, which is then passed to the appropriate
insert or update method. This allows you to work with Entity classes in a very clean way. Entity classes are
simple classes that represent a single instance of an object type, like a user, a blog post, job, etc. This
class is responsible for maintaining the business logic surrounding the object itself, like formatting
elements in a certain way, etc. They shouldn't have any idea about how they are saved to the database. At their
simplest, they might look like this::

	namespace App\Entities;

	class Job
	{
		protected $id;
		protected $name;
		protected $description;

		public function __get($key)
		{
			if (property_exists($this, $key))
			{
				return $this->$key;
			}
		}

		public function __set($key, $value)
		{
			if (property_exists($this, $key))
			{
				$this->$key = $value;
			}
		}
	}

A very simple model to work with this might look like::

	class JobModel extends \CodeIgniter\Model
	{
		protected $table = 'jobs';
		protected $returnType = '\App\Entities\Job';
		protected $allowedFields = [
			'name', 'description'
		];
	}

This model works with data from the ``jobs`` table, and returns all results as an instance of ``App\Entities\Job``.
When you need to persist that record to the database, you will need to either write custom methods, or use the
model's ``save()`` method to inspect the class, grab any public and private properties, and save them to the database::

	// Retrieve a Job instance
	$job = $model->find(15);

	// Make some changes
	$job->name = "Foobar";

	// Save the changes
	$model->save($job);

.. note:: If you find yourself working with Entities a lot, CodeIgniter provides a built-in :doc:`Entity class </database/entities>`
	that provides several handy features that make developing Entities simpler.

Deleting Data
-------------

**delete()**

Takes a primary key value as the first parameter and deletes the matching record from the model's table::

	$userModel->delete(12);

If the model's $useSoftDeletes value is true, this will update the row to set 'deleted = 1'. You can force
a permanent delete by setting the second parameter as true.

**deleteWhere()**

Deletes multiple records from the model's table based on the criteria pass into the first two parameters.
::

	// Simple where
	$userMdoel->deleteWhere('status', 'inactive');

	// Complex where
	$userModel->deleteWhere([
		'status'      => 'inactive',
		'warn_lvl >=' => 50
	]);

If the model's $useSoftDeletes value is true, this will update the rows to set 'deleted = 1'. You can force
a permanent delete by setting the third parameter as true.

**purgeDeleted()**

Cleans out the database table by permanently removing all rows that have 'deleted = 1'. ::

	$userModel->purgeDeleted();

Validating Data
---------------

For many people, validating data in the model is the preferred way to ensure the data is kept to a single
standard, without duplicating code. The Model class provides a way to automatically have all data validated
prior to saving to the database with the ``insert()``, ``update()``, or ``save()`` methods.

The first step is to fill out the ``$validationRules`` class property with the fields and rules that should
be applied. If you have custom error message that you want to use, place them in the ``$validationMessages`` array::

	class UserModel extends Model
	{
		protected $validationRules    = [
			'username'     => 'required|alpha_numeric_space|min_length[3]',
			'email'        => 'required|valid_email|is_unique[users.email]',
			'password'     => 'required|min_length[8]',
			'pass_confirm' => 'required_with[password]|matches[password]'
		];

		protected $validationMessages = [
			'email'        => [
				'is_unique' => 'Sorry. That email has already been taken. Please choose another.'
			]
		];
	}

Now, whenever you call the ``insert()``, ``update()``, or ``save()`` methods, the data will be validated. If it fails,
the model will return boolean **false**. You can use the ``errors()`` method to retrieve the validation errors::

	if ($model->save($data) === false)
	{
		return view('updateUser', ['errors' => $model->errors()];
	}

This returns an array with the field names and their associated errors that can be used to either show all of the
errors at the top of the form, or to display them individually::

	<?php if (! empty($errors)) : ?>

		<?php foreach ($errors as $field => $error) : ?>

<?= $error ?>

		<?php endforeach ?>

	<?php endif ?>

If you'd rather organize your rules and error messages within the Validation configuration file, you can do that
and simply set ``$validationRules`` to the name of the validation rule group you created::

	class UserModel extends Model
	{
		protected $validationRules = 'users';
	}

Validation Placeholders
-----------------------

The model provides a simple method to replace parts of your rules based on data that's being passed into it. This
sounds fairly obscure but can be especially handy with the ``is_unique`` validation rule. Placeholders are simply
the name of the field (or array key) that was passed in as $data surrounded by curly brackets. It will be
replaced by the **value** of the matched incoming field. An example should clarify this::

    protected $validationRules = [
        'email' => 'required|valid_email|is_unique[users.email,id,{id}]'
    ];

In this set of rules, it states that the email address should be unique in the database, except for the row
that has an id matching the placeholder's value. Assuming that the form POST data had the following::

    $_POST = [
        'id' => 4,
        'email' => 'foo@example.com'
    ]

then the ``{id}`` placeholder would be replaced with the number **4**, giving this revised rule::

    protected $validationRules = [
        'email' => 'required|valid_email|is_unique[users.email,id,4]'
    ];

So it will ignore the row in the database that has ``id=4`` when it verifies the email is unique.

This can also be used to create more dynamic rules at runtime, as long as you take care that any dynamic
keys passed in don't conflict with your form data.

Protecting Fields
-----------------

To help protect against Mass Assignment Attacks, the Model class **requires** that you list all of the field names
that can be changed during inserts and updates in the ``$allowedFields`` class property. Any data provided
in addition to these will be removed prior to hitting the database. This is great for ensuring that timestamps,
or primary keys do not get changed.
::

	protected $allowedFields = ['name', 'email', 'address'];

Occasionally, you will find times where you need to be able to change these elements. This is often during
testing, migrations, or seeds. In these cases, you can turn the protection on or off::

	$model->protect(false)
	      ->insert($data)
	      ->protect(true);

Working With Query Builder
--------------------------

You can get access to a shared instance of the Query Builder for that model's database connection any time you
need it::

	$builder = $userModel->builder();

This builder is already setup with the model's $table.

You can also use Query Builder methods and the Model's CRUD methods in the same chained call, allowing for
very elegant use::

	$users = $userModel->where('status', 'active')
			   ->orderBy('last_login', 'asc')
			   ->findAll();

.. note:: You can also access the model's database connection seamlessly::

			$user_name = $userModel->escape($name);

Runtime Return Type Changes
----------------------------

You can specify the format that data should be returned as when using the find*() methods as the class property,
$returnType. There may be times that you would like the data back in a different format, though. The Model
provides methods that allow you to do just that.

.. note:: These methods only change the return type for the next find*() method call. After that,
			it is reset to its default value.

**asArray()**

Returns data from the next find*() method as associative arrays::

	$users = $userModel->asArray()->findWhere('status', 'active');

**asObject()**

Returns data from the next find*() method as standard objects or custom class intances::

	// Return as standard objects
	$users = $userModel->asObject()->findWhere('status', 'active');

	// Return as custom class instances
	$users = $userModel->asObject('User')->findWhere('status', 'active');

Processing Large Amounts of Data
--------------------------------

Sometimes, you need to process large amounts of data and would run the risk of running out of memory.
To make this simpler, you may use the chunk() method to get smaller chunks of data that you can then
do your work on. The first parameter is the number of rows to retrieve in a single chunk. The second
parameter is a Closure that will be called for each row of data.

This is best used during cronjobs, data exports, or other large tasks.
::

	$userModel->chunk(100, function ($data)
	{
		// do something.
		// $data is a single row of data.
	});

Model Events
============

There are several points within the model's execution that you can specify multiple callback methods to run.
These methods can be used to normalize data, hash passwords, save related entities, and much more. The following
points in the model's execution can be affected, each through a class property: **$beforeInsert**, **$afterInsert**,
**$beforeUpdate**, **afterUpdate**, **afterFind**, and **afterDelete**.

Defining Callbacks
------------------

You specify the callbacks by first creating a new class method in your model to use. This class will always
receive a $data array as its only parameter. The exact contents of the $data array will vary between events, but
will always contain a key named **data** that contains the primary data passed to original method. In the case
of the insert* or update* methods, that will be the key/value pairs that are being inserted into the database. The
main array will also contain the other values passed to the method, and be detailed later. The callback method
must return the original $data array so other callbacks have the full information.

::

	protected function hashPassword(array $data)
	{
		if (! isset($data['data']['password']) return $data;

		$data['data']['password_hash'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
		unse($data['data']['password'];

		return $data;
	}

Specifying Callbacks To Run
---------------------------

You specify when to run the callbacks by adding the method name to the appropriate class property (beforeInsert, afterUpdate,
etc). Multiple callbacks can be added to a single event and they will be processed one after the other. You can
use the same callback in multiple events::

	protected $beforeInsert = ['hashPassword'];
	protected $beforeUpdate = ['hashPassword'];

Event Parameters
----------------

Since the exact data passed to each callback varies a bit, here are the details on what is in the $data parameter
passed to each event:

================ =========================================================================================================
Event            $data contents
================ =========================================================================================================
beforeInsert      **data** = the key/value pairs that are being inserted. If an object or Entity class is passed to the
                  insert method, it is first converted to an array.
afterInsert       **data** = the original key/value pairs being inserted.
                  **result** = the results of the insert() method used through the Query Builder.
beforeUpdate      **id** = the primary key of the row being updated.
                  **data** = the key/value pairs that are being inserted. If an object or Entity class is passed to the
                  insert method, it is first converted to an array.
afterUpdate       **id** = the primary key of the row being updated.
                  **data** = the original key/value pairs being updated.
                  **result** = the results of the update() method used through the Query Builder.
afterFind         Varies by find* method. See the following:
- find()          **id** = the primary key of the row being searched for.
                  **data** = The resulting row of data, or null if no result found.
- findWhere()     **data** = the resulting rows of data, or null if no result found.
- findAll()       **data** = the resulting rows of data, or null if no result found.
                  **limit** = the number of rows to find.
                  **offset** = the number of rows to skip during the search.
- first()         **data** = the resulting row found during the search, or null if none found.
beforeDelete      Varies by delete* method. See the following:
- delete()        **id** = primary key of row being deleted.
                  **purge** = boolean whether soft-delete rows should be hard deleted.
- deleteWhere()   **key**/**value** = the key/value pair used to search for rows to delete.
                  **purge** = boolean whether soft-delete rows should be hard deleted.
afterDelete       Varies by delete* method. See the following:
- delete()        **id** = primary key of row being deleted.
                  **purge** = boolean whether soft-delete rows should be hard deleted.
                  **result** = the result of the delete() call on the Query Builder.
                  **data** = unused.
- deleteWhere()	  **key**/**value** = the key/value pair used to search for rows to delete.
                  **purge** boolean whether soft-delete rows should be hard deleted.
                  **result** = the result of the delete() call on the Query Builder.
                  **data** = unused.
================ =========================================================================================================


text:
title: 'WIFIRE Project'
url: https://wifire.ucsd.edu
image: assets/graphics/content/view--community-projects/projects/covers/WIFIRE.jpg
logo: assets/graphics/content/view--community-projects/projects/logos/project-logo-wifire.png
type: Modeling
location: USA
featured: true
---

The WIFIRE project integrates a variety of data sources to perform predictive modeling and analysis of wildfires. Data from OpenAQ enhances their situational awareness by letting them see the effects of air pollution for large wildfires.


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

namespace Azure.AI.TextAnalytics.Models
{
    internal partial class TextAnalyticsErrorInternal
    {
        internal static TextAnalyticsErrorInternal DeserializeTextAnalyticsErrorInternal(JsonElement element)
        {
            string code = default;
            string message = default;
            Optional<string> target = default;
            Optional<InnerError> innererror = default;
            Optional<IReadOnlyList<TextAnalyticsErrorInternal>> details = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("code"))
                {
                    code = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("message"))
                {
                    message = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("target"))
                {
                    target = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("innererror"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    innererror = InnerError.DeserializeInnerError(property.Value);
                    continue;
                }
                if (property.NameEquals("details"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<TextAnalyticsErrorInternal> array = new List<TextAnalyticsErrorInternal>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(DeserializeTextAnalyticsErrorInternal(item));
                    }
                    details = array;
                    continue;
                }
            }
            return new TextAnalyticsErrorInternal(code, message, target.Value, innererror.Value, Optional.ToList(details));
        }
    }
}


text:
layout: post
title: Go Challenge - 7
tags: [go challenge, golang]
---

![update.jpg](/images/update.jpg)

**Winners have been declared**

Winner #1 - **James Scott**

Winner #2 - **Daniel Skinner**

---

#### The October 2015 Go Challenge for developers (newbies included)

#### Francesc Campoy Flores: Author of the 7th Go Challenge

The 7th Go Challenge author is Francesc Campoy Flores who joined the Go team in 2012 as Developer Advocate after several years as a Python and C++ developer. His mission is to make Go useful and fun.

Francesc has this to say about the challenge:

> "Preparing this challenge got me so excited about the support for OpenGL and simple audio primitives that I had to concentrate on writing the description rather than hacking on my own virtual piano.

> Event based applications are easily modeled using goroutines and channels, and I expect this project will be a chance for everyone to experiment with them."

---

#### The Go Challenge 7

##### A piano on your phone

##### Preamble

The latest version of Go 1.5 released last month includes, among many other cool things, experimental support for mobile platforms such as Android and iOS.

I have personally played around with the the golang.org/x/mobile packages and thought this challenge would be a great opportunity to see what great projects people could come up.

**Goals of the challenge**

The goal is simple: build a virtual piano for mobile devices.

The piano should display a set of keys (some white, some black) as in real traditional pianos (see image below). When the user presses a key a sound should be played. How and what exactly the key sounds is left to your choice and artistic freedom.

![piano-octave](/images/piano-octave.png)

**Requirements of the challenge**

The resulting application should:

* run on Android (at least),
* uses the [golang.org/x/mobile/gl](https://godoc.org/golang.org/x/mobile/gl) to display a set of keys,
* use the [golang.org/x/mobile/exp/audio](https://godoc.org/golang.org/x/mobile/exp/audio) package to generate sounds
* have some way for the user to act on what sound is generated

**Bonus features**:

* use complex interactions other than simple taps
* allow the user to save/export the music generated
* create a web page where users can show their skills
* provide a way for different musicians to colaborate/compete

**Hints**

There's multiple ways to generate audio. You can use audio files quite easily, but it would be much more creative to provide a way to generate sounds "from scratch" with [https://godoc.org/golang.org/x/mobile/exp/audio/al](https://godoc.org/golang.org/x/mobile/exp/audio/al).

---

#### Challenge Rules and how to enter the Go Challenge?

By participating in this challenge, you agree to be bound by the Challenge Rules below:

* The Challenge is open to individuals.
* Evaluators cannot enter the challenge except under the "Just for Fun" category.
* Each entrant shall indemnify, defend, and hold JoshSoftware Pvt. Ltd. (who has sponsored the domain and is the organizer of these challenges) harmless from any third party claims arising from or related to that entrant's participation in the Challenge. In no event shall JoshSoftware Pvt. Ltd. be liable to an entrant for acts or omissions arising out of or related to the Challenge or that entrant's participation in the Challenge.
* Odds of winning depend on the number and quality of entries received.
* All taxes, including income taxes, are the sole responsibility of the winners.
* No prize substitution is permitted.
* Create a zip of your Go source code and test cases and send the zip file to **golangchallenge [at] gmail.com before 27th of October 2015 (6 am IST). Use [this link](http://www.worldtimeserver.com/convert_time_in_IN.aspx?y=2015&mo=10&d=27&h=6&mn=0) to find the equivalent time in your city/country**. No new solutions will be accepted after that. In the email mention **your full name, country of residence, twitter or GitHub id (if any) and participating under which category - Just participating | Participating and exploring further | Just for Fun | Anonymous entry**. We are accepting anonymous submissions and will evaluate them too but then these participants are not eligible for the prizes.
* We shall be publishing on this blog, a list of participant names. If you don't want your name to appear kindly mention the same in your email.
* You are allowed to re-submit your code if you feel it is necessary.
* After the challenge is over, all submissions will be made available [online on GitHub](https://github.com/golangchallenge/GCSolutions) under the [BSD 3-Clause License](http://opensource.org/licenses/BSD-3-Clause) or the [GNU General Public License, version 3 - GPL-3.0](http://opensource.org/licenses/GPL-3.0) unless a participant has indicated that his/her solution should not be made public before the challenge ends.

#### How will the challenge be evaluated?

Entries will be evaluated by the challenge author and a team of evaluators.

#### Questions?

If you have any questions about this challenge, please join the [golang-challenge channel on slack](http://t.co/n6EesY9Mmv) and ask your questions. This is a room for people who are going to participate in the Go Challenge. You can also send us an email at golangchallenge [at] gmail.com

#### Evaluators

[Nathan Youngman](https://twitter.com/nathany) had set the guidelines for evaluation for the first Go Challenge. Subsequently [Dominik Honnef](https://twitter.com/dominikhonnef) modified the guidelines based on his experience as an evaluator for the first challenge. [Austin Riendeau](https://github.com/apriendeau), [Cory LaNou](https://twitter.com/corylanou), [Edd Robinson](https://github.com/e-dard), [Gautam Dey](https://github.com/gdey), [Jyotiska NK](https://twitter.com/jyotiska_nk), [Kevin Gillette](https://twitter.com/kevingillette) and [Pravin Mishra](https://twitter.com/pravinmishra88) have agreed to go through all the submitted solutions of a challenge. They will comment and rank these solutions.

#### Best Solution

The author of the Go Challenge will decide the best five solutions. The author shall have the sole authority and discretion to select the award recipients.

#### Notification

The winning entries will be announced here on this blog. The winners will be sent their prizes by email/postal mail.

#### Prizes

The author of the challenge will select 2 winners and prizes will be awarded to them.

Here are some great prizes provided by our sponsors for the event.

_Winner 1_:

* [Apcera](https://www.apcera.com/) - [Go Gopher Messenger Bag](https://www.googlemerchandisestore.com/shop.axd/Search?keywords=gopher)
* [Cube Root Software](http://cuberoot.in/) - An eBook [Go-The Standard Library](https://leanpub.com/go-thestdlib)
* [Docker](https://www.docker.com/) - 1 ticket to DockerCon Europe in November.
* [InfluxDB](http://influxdb.com/) - A US$ 50 Amazon digital gift card.
* [Manning Publications Co.](http://manning.com/) - Two eBooks [Go Web Programming](http://www.manning.com/chang/) and [Go in Action](http://www.manning.com/ketelsen/)
* [Packt Publishing](https://www.packtpub.com/) - A print book [Mastering Concurrency in Go](https://www.packtpub.com/application-development/mastering-concurrency-go)
* [Qwinix Technologies](http://www.qwinixtech.com/) - An eBook [The Docker Book: Containerization is the new virtualization](http://goo.gl/6sJJTy)

_Winner 2_:

* [Anand D N](https://twitter.com/Wanderer140) - An eBook: [Mastering Go Web Services](http://shop.oreilly.com/product/9781783981304.do)
* [Apcera](https://www.apcera.com/) - [Go Gopher Squishable](https://www.googlemerchandisestore.com/shop.axd/Search?keywords=gopher)
* [InfluxDB](http://influxdb.com/) - A US$ 50 Amazon digital gift card.
* [Manning Publications Co.](http://manning.com/) - One eBook [Go Web Programming](http://www.manning.com/chang/)
* [Qwinix Technologies](http://www.qwinixtech.com/) - An eBook [The Docker Book: Containerization is the new virtualization](http://goo.gl/6sJJTy)

#### Challenge Solutions

All the solutions submitted by the participants will be available **[here](https://github.com/golangchallenge/GCSolutions)** after the challenge ends.

#### The Winners

![winner.png](/images/winner.png)

**Winner #1 - James Scott** works at [18F](https://18f.gsa.gov/) as an Innovation Specialist in Washington, D.C. where he is currently working on the [cloud.gov](https://cloud.gov/) project.

Throughout his career, he programmed in C++, Java, and Python. In early 2013, James first encountered Go and instantly fell in love. His passion for Go motivated him to integrate it not only into his personal projects but his professional projects as well. He is very excited about Go and looks forward to the language's future.

His [solution](https://bitbucket.org/jcscottiii/amadeus).

---

**Winner #2 - Daniel Skinner** is currently working at [The Smyth Group](http://thesmythgroup.com/) primarily as a lead android developer. He has been writing Go since mid-2012 and uses it for nearly all of his personal projects. Back when he was a budding engineer, picking a project to develop his skills was always problematic until he came across Victor Lazzarini's [SndObj Library](http://sndobj.sourceforge.net/). This challenge was a chance to get back to what he enjoys while SndObj served as an inspiration to provide something similar for Go.

His [solution](https://github.com/dskinner/snd/tree/master/example/piano).

---

#### Sponsors

This challenge's sponsors are: [Anand D N](https://twitter.com/Wanderer140), [Apcera](https://www.apcera.com/), [Cube Root Software](http://cuberoot.in/), [Docker](https://www.docker.com/), [InfluxDB](http://influxdb.com/), [JoshSoftware Pvt. Ltd.](http://www.joshsoftware.com/), [Manning Publications Co.](http://manning.com/), [Packt Publishing](https://www.packtpub.com/) and [Qwinix Technologies](http://www.qwinixtech.com/).

#### Credit

* The Gopher character is based on the Go mascot designed by Renée French and copyrighted under the Creative Commons Attribution 3.0 license.
* [GitHub](https://github.com/) for the yearly sponsorship of a [GitHub Bronze Organisation plan](https://github.com/pricing) for the Go Challenge.
* The Go Challenge is being organized by [JoshSoftware Pvt. Ltd.](http://www.joshsoftware.com/) with help from the Go community.


text:
package com.gilt.hackathon

import java.net.Socket
import java.io.{IOException, OutputStream, ByteArrayOutputStream, File}
import akka.actor.{PoisonPill, ActorRef, Actor}
import org.slf4j.LoggerFactory
import java.util.concurrent.TimeUnit

// tells a RadioStation to subscribe this RadioListener
case class Subscribe(actor: ActorRef)

// tells a RadioStation to unsubscribe this RadioListener
case class Unsubscribe(actor: ActorRef)

// tells a RadioListener to listen to this station
case class ListenTo(station: ActorRef)

// tells a RadioListener to push these bytes to its listener socket
case class Chunk(bytes: Array[Byte])

object RadioListener {
  val log = LoggerFactory.getLogger(classOf[RadioListener])
}

class RadioListener(socket: Socket) extends Actor {
  import RadioListener.log
  private var output: OutputStream = _
  private var station: ActorRef = _
  private var dead = false

  def receive = {
    case ListenTo(station) =>
      withCleanup {
        this.station = station
        new LineIterator(socket.getInputStream).takeWhile(_ != "")
        station ! Subscribe(self)
        output = socket.getOutputStream
        IcyResponder.writeResponseHeaders(output, "scala radio streamer", Server.radioPort)
      }
    case Chunk(bytes) =>
      withCleanup {
        output.write(bytes)
      }
  }

  def withCleanup(f: => Unit) {
    try {
      f
    } catch {
      case e: IOException =>
        if (!dead) {
          log.info("Shutting down listener " + socket.getRemoteSocketAddress + ": " + e.toString)
          dead = true
          station ! Unsubscribe(self)
          self ! PoisonPill
          socket.close()
        }
    }
  }
}

class RadioStation(files: Iterable[File]) extends Actor {

  import ImplicitHelpers._

  val subscribers = collection.mutable.Set[ActorRef]()
  val responder = new IcyResponder(new ChunkIterator(Server.chunkSize, files))

  def receive = {
    case Subscribe(actor) =>
      subscribers += actor
    case Unsubscribe(actor) =>
      subscribers -= actor
    case NextChunk =>
      val chunk = new ByteArrayOutputStream
      val sleep = responder.writeNextChunk(chunk)
      val bytes = chunk.toByteArray
      subscribers.foreach((a: ActorRef) => a ! Chunk(bytes))
      Server.executor.schedule(() => self ! NextChunk, sleep, TimeUnit.MILLISECONDS)
  }
}


text:
subject: What stands between youth and decent jobs?
description: More youth seem to prefer staying in school to getting a job early in life. That's good news. Yet more than 200 million young people are either unemployed or have a job but live in poverty.

---
<container>

	<row class="hero collapse">
		<columns class="no-padding" small="12" large="12">

		</columns>
	</row>

	<row class="email-body">

		<columns class="buffer show-for-large" large="1" small="0"></columns>

		<columns class="main" small="12" large="10" valign="top">
			<spacer size="20"></spacer>
			<row>
				<columns>

					<spacer size="20"></spacer>
				</columns>
			</row>

			<row>
				<columns>

What stands between youth and decent jobs?

					<spacer size="20"></spacer>
				</columns>
			</row>

			<spacer size="5"></spacer>

			<row>
				<columns class="no-padding">

						More youth seem to prefer staying in school to getting a job early in life. That's good news. Yet more than 200 million young people are either unemployed or have a job but live in poverty.

					<spacer size="10"></spacer>

						Check out the latest InfoStory to learn more about global employment trends for young people and what stands between them and a decent job.

					<spacer size="20"></spacer>

						<button class="rounded" href="http://www.ilo.org/infostories/Stories/Youth-Employment/Youth-still-struggle-to-get-good-jobs"> Explore InfoStory</button>

				</columns>
			</row>
			<spacer size="20"></spacer>
			<row>
				<columns class="no-padding">

				</columns>
			</row>
			<spacer size="40"></spacer>
				{{> footer}}
		</columns>

		<columns class="buffer show-for-large" large="1"></columns>
	</row>

	<row>
		<columns class="bottom-margin show-for-large" small="0" large="12"></columns>
	</row>

</container>


text:
package de.crunc.jackson.datatype.vertx;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import io.vertx.core.json.JsonObject;

import java.io.IOException;

import static de.crunc.jackson.datatype.vertx.JsonObjectBuilder.object;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

/**
 * Unit test for {@link JsonObjectDeserializer}
 *
 * @author Hauke Jaeger, hauke.jaeger@googlemail.com
 */
public class JsonObjectDeserializerTest {

    private ObjectMapper om;

    @Before
    public void setUp() {
        om = new ObjectMapper();
        om.registerModule(new VertxJsonModule());
    }

    @Test
    public void testDeserializeEmptyObject() throws IOException {
        JsonObject expected = object().build();

        String json = expected.encode();

        JsonObject object = om.readValue(json, JsonObject.class);

        assertThat(object, equalTo(expected));
    }

    @Test
    public void testDeserializeObject() throws IOException {
        JsonObject expected = object()
                .put("anObject", object()
                        .put("foo", "bar")
                        .put("anInt", 7)
                        .put("aFloat", 4.669))
                .putNull("nullValue")
                .put("anArray", JsonArrayBuilder.array()
                        .add("Hello")
                        .add("World :)")
                        .add(19)
                        .add(false)
                        .addNull())
                .put("aBool", true)
                .put("anotherBool", false)
                .put("anInt", 42)
                .put("aFloat", 3.141)
                .build();

        String json = expected.encode();

        JsonObject object = om.readValue(json, JsonObject.class);

        assertThat(object, equalTo(expected));
        assertThat(object.size(), equalTo(7));
    }
}


text:
function output = sensor(blankObj,time,state,input,flowTime,jumpCount)
% The "sensor" method will produce output values given the current
% time and state of the system.
%
% SYNTAX:
%   output = blankObj.sensor()
%   ...
%   output = blankObj.sensor(time,state,input,flowTime,jumpCount)
%
% INPUTS:
%   blankObj - (1 x 1 simulate.blank)
%       An instance of the "simulate.blank" class.
%
%   time - (1 x 1 real number) [blankObj.time]
%       Current time.
%
%   state - (1 x 1 number) [blankObj.state]
%       Current state.
%
%   input - (1 x 1 number) [blankObj.input]
%       Current input value.
%
%   flowTime - (1 x 1 semi-positive real number) [blankObj.flowTime]
%       Current flow time value.
%
%   jumpCount - (1 x 1 semi-positive integer) [blankObj.jumpCount]
%       Current jump count value.
%
% OUTPUTS:
%   output - (1 x 1 number)
%       Output values for the plant.
%
% NOTES:
%
% NECESSARY FILES AND/OR PACKAGES:
%   +simulate, +simulate
%
% AUTHOR:
%    Rowland O'Flaherty (rowlandoflaherty.com)
%
% VERSION:
%   Created 29-OCT-2013
%-------------------------------------------------------------------------------

%% Apply default values
if nargin < 2, time = blankObj.time; end
if nargin < 3, state = blankObj.state; end
if nargin < 4, input = blankObj.input; end
if nargin < 5, flowTime = blankObj.flowTime; end
if nargin < 6, jumpCount = blankObj.jumpCount; end

%% Parameters

%% Variables

%% Sensor Definition

%% Set output
output = zeros(blankObj.nOutputs,1);

end


text:
namespace ui {
class Accelerator;
}

class BrowserView;

// A customized dialog view for the keyboard overlay.
class KeyboardOverlayDialogView : public HtmlDialogView {
 public:
  KeyboardOverlayDialogView(Profile* profile,
                            HtmlDialogUIDelegate* delegate,
                            BrowserView* parent_view);
  virtual ~KeyboardOverlayDialogView();

  // Overridden from views::View:
  virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) OVERRIDE;

  // Shows the keyboard overlay.
  static void ShowDialog(gfx::NativeWindow owning_window, BrowserView* parent);

 private:
  virtual void RegisterDialogAccelerators() OVERRIDE;

  // Returns true if |accelerator| is an accelerator for closing the dialog.
  bool IsCloseAccelerator(const ui::Accelerator& accelerator);

  // Points to the view from which this dialog is created.
  BrowserView* parent_view_;

  // Contains accelerators for closing this dialog.
  std::set<ui::Accelerator> close_accelerators_;

  DISALLOW_COPY_AND_ASSIGN(KeyboardOverlayDialogView);
};

#endif  // CHROME_BROWSER_UI_VIEWS_KEYBOARD_OVERLAY_DIALOG_VIEW_H_


text:
<?php

namespace litepubl\core;

use litepubl\Config;

class StorageJson extends Storage
{

    public function getExt(): string
    {
        return '.json';
    }

    public function serialize(array $data): string
    {
        return \json_encode($data, JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE | (Config::$debug ? JSON_PRETTY_PRINT : 0));
    }

    public function unserialize(string $str)
    {
        return \json_decode($s, true);
    }

    public function before(string $str): string
    {
        return $str;
    }

    public function after(string $str): string
    {
        return $str;
    }
}


text:
class Hdf5 < Formula
  desc "File format designed to store large amounts of data"
  homepage "http://www.hdfgroup.org/HDF5"
  url "https://www.hdfgroup.org/ftp/HDF5/releases/hdf5-1.10/hdf5-1.10.0-patch1/src/hdf5-1.10.0-patch1.tar.bz2"
  version "1.10.0-patch1"
  sha256 "f772264dd853dceb18855418a81c63c9cdcca7bcd075b9c54eb516af006fdfba"

  bottle do
    sha256 "163b5ff7743239a061377686f6e0849daa72b25bafd71743ec51b6b4ef235a05" => :sierra
    sha256 "a7b1fb7401c57cef52ca62579854c9145a6931b052f5947cfa1a9966e72ad940" => :el_capitan
    sha256 "8fc3fdc3dcf31ed75089844e827c0c24d799b4afb9e30e777dcdfea8b3781c27" => :yosemite
    sha256 "a940eae31660c8ad10fd7c64dc4bf6ce654490bcf8622fa9edf361fa7a3c69ef" => :x86_64_linux
  end

  deprecated_option "enable-fortran" => "with-fortran"
  deprecated_option "enable-threadsafe" => "with-threadsafe"
  deprecated_option "enable-parallel" => "with-mpi"
  deprecated_option "enable-fortran2003" => "with-fortran2003"
  deprecated_option "enable-cxx" => "with-cxx"
  deprecated_option "with-check" => "with-test"

  option "with-test", "Run build-time tests"
  option "with-threadsafe", "Trade performance for C API thread-safety (requires --without-cxx and --without-hl)"
  option "with-fortran2003", "Compile Fortran 2003 bindings (requires --with-fortran)"
  option "with-mpi", "Compile with parallel support (unsupported with thread-safety)"
  option "without-cxx", "Disable the C++ interface"
  option "without-hl", "Compile without high-level library"
  option "with-unsupported", "Allow unsupported combinations of configure options"
  option :cxx11

  depends_on :fortran => :optional
  depends_on "szip"
  depends_on :mpi => [:optional, :cc, :cxx, :f90]
  depends_on "zlib" unless OS.mac?

  depends_on "autoconf" => :build
  depends_on "automake" => :build
  depends_on "libtool" => :build

  def install
    inreplace %w[c++/src/h5c++.in fortran/src/h5fc.in tools/misc/h5cc.in],
      "${libdir}/libhdf5.settings", "#{pkgshare}/libhdf5.settings"

    inreplace "src/Makefile.am", "settingsdir=$(libdir)",
                                 "settingsdir=#{pkgshare}"

    system "autoreconf", "-fiv"

    args = %W[
      --prefix=#{prefix}
      --enable-build-mode=production
      --disable-dependency-tracking
      --with-zlib=#{OS.mac? ? "/usr" : Formula["zlib"].opt_prefix}
      --with-szlib=#{Formula["szip"].opt_prefix}
      --enable-static=yes
      --enable-shared=yes
    ]
    args << "--enable-unsupported" if build.with? "unsupported"
    args << "--enable-threadsafe" << "--with-pthread=/usr" if build.with? "threadsafe"
    args << "--disable-hl" if build.without? "hl"

    if build.with?("cxx") && build.without?("mpi")
      args << "--enable-cxx"
    else
      args << "--disable-cxx"
    end

    if build.with? "fortran"
      args << "--enable-fortran"
      args << "--enable-fortran2003" if build.with? "fortran2003"
    else
      args << "--disable-fortran"
    end

    if build.with? "mpi"
      args << "--enable-parallel"
      ENV["CC"] = ENV["MPICC"]
      ENV["CXX"] = ENV["MPICXX"]
      ENV["FC"] = ENV["MPIFC"]
    end

    system "./configure", *args
    system "make"
    system "make", "check" if build.with?("test") || build.bottle?
    system "make", "install"
  end

  test do
    (testpath/"test.c").write <<-EOS.undent
      #include <stdio.h>
      #include "hdf5.h"
      int main()
      {
        printf(\"%d.%d.%d\\n\",H5_VERS_MAJOR,H5_VERS_MINOR,H5_VERS_RELEASE);
        return 0;
      }
    EOS
    system "#{bin}/h5cc", "test.c"
    assert_equal "1.10.0", shell_output("./a.out").chomp
  end
end


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

namespace EPI.Sorting
{
    /// <summary>
    /// Design an algorithm that takes as input a set of intervals and outputs their union expressed as a set of disjoint intervals.
    /// </summary>
    /// <example>
    /// {} => open interval, [] => closed interval
    /// {0,3},[1,1],[3,4},[2,4],[5,7},[7,8},[8,11},{9,11], [12,14],{12,16],{13,15},{16,17} returns
    /// {0,4],[5,11],[12,17}
    /// </example>
    public static class UnionOfIntervals
	{
		public struct Entry
		{
			public int value;
			public bool isOpenInterval;
		}

		public struct Interval
		{
			public Entry left;
			public Entry right;
		}

		private class EntryType : IComparable
		{
			public Entry entry;
			public bool isRightInterval;

			public int CompareTo(object obj)
			{
				EntryType entryType = obj as EntryType;
				if (entryType != null)
				{
					return (entry.value != entryType.entry.value) ?
						entry.value.CompareTo(entryType.entry.value) : // first sort entry's with lowest value
						(isRightInterval != entryType.isRightInterval) ?
							isRightInterval.CompareTo(entryType.isRightInterval) :  // then sort by entry type which are left
							(isRightInterval) ? (!entry.isOpenInterval).CompareTo(!entryType.entry.isOpenInterval)  : entry.isOpenInterval.CompareTo(entryType.entry.isOpenInterval); //then sort by closed interval entry
				}
				throw new InvalidOperationException();
			}
		}

		public static List<Interval> FindUnionOfIntervals(List<Interval> intervals)
		{
			List<Interval> result = new List<Interval>();
			EntryType[] entries = new EntryType[intervals.Count * 2];
			for (int i = 0; i < intervals.Count; i++)
			{
				entries[2 * i] = new EntryType() { entry = intervals[i].left, isRightInterval = false };
				entries[2*i + 1] = new EntryType() { entry = intervals[i].right, isRightInterval = true };
			}

			QuickSort<EntryType>.Sort(entries);
			Stack<EntryType> stackedEntries = new Stack<EntryType>();
			foreach (EntryType entryType in entries)
			{
				if (!entryType.isRightInterval)
				{
					stackedEntries.Push(entryType);
				}
				else
				{
					EntryType oldestEntryInSet = stackedEntries.Pop();
					if (stackedEntries.Count == 0) // set is complete
					{
						result.Add(new Interval()
						{
							left = oldestEntryInSet.entry,
							right = entryType.entry
						});
					}
				}
			}
			return result;
		}
	}
}


text:
@implementation PKSRecognitionException

- (void)dealloc {
    self.currentReason = nil;
    [super dealloc];
}

- (NSString *)reason {
    return self.currentReason;
}

@end


text:
<?php

namespace Oro\Bundle\ApiBundle\Util;

use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

use Oro\Bundle\ApiBundle\DependencyInjection\Configuration;

class DependencyInjectionUtil
{
    /**
     * @param ContainerBuilder $container
     * @param string           $serviceId
     *
     * @return Definition|null
     */
    public static function findDefinition(ContainerBuilder $container, $serviceId)
    {
        return $container->hasDefinition($serviceId) || $container->hasAlias($serviceId)
            ? $container->findDefinition($serviceId)
            : null;
    }

    /**
     * @param ContainerBuilder $container
     *
     * @return array
     */
    public static function getConfig(ContainerBuilder $container)
    {
        $processor = new Processor();

        return $processor->processConfiguration(
            new Configuration(),
            $container->getExtensionConfig('oro_api')
        );
    }

    /**
     * @param ContainerBuilder $container
     * @param string           $chainServiceId
     * @param string           $tagName
     * @param string           $addMethodName
     */
    public static function registerTaggedServices(
        ContainerBuilder $container,
        $chainServiceId,
        $tagName,
        $addMethodName
    ) {
        $chainServiceDef = self::findDefinition($container, $chainServiceId);
        if (null !== $chainServiceDef) {
            // find services
            $services = [];
            $taggedServices = $container->findTaggedServiceIds($tagName);
            foreach ($taggedServices as $id => $attributes) {
                $priority = isset($attributes[0]['priority']) ? $attributes[0]['priority'] : 0;
                $services[$priority][] = new Reference($id);
            }
            if (empty($services)) {
                return;
            }

            // sort by priority and flatten
            krsort($services);
            $services = call_user_func_array('array_merge', $services);

            // register
            foreach ($services as $service) {
                $chainServiceDef->addMethodCall($addMethodName, [$service]);
            }
        }
    }

    /**
     * Replaces a regular service with the debug one
     *
     * @param ContainerBuilder $container
     * @param string           $serviceId
     * @param string           $debugServiceClassName
     */
    public static function registerDebugService(
        ContainerBuilder $container,
        $serviceId,
        $debugServiceClassName = 'Oro\Component\ChainProcessor\Debug\TraceableActionProcessor'
    ) {
        $definition = $container->findDefinition($serviceId);
        $definition->setPublic(false);
        $container->setDefinition($serviceId . '.debug.parent', $definition);
        $debugDefinition = new Definition(
            $debugServiceClassName,
            [
                new Reference($serviceId . '.debug.parent'),
                new Reference('oro_api.profiler.logger')
            ]
        );
        $debugDefinition->setPublic(false);
        $container->setDefinition($serviceId . '.debug', $debugDefinition);
        $container->setAlias($serviceId, $serviceId . '.debug');
    }
}


text:
Playing with gaussian kernels for more authentic resampling for [snes-apu](https://github.com/emu-rs/snes-apu).

Probably not useful for much else, but made for a fun few hours :)


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_enabled="false"
        android:color="@color/common_google_signin_btn_text_light_disabled" />
    <item
        android:state_pressed="true"
        android:color="@color/common_google_signin_btn_text_light_pressed" />
    <item
        android:state_focused="true"
        android:color="@color/common_google_signin_btn_text_light_focused" />
    <item
        android:color="@color/common_google_signin_btn_text_light_default" />
</selector>
<!-- From: file:/Users/DPSingh/Desktop/thehelpiez/Parse-Starter-Project-1.11.0/ParseStarterProject/build/intermediates/exploded-aar/com.google.android.gms/play-services-base/8.3.0/res/color/common_google_signin_btn_text_light.xml -->


text:
// This file is automatically generated.

package adila.db;

/*
 * Archos TV Connect
 *
 * DEVICE: LUDO
 * MODEL: ARCHOS LUDOG10
 */
final class ludo_archos20ludog10 {
    public static final String DATA = "Archos|TV Connect|";
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
  <meta name=viewport content="width=device-width, initial-scale=0.3333334">
  <meta name="google-site-verification" content="_bMOCDpkx9ZAzBwb2kF3PRHbfUUdFj2uO8Jd1AXArz4"/>
  <title>ImageMagick: Magick++, C++ API for ImageMagick: Classes</title>
  <meta http-equiv="content-language" content="en-US"/>
  <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  <meta http-equiv="reply-to" content="magick-users@imagemagick.org"/>
  <meta name="application-name" content="ImageMagick"/>
  <meta name="description" content="A collection of tools and libraries to read, write, and manipulate an image in any of the more popular image formats."/>
  <meta name="application-url" content="http://www.imagemagick.org"/>
  <meta name="generator" content="PHP"/>
  <meta name="keywords" content="magick++, c++, api, for, imagemagick:, classes, convert, edit, compose, image, pixel"/>
  <meta name="rating" content="GENERAL"/>
  <meta name="robots" content="INDEX, FOLLOW"/>
  <meta name="generator" content="ImageMagick Studio LLC"/>
  <meta name="author" content="ImageMagick Studio LLC"/>
  <meta name="revisit-after" content="2 DAYS"/>
  <meta name="resource-type" content="document"/>
  <meta name="copyright" content="Copyright (c) 1999-2012 ImageMagick Studio LLC"/>
  <meta name="distribution" content="Global"/>
  <meta name="magick-serial" content="P131-S030410-R485315270133-P82224-A6668-G1245-1"/>
  <link rel="icon" href="../../images/wand.png"/>
  <link rel="shortcut icon" href="../../images/wand.ico" type="images/x-icon"/>
  <link rel="canonical" href="../../index.html" />
  <link rel="meta" type="application/rdf+xml" title="ICI" href="http://imagemagick.org/ici.rdf"/>

  <link rel="stylesheet" href="http://www.imagemagick.org/fancybox/source/jquery.fancybox.css?v=2.1.5" type="text/css" media="screen" />

  <link rel="stylesheet" href="http://www.imagemagick.org/fancybox/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" type="text/css" media="screen" />

  <link rel="stylesheet" href="http://www.imagemagick.org/fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" type="text/css" media="screen" />

  About ImageMagick

  Binary Releases

    Unix

    Mac OS X

    iOS

    Windows

  Command-line Tools

    Processing

    Options

    Usage

  Program Interfaces

    MagickWand

    MagickCore

    PerlMagick

    Magick++

   Install from Source

    Unix

    Windows

  Resources

  Architecture

  Download

  Search

  Site Map

  Links

  Support ImageMagick Development

Magick++ Classes

Magick++ provides a simple C++ API to the ImageMagick image processing library which supports reading and writing a huge number of image formats as well as supporting a broad spectrum of traditional image processing operations. The ImageMagick C API is complex and the data structures are currently not documented. Magick++ provides access to most of the features available from the C API but in a simple object-oriented and well-documented framework.

Magick++ is intended to support commercial-grade application development. In order to avoid possible conflicts with the user's application, all symbols contained in Magick++ (included by the header <tt><Magick++.h></tt>) are scoped to the namespace Magick. Symbols from the ImageMagick C library are imported under the MagickCore namespace to avoid possible conflicts and ImageMagick macros are only included within the Magick++ implementation so they won't impact the user's application.

The core class in Magick++ is the Image class. The Image class provides methods to manipulate a single image frame (e.g. a JPEG image). Standard Template Library (STL)compatible algorithms and function objects are provided in order to manipulate multiple image frames or to read and write file formats which support multiple image frames (e.g. GIF animations, MPEG animations, and Postscript files).

The Image class supports reference-counted memory management which supports the semantics of an intrinsic variable type (e.g. 'int') with an extremely efficient <tt>operator =</tt> and copy constructor (only a pointer is assigned) while ensuring that the image data is replicated as required so that it the image may be modified without impacting earlier generations. Since the Image class manages heap memory internally, images are best allocated via C++ automatic (stack-based) memory allocation. This support allows most programs using Magick++ to be written without using any pointers, simplifying the implementation and avoiding the risks of using pointers. When a program uses automatic memory allocation to allocate Magick++ images, that aspect of the program becomes naturally exception-safe and thread-safe.

The image class uses a number of supportive classes in order to specify arguments. Colors are specified via the Color class. Colors specified in X11-style string form are implicitly converted to the Color class. Geometry arguments (those specifying width, height, and/or x and y offset) are specified via the Geometry class. Similar to the Color class, geometries specified as an X11-style string are implicitly converted to the Geometry class. Two dimensional drawable objects are specified via the Drawable class. Drawable objects may be provided as a single object or as a list of objects to be rendered using the current image options. Montage options (a montage is a rendered grid of thumbnails in one image) are specified via the Montage class.

Errors are reported using C++ exceptions derived from the Exception class, which is itself derived from the standard C++ exception class. Exceptions are reported synchronous with the operation and are caught by the first matching try block as the stack is unraveled. This allows a clean coding style in which multiple related Magick++ commands may be executed with errors handled as a unit rather than line-by-line. Since the Image object provides reference-counted memory management, unreferenced images on the stack are automagically cleaned up, avoiding the potential for memory leaks.

For ease of access, the documentation for the available user-level classes is available via the following table.

Magick++ User-Level Classes

<colgroup>
<col width="18%" />
<col width="82%" />
</colgroup>

Blob
Binary Large OBject container.

CoderInfo
Report information about supported image formats (use with
coderInfoList())

Color
Color specification.

Drawable
Drawable shape (for input to 'draw').

Exception
C++ exception objects.

Geometry
Geometry specification.

Image
Image frame.  This is the primary object in Magick++.

Montage
Montage options for montageImages().

Pixels
Low-level access to image pixels.

STL
STL algorithms and function objects for operating on
containers of image frames.

TypeMetric
Container for font type metrics (use with
Image::fontTypeMetrics).

      Discourse Server •
      Public Key •
      Studio •
      JqMagick

  ©  1999-2014 ImageMagick Studio LLC
   Contact the Wizards


text:
import { assert } from 'chai';
import Metrics from '../../src/metrics/metrics.js';
import MockLogger from '../lib/mock_logger';
import ConfigServer from '../lib/config_server';
import LocalMetricFactory from '../lib/metrics/local/metric_factory.js';
import LocalBackend from '../lib/metrics/local/backend.js';
import RemoteThrottler from '../../src/throttler/remote_throttler';
import sinon from 'sinon';

describe('RemoteThrottler should', () => {
  let server: ConfigServer;
  let logger: MockLogger;
  let metrics: Metrics;
  let throttler: RemoteThrottler;
  let serviceName = 'service';
  let operation = 'op';
  let other_operation = 'oop';
  let uuid = 'uuid';
  let creditsUpdatedHook;

  before(() => {
    server = new ConfigServer().start();
  });

  after(() => {
    server.close();
  });

  beforeEach(() => {
    server.clearConfigs();
    logger = new MockLogger();
    metrics = new Metrics(new LocalMetricFactory());
    creditsUpdatedHook = sinon.spy();
    throttler = new RemoteThrottler(serviceName, {
      refreshIntervalMs: 0,
      initialDelayMs: 60000,
      metrics: metrics,
      logger: logger,
      onCreditsUpdate: (...args) => creditsUpdatedHook(...args),
    });
  });

  afterEach(() => {
    throttler.close();
  });

  it('return false for isAllowed on initial call and return true once credits are initialized', done => {
    throttler.setProcess({ uuid: uuid });
    server.addCredits(serviceName, [{ operation: operation, balance: 3 }]);
    creditsUpdatedHook = _throttler => {
      assert.isTrue(_throttler.isAllowed(operation));
      assert.equal(_throttler._credits[operation], 2);
      assert.equal(LocalBackend.counterValue(metrics.throttlerUpdateSuccess), 1);
      assert.equal(LocalBackend.counterValue(metrics.throttledDebugSpans), 1);
      done();
    };
    assert.isFalse(throttler.isAllowed(operation));
    throttler._refreshCredits();
  });

  it('log an error if _refreshCredits is called prior to UUID being set', () => {
    throttler._fetchCredits = sinon.spy();
    throttler._refreshCredits();
    assert.equal(logger._errorMsgs.length, 1);
    sinon.assert.notCalled(throttler._fetchCredits);
  });

  it('not fetch credits if uuid is invalid', () => {
    throttler._fetchCredits = sinon.spy();
    throttler.setProcess({ uuid: null });
    throttler._refreshCredits();
    assert.equal(logger._errorMsgs.length, 1, `errors=${logger._errorMsgs}`);
    sinon.assert.notCalled(throttler._fetchCredits);
  });

  it("return false for _isAllowed if operation isn't in _credits or operation has no credits", () => {
    assert.isFalse(
      throttler._isAllowed(operation),
      'operation is not set so operation should not be allowed'
    );
    throttler._credits[operation] = 0;
    assert.isFalse(throttler._isAllowed(operation), 'operation is set but lacks credit');
    assert.equal(LocalBackend.counterValue(metrics.throttledDebugSpans), 2);
  });

  it("return false for isAllowed if operation doesn't have enough credits", () => {
    throttler._credits[operation] = 0.5;
    assert.isFalse(throttler._isAllowed(operation));
    assert.equal(LocalBackend.counterValue(metrics.throttledDebugSpans), 1);
  });

  it('succeed when we retrieve credits for multiple operations', done => {
    throttler.setProcess({ uuid: uuid });
    server.addCredits(serviceName, [
      { operation: operation, balance: 5 },
      { operation: other_operation, balance: 3 },
    ]);
    throttler._credits[operation] = 0;
    throttler._credits[other_operation] = 0;
    creditsUpdatedHook = _throttler => {
      assert.isTrue(_throttler.isAllowed(operation));
      assert.equal(_throttler._credits[operation], 4);
      assert.isTrue(_throttler.isAllowed(other_operation));
      assert.equal(_throttler._credits[other_operation], 2);
      assert.equal(LocalBackend.counterValue(metrics.throttlerUpdateSuccess), 1);
      done();
    };
    throttler._refreshCredits();
  });

  it('emit failure metric on failing to query for credits', done => {
    throttler.setProcess({ uuid: uuid });
    throttler._credits[operation] = 0;
    metrics.throttlerUpdateFailure.increment = function() {
      assert.equal(logger._errorMsgs.length, 1, `errors=${logger._errorMsgs}`);
      done();
    };
    throttler._host = 'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch';
    throttler._refreshCredits();
  });

  it('emit failure metric on failing to parse bad http json response', done => {
    throttler.setProcess({ uuid: uuid });
    throttler._credits[operation] = 0;
    metrics.throttlerUpdateFailure.increment = function() {
      assert.equal(logger._errorMsgs.length, 1, `errors=${logger._errorMsgs}`);
      done();
    };
    server.addCredits(serviceName, 'not-json');
    throttler._refreshCredits();
  });

  it('emit failure metric when server returns an invalid response', done => {
    throttler.setProcess({ uuid: uuid });
    throttler._credits[operation] = 0;
    metrics.throttlerUpdateFailure.increment = function() {
      assert.equal(logger._errorMsgs.length, 1, `errors=${logger._errorMsgs}`);
      done();
    };
    throttler._refreshCredits();
  });

  it('not fetch credits if no operations have been seen', () => {
    throttler = new RemoteThrottler(serviceName);
    throttler._fetchCredits = sinon.spy();
    throttler.setProcess({ uuid: uuid });
    throttler._refreshCredits();
    sinon.assert.notCalled(throttler._fetchCredits);
    throttler.close();
  });

  it('refresh credits after _afterInitialDelay is called', done => {
    throttler.setProcess({ uuid: uuid });
    throttler._credits[operation] = 0;
    server.addCredits(serviceName, [{ operation: operation, balance: 5 }]);
    creditsUpdatedHook = _throttler => {
      assert.isTrue(_throttler.isAllowed(operation));
      assert.equal(_throttler._credits[operation], 4);
      assert.equal(LocalBackend.counterValue(metrics.throttlerUpdateSuccess), 1);
      done();
    };
    throttler._afterInitialDelay();
  });
});


text:
using EasyNetQ.Host.Core;
using EasyNetQ.Host.TestSaga.ServiceContract;

namespace EasyNetQ.Host.TestSaga.Subscribers
{
    public class TestMultipleInstancesSubscriber : ISubscriber
    {
        private readonly IBusContainer _busContainer;

        public TestMultipleInstancesSubscriber(IBusContainer busContainer)
        {
            _busContainer = busContainer;
        }

        public void Subscribe()
        {
            _busContainer["Broker_A"].Subscribe<TestMultipleInstancesMessage>("TestMultipleInstances", message =>
            {
                _busContainer["Broker_B"].Request<GetSomethingRequest, GetSomethingResponse>(new GetSomethingRequest());
                _busContainer["Broker_C"].Request<GetSomethingRequest, GetSomethingResponse>(new GetSomethingRequest());
            });
        }
    }
}


text:
package demo;

import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.Test;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.integration.json.JsonPropertyAccessor;

import java.text.ParseException;

public class DateTimeTests {

    @Test
    public void testDateTime() throws ParseException {
        DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");

        System.out.print(new SpelExpressionParser().parseRaw("new org.joda.time.DateTime(new java.lang.Long('1487145898898')).toLocalDateTime().toString()").getValue());
        dateFormatter.parseDateTime(new DateTime(new Long("1487145898898")).toLocalDateTime().toString());

        JsonPropertyAccessor.ToStringFriendlyJsonNode jsonNode = new JsonPropertyAccessor.ToStringFriendlyJsonNode(JsonNodeFactory.instance.textNode("test"));

        new SpelExpressionParser().parseExpression("toString()").getValue(jsonNode, CharSequence.class);
    }
}


text:
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.specmath.library.UnionConflictException;
import org.specmath.library.UnionOptions;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;

@Command(
    name = "union",
    description = "Perform the union operation",
    version = "1.0",
    mixinStandardHelpOptions = true)
class UnionCommand implements Callable<Integer> {
  @Option(
      names = {"-o", "--output"},
      required = true,
      description = "name of the output file")
  String outputFilename;

  @Option(
      names = {"-d", "--defaults"},
      required = false,
      description = "path to defaults file")
  Path defaultsPath;

  @Option(
      names = {"-c", "--conflictResolutions"},
      required = false,
      description = "path to conflict resolutions file")
  Path conflictResolutionsPath;

  @Parameters(
      arity = "2..*",
      paramLabel = "FILEPATH",
      description = "two or more paths to specs to merge")
  private List<Path> filePathsOfSpecsToMerge;

  SpecMathService specMath = new SpecMathService();

  public static void main(String[] args) {
    int exitCode = new CommandLine(new UnionCommand()).execute(args);
    System.exit(exitCode);
  }

  @Override
  public Integer call() throws Exception {
    List<String> specStrings = new ArrayList<>();
    for (Path path : filePathsOfSpecsToMerge) {
      specStrings.add(Files.readString(path));
    }

    String defaults = "";
    String conflictResolutions = "";

    if (defaultsPath != null) {
      defaults = Files.readString(defaultsPath);
    }
    if (conflictResolutionsPath != null) {
      conflictResolutions = Files.readString(conflictResolutionsPath);
    }

    UnionOptions unionOptions =
        UnionOptions.builder().defaults(defaults).conflictResolutions(conflictResolutions).build();

    try {
      String result = specMath.union(specStrings, unionOptions);
      writeResultToDisk(result);

      System.out.printf(
          "The union operation succeeded. Result file written to %s.\n", outputFilename);
    } catch (UnionConflictException e) {
      handleUnionConflictException(e);
    }

    return 0;
  }

  void writeResultToDisk(String result) throws IOException {
    Files.writeString(Paths.get(outputFilename), result);
  }

  private void handleUnionConflictException(UnionConflictException e) throws IOException {
    System.out.println("There were conflicts in the union process\n");

    String conflictsFilename = writeConflictFileToDisk(e);

    System.out.println("Please see the file " + conflictsFilename + " for more information\n");

    System.out.println("To resolve the conflicts you have three choices:");
    System.out.printf(
        "1: Updating the \"resolvedValue\" property in %s"
            + " with your desired option, and then passing that file into the union as an"
            + " additional parameter using the -c flag\n\n",
        conflictsFilename);
    System.out.printf(
        "2: Looking at %s and manually updating the input YAML files\n\n",
        conflictsFilename);
    System.out.printf(
        "3: Updating/creating a defaults file with "
            + "overrides for the conflicting keypaths in %s, and passing in the new defaults file"
            + " into the union as an additional parameter using the -d flag\n\n",
        conflictsFilename);
  }

  String writeConflictFileToDisk(UnionConflictException e) throws IOException {
    String conflictsFilename = outputFilename + "_CONFLICTS";

    ObjectMapper mapper = new ObjectMapper();

    mapper
        .writerWithDefaultPrettyPrinter()
        .writeValue(new File(conflictsFilename), e.getConflicts());

    return conflictsFilename;
  }
}


text:
package derpatiel.progressivediff;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import derpatiel.progressivediff.util.LOG;
import derpatiel.progressivediff.util.MobNBTHandler;
import net.minecraft.advancements.Advancement;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.fml.common.registry.EntityEntry;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import org.apache.commons.lang3.exception.ExceptionUtils;

import javax.annotation.Nullable;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by Jim on 5/7/2017.
 */
public class ServerCommand extends CommandBase {

    private String[] usage = new String[]{
            "progdiff (Progressive Difficulty) help:",
            "\"progdiff sync\" sync the config for the server",
            "    Useful for testing difficulty configs.",
            "\"progdiff killmodified\" kill modified mobs in the ",
            "    same dimension as the player",
            "\"progdiff killmobs\" kill all mobs in the ",
            "    same dimension as the player",
            "\"progdiff advancements\" print a list of all loaded",
            "    advancements to the configuration directory as",
            "    progdiff_advancements.txt",
            "    (filters out advancements under minecraft:recipes/*)",
            "\"progdiff region\" print the region the player is currently in",
            "\"progdiff simulate [mobId]\" simulates the spawn of the given",
            "    mob at the player's location and returns the difficulty",
            "\"progdiff simulateDetailed [mobId]\" as with simulate, but",
            "    prints much more detailed results"
    };

    @Override
    public String getName() {
        return "progdiff";
    }

    @Override
    public String getUsage(ICommandSender sender) {
        return "\"progdiff [sync|killmodified|killmobs|advancements|region|simulate|simulateDetailed]\"";
    }

    @Override
    public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException {
        if (args.length == 0 || args.length > 2) {
            sendChat(sender, usage);
        } else if (args[0].equalsIgnoreCase("sync")) {
            DifficultyManager.syncConfig();
            sendChat(sender, new String[]{"Synced config."});
        }else if(args[0].equalsIgnoreCase("simulate") || args[0].equalsIgnoreCase("simulateDetailed")){
            boolean detailed = args[0].equalsIgnoreCase("simulateDetailed");
            if(args.length<2){
                sendChat(sender, new String[]{"No mob provided.  Call this command with a mob to simulate. (try tab completion!)"});
                return;
            }
            if(args.length>2){
                sendChat(sender, new String[]{"Too many arguments to simulate/simulateDetailed."});
                return;
            }
            String mobType = args[1];
            Region senderRegion = DifficultyManager.getRegionForPosition(sender.getEntityWorld().provider.getDimension(),sender.getPosition());
            List<EntityEntry> matchingMob = ForgeRegistries.ENTITIES.getValues().stream()
                    .filter(entry->entry.getName().equalsIgnoreCase(mobType))
                    .collect(Collectors.toList());
            if(matchingMob.size()!=1){
                sendChat(sender, new String[]{"No matching mob found for "+mobType+".  Try using tab completion to find a mob to simulate."});
                return;
            }
            Entity fakeSpawned = matchingMob.get(0).newInstance(sender.getEntityWorld());
            fakeSpawned.setPosition(sender.getPosition().getX(),sender.getPosition().getY(),sender.getPosition().getZ());
            SpawnEventDetails fakeDetails = new SpawnEventDetails();
            fakeDetails.fromSpawner=false;
            fakeDetails.entity = (EntityLiving) fakeSpawned;
            Map<String, Integer> difficultyDetails = Maps.newHashMap();
            try {
                difficultyDetails.putAll(senderRegion.determineDifficultyForFakedSpawnEvent(fakeDetails));
            }catch(Exception e){
                sendChat(sender, new String[]{
                        "There was a problem simulating difficulty.",
                        "Please check the server log for details.",
                        });
                LOG.error(e.getMessage());
                LOG.error(ExceptionUtils.getStackTrace(e));
                return;
            }
            int totalDifficulty = 0;
            for(String key : difficultyDetails.keySet()){
                int thisControlDif = difficultyDetails.get(key);
                totalDifficulty+=thisControlDif;
                if(detailed){
                    sendChat(sender, new String[]{key+": "+thisControlDif+" points."});
                }
            }
            sendChat(sender, new String[]{totalDifficulty+" difficulty points"});
        }else if(args[0].equalsIgnoreCase("killmodified")){
            sendChat(sender, new String[]{"Killing all modified mobs in this dimension."});
            MobNBTHandler.getModifiedEntities(sender.getEntityWorld()).stream().forEach(mob->mob.setDead());
        }else if(args[0].equalsIgnoreCase("killmobs")) {
            sendChat(sender, new String[]{"Killing all non-blacklisted in this dimension."});
            sender.getEntityWorld().getEntities(EntityLiving.class, (entity) -> !entity.isDead && DifficultyManager.shouldModifyEntity(entity)).stream().forEach(mob -> mob.setDead());
        }else if(args[0].equalsIgnoreCase("region")) {
            Region currentRegion = DifficultyManager.getRegionForPosition(sender.getEntityWorld().provider.getDimension(),sender.getPosition());
            sendChat(sender, new String[]{"Currently in region "+currentRegion.getName()});
        }else if(args[0].equalsIgnoreCase("advancements")){
            File configDir = DifficultyManager.getConfigDir();
            File advancementsFile = new File(configDir,"progdiff_advancements.txt");
            try(BufferedWriter writer = new BufferedWriter(new FileWriter(advancementsFile))){
                for(Advancement advancement : sender.getServer().getAdvancementManager().getAdvancements()){
                    String id = advancement.getId().toString();
                    if(!id.startsWith("minecraft:recipes")) {
                        writer.write(advancement.getId().toString());
                        writer.newLine();
                    }
                }
            }catch(Exception e){
                sendChat(sender, new String[]{
                        "There was a problem writing the advancements file.",
                });
                if(advancementsFile.exists()){
                    try {
                        advancementsFile.delete();
                    }catch(Exception e2){
                        sendChat(sender, new String[]{
                                "There was a problem deleting the broken file.",
                                "Please manually delete the \"progdiff_advancements.txt\" file before trying again."
                        });
                    }
                }
            }

        }else{
            sendChat(sender,usage);
        }
    }

    private void sendChat(ICommandSender sender, String[] msg){
        EntityPlayer player = (EntityPlayer)sender.getCommandSenderEntity();
        for (String str : msg)
        {
            TextComponentString line = new TextComponentString(str);
            player.sendMessage(line);
        }
    }

    @Override
    public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos) {
        if (args.length == 1) {
            String[] validCompletions = new String[]{
                    "sync",
                    "killmodified",
                    "advancements",
                    "killmobs",
                    "region",
                    "simulate",
                    "simulateDetailed"
            };
            return CommandBase.getListOfStringsMatchingLastWord(args, validCompletions);
        }
        if(args.length == 2 && args[0].startsWith("simulate")){
            String[] validCompletions = getMobList();
            return CommandBase.getListOfStringsMatchingLastWord(args, validCompletions);
        }
        return CommandBase.getListOfStringsMatchingLastWord(args, new String[0]);
    }

    private String[] getMobList(){
        List<String> lines = Lists.newArrayList();
        for(EntityEntry entry : ForgeRegistries.ENTITIES.getValues()){
            if(EntityLiving.class.isAssignableFrom(entry.getEntityClass())) {
                lines.add(entry.getName());
            }
        }
        return lines.toArray(new String[lines.size()]);
    }
}


text:
package herddb.network.netty;

import herddb.proto.Pdu;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Handles messages
 *
 * @author enrico.olivelli
 */
public class ClientInboundMessageHandler extends ChannelInboundHandlerAdapter {

    private static final Logger LOG = Logger.getLogger(ClientInboundMessageHandler.class.getName());

    private final NettyChannel session;

    public ClientInboundMessageHandler(NettyChannel session) {
        this.session = session;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOG.log(Level.SEVERE, "error on channel " + ctx, cause);
        ctx.close();
        session.exceptionCaught(cause);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        session.channelClosed();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        session.pduReceived((Pdu) msg);
    }

}


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

    <groupId>com.github.stephenc</groupId>
    <artifactId>opensocial-java-client</artifactId>
    <version>2.0-SNAPSHOT</version>
    <name>OpenSocial Java Client</name>

    <description>
        The OpenSocial Java Client Library enables you to work with OpenSocial data on your server.
    </description>

    <scm>
        <connection>scm:git:git://github.com/stephenc/opensocial-java-client.git</connection>
        <developerConnection>scm:git:git@github.com:stephenc/opensocial-java-client.git</developerConnection>
        <url>http://github.com/stephenc/opensocial-java-client/tree/master/</url>
    </scm>

    <licenses>
        <license>
            <name>The Apache Software License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
        </license>
    </licenses>

    <dependencies>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.3</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>org.scribe</groupId>
            <artifactId>scribe</artifactId>
            <version>1.0.8</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.easymock</groupId>
            <artifactId>easymock</artifactId>
            <version>2.4</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>2.4</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>2.3</version>
                    <configuration>
                        <source>1.5</source>
                        <target>1.5</target>
                    </configuration>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.5</version>
                </plugin>
                <plugin>
                    <artifactId>maven-failsafe-plugin</artifactId>
                    <version>2.6</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.3</version>
                </plugin>
                <plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>2.3</version>
                </plugin>
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>2.4.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-site-plugin</artifactId>
                    <version>2.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.6</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

    <properties>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <project.build.outputEncoding>UTF-8</project.build.outputEncoding>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

</project>


text:
<?php
include_once('kml_root.php');

class kml_Object extends kml_root {

    var $tagName = 'Object';

    var $id;
    var $targetId;

    /* Constructor */
    function kml_Object($id = null, $targetId = null) {
        if ($id !== null) $this->set_id($id);
        if ($targetId !== null) $this->set_targetId($targetId);
    }

    /* Assignments */
    function set_id($id) { $this->id = $id; }
    function set_targetId($targetId) { $this->targetId = $targetId; }

    /* Render */
    function render($doc) {
        $X = parent::render($doc);

        if (isset($this->id)) $X->setAttribute('id', $this->id);
        if (isset($this->targetId)) $X->setAttribute('targetId', $this->targetId);

        return $X;
    }

}

/**
$a = new kml_Object('iiii');
$a->dump(false);
*/