text:
<?php
//modify vars below
// Database
define('DB_HOSTNAME', 'hostname');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
define('DB_PREFIX', '');
define('SITE_URL', '');
define('ALLOW_SIGNUP', true);
define('SHOW_SIGNUP_LINK', true);
define('USER_NAMES_DISPLAY', 3); // 1 = real names, 2 = usernames, 3 = usernames w/ real names on hover
define('COMMENTS_SYSTEM', 'basic'); // basic, disqus, or disabled
define('DISQUS_SHORTNAME', ''); // only needed if using Disqus for comments

define('SEASON_YEAR', '2015');

//set timezone offset, hours difference between your server's timezone and eastern
define('SERVER_TIMEZONE_OFFSET', +2);

// ***DO NOT EDIT ANYTHING BELOW THIS LINE***
error_reporting(E_ALL ^ E_NOTICE ^ E_STRICT);


text:
[![Python](https://img.shields.io/badge/python-3.4%2C%203.5%2C%203.6-blue.svg)](https://travis-ci.org/xuwenyihust/Visor)
[![release](https://img.shields.io/badge/release-v0.0-orange.svg)](https://github.com/xuwenyihust/Visor/releases/tag/v0.0)
[![Travis](https://travis-ci.org/xuwenyihust/Visor.svg?branch=master)](https://travis-ci.org/xuwenyihust/Visor)
[![license](https://img.shields.io/github/license/mashape/apistatus.svg?maxAge=2592000)](https://github.com/xuwenyihust/Visor/blob/master/LICENSE)
[![Coverage Status](https://coveralls.io/repos/github/xuwenyihust/Visor/badge.svg)](https://coveralls.io/github/xuwenyihust/Visor)
[![Percentage of issues still open](http://isitmaintained.com/badge/open/xuwenyihust/Visor.svg)](http://isitmaintained.com/project/xuwenyihust/Visor "Percentage of issues still open")

# Visor: Real-time Log Monitor - [Read The Docs](https://goo.gl/F0rADZ)

Web page: *https://xuwenyihust.github.io/Visor/*

Visor is a real-time log monitor that supports different log patterns, currently Apache access log format and Apache error log format.

Visor can monitor multiple log sources at the same time, and in realtime with the help of Apache Kafka and Spark Streaming.

This can be a simple and relative complete example of real-time log monitor, if you have a lot of continously generated logs to be analyzed, or you want to learn how to build a log monitor, Visor can be a good choice.

Also, if you want to see how Visor works, or have your own monitor to test, but you don't have access to real logs, Visor has its own fake log generator to generate likely log files for analytics.

## Documentation
The Visor's documentation is hosted on GitBook at https://xuwenyihust.gitbooks.io/visor-real-time-log-monitor/content/.

## Overview
Visor is designed to be highly modular. Easly to be configured, and extended if you want.

The whole platform is composed of several components:
* Fake log generator
* Log import system
* Log analysis system
* Alerting system
* Output Storage
* Dashboard

### Fake Log Generator

The generated log lines will be stored into files by default, you can also stream them into the analysis part through TCP sockets or Apache Kafka.

#### Log Format

  Currently we support generating and analyzing 2 [log formats](https://github.com/xuwenyihust/Visor/wiki/Log-Formats): Apache access log format and Apache error log format.

|Access Log Fields|Error Log Fields|
|-----|-----|
|IP address of the client|Date and time|
|RFC 1413 identity of the client|Message level|
|UserID of the client|Process ID|
|The time that the request was received|Client Address|
|Request line from the client|Detailed error message|
|HTTP status code|N/A|
|Size of the object returned to the client|N/A|

#### Log Traffic Control

In real world, log traffic may have huge **peaks**, and these peaks may lead to high latencies in our streaming system.

So the generator supports suddenly producing huge amounts of logs in a short time to try to give the streaming system more pressures.

* **Log import rates shown by Spark UI:** (*with backpressure off*)

#### Log Content Control

The generator supports controlling the log fields contents, such as HTTP status code in access logs and client address in error logs.

* **Client address distribution:** (*binomial distribution*)

  Initialize a pool of client addresses, then generate the index to the pool applying binomial distribution every time to select address for a error log line.

### Log Import
Support 3 log import modes:
* Direct file import
* TCP socket transmission
* Apache Kafka streaming

### Log Analysis
The platform also provides 3 different analysis application:
* Mini-monitor
* Spark-monitor

The mini-monitor is a simple prototype, written in pure Python. It can only work with the direct file import method, and write the analysis results into a file.

The application implemented with Spark Streaming can realize real-time when used with Apache Kafka.

### Alert System & Summary Report
* [Alert System](https://github.com/xuwenyihust/Visor/wiki/Alert-System)

  Can detect & announce errors with very short latency through email.

* [Summary Report](https://github.com/xuwenyihust/Visor/wiki/Summary-Report)

  Will be generated every interval (configured by users), to report informations including total # of errors in the last report interval, error rate, top ip addresses etc.

  ![summary report](https://github.com/xuwenyihust/Visor/blob/master/img/summary_report.JPG)

### Architecture

Kafka + Spark Streaming:

## Configuration
### Environment Variables
Add the application's root directory to both `$PYTHONPATH` and `$VISORHOME`.

### Configuration Files
Use JSON for configuration files, all stored under **$HOME/config**.

An example of the configuration files:
```json
{
    "heartbeat" : {
        "interval": "3",
        "message": "HEARBEAT"
    },
    "warn": {
        "interval": {
            "min": 5,
            "max": 30
            },
        "message": [
            "Have no idea what the professor is talking about",
            "My phone is out of battery",
            "Forgot to bring my wallet with me",
            "Do not play overwatch"
        ]
    }
```

### Alert / Report Sender Email

A new json file needs to be created by user to store the authentication information of the Alert / Report system sender email.

The format should be like:

```json
{
	"email": {
		"address": "XXXXXXXXXXXXX",
		"password": "XXXXXXXXXXXXX"
	}
}

```
And named after 'private.json'.

## Usage

### Direct File Import + Mini-Monitor

* Run fake log generator:

```
python3.4 $VISORHOME/src/fake_log_gen/fake_log_gen.py -m [access/error] -o [logfile]
```

* Run Mini-Monitor to analyze generated log files:
```
python3.4 $VISORHOME/src/mini_monitor/mini_monitor.py -i [logfile]
```

### TCP Transmission + Spark Streaming

* Generate fake logs and run as TCP server:

```
python3.4 $VISORHOME/src/socket/fake_log_stream.py -m [access/error]
```

* Run Spark Streaming application to receive & analyze logs

```
$SPARK_HOME/bin/spark-submit $VISORHOME/src/stream_monitor/stream_monitor.py
```

### Kafka Streaming + Spark Streaming
* Start a Kafka server:
```
$KAFKA_HOME/bin/kafka-server-start.sh $KAFKA_HOME/config/server.properties
```

* Create a Kafka topic:
```
$KAFKA_HOME/bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic Logs
```

* Check if the topic has been created:
```
$KAFKA_HOME/bin/kafka-topics.sh --list --zookeeper localhost:2181
```

```
>>> Output:

...
Logs
...
```

* Generate fake logs and run as Kafka producer:
```
python3.4 $VISORHOME/src/fake_log_gen/fake_log_producer.py -m [access/error] -o $VISORHOME/log/fake_log_producer.log
```

* Run Spark Streaming application to consume & analyze logs
```
$SPARK_HOME/bin/spark-submit --packages org.apache.spark:spark-streaming-kafka-0-8_2.11:2.0.0 $VISORHOME/src/kafka_monitor/kafka_monitor.py > $VISORHOME/log/kafka_monitor.log
```

## Environment

Check the [Visor's Wiki](https://github.com/xuwenyihust/Visor/wiki/Environment) to see the test environment.

## Performance

|Spec|Stat|
|------|------|
|Batch Interval|2.5 Sec|
|# of Executors|1|
|# of Cores per Executor|4|
|# of Kafka Topic Partition|1|
|Avg Input Rate|41.76 Rec/Sec|
|Avg Processing Time|1 Sec 982ms|

## Just Some Thoughts
* Run Spark on your laptop, no matter how many cores do you own, you can have only one executor

* There will be some latency (~10 minutes) for the backpressure to take effect
![](https://github.com/xuwenyihust/Visor/blob/master/img/visor_backpressure.JPG)

* Cannot count too much on backpressure
    * You see the import rate drops after some time, but scheduling latency doesn't recover
    * Not sure about 'spark.streaming.backpressure.initialRate''s equivalent in kafka direct API.

* Change the batch interval, the processing time will also change slightly
    * (batch interval: 2.5, proce time: 1.8) --> (batch interval: 2, proce time: 2.1)

## Resources
* [Apache Log Files](https://httpd.apache.org/docs/1.3/logs.html)
* [Unit Testing TCP Server & Client with Python](http://www.devdungeon.com/content/unit-testing-tcp-server-client-python)
* [How to choose the number of topicspartitions in a kafka cluster](https://www.confluent.io/blog/how-to-choose-the-number-of-topicspartitions-in-a-kafka-cluster/)
* [kafka direct + spark streaming + checkpoints + code changes](https://community.cloudera.com/t5/Advanced-Analytics-Apache-Spark/kafka-direct-spark-streaming-checkpoints-code-changes/m-p/38786#M1524)
* [Four Things to Know About Reliable Spark Streaming with Typesafe and Databricks](https://www.slideshare.net/Typesafe_Inc/four-things-to-know-about-reliable-spark-streaming-with-typesafe-and-databricks)
* [Spark & Kafka - Achieving zero data-loss](http://aseigneurin.github.io/2016/05/07/spark-kafka-achieving-zero-data-loss.html)
* [Exploring Stateful Streaming with Apache Spark](http://asyncified.io/2016/07/31/exploring-stateful-streaming-with-apache-spark/)

## License
See the LICENSE file for license rights and limitations (MIT).

redpajama_set_name: RedPajamaGithub


text: - [Google Brillo for Intel Edison](https://communities.intel.com/thread/96539?tstart=0)


text:
.. _usage:

***********************
Using yawd-translations
***********************

.. _languages-model:

The Languages model
+++++++++++++++++++

yawd-translations implements a :class:`translations.models.Language` model that allows
you to manage a website's languages through the admin interface. To use it you need to
enable yawd-translations in your project ``settings.py`` file:

.. code-block:: python

	 ...
	 INSTALLED_APPS = (
	 	...
	 	'translations',
	 	'yawd-elfinder' #yawd-translations prerequisite
	 )

Also make sure your ``MEDIA_ROOT`` setting is set for the language image to work.

.. image:: yawd-translations-add-language.jpg

Working with Languages
----------------------

You can set a single language as `default` (e.g. see image above). This will act as the
language to which your pages will be translated unless another language is activated.
yawd-translations will ensure that only one default language is set at the model level.

The set of languages from which a user can choose is the one defined in
django's `LANGUAGES <https://docs.djangoproject.com/en/dev/ref/settings/#languages>`_
setting. The :class:`translations.models.Language` model uses language codes as
primary keys (to eliminate the need of database joins), where codes are the same as
django language codes. As a result, the django built-in
`translation methods and template-tags <https://docs.djangoproject.com/en/dev/topics/i18n/translation/>`_
can be used. For example, to activate a language:

.. code-block:: python

	 from django.utils.translation import activate
	 from translations.models import Language

	 language = Language.objects.get(default=True)
	 activate(language.pk)

...or in your templates to get language info (with the `language` context variable referring to a
db Language instance):

.. code-block:: django

	{% get_language_info for language.pk as lang %}

If you assign an image to the language, you can retrieve it in your templates like this
(this is all you'll need, but you still can find more in the
`yawd-elfinder documentation <http://yawd-elfinder.readthedocs.org/>`_):

.. code-block:: django

	{% if language.image %}<img src="{{language.image.url}}" alt="{{language.get_name_display}}" />{% endif %}

yawd-translations will add the Languages model to the admin interface so do not forget
your ``admin.autodiscover()`` in your root urls.py module:

.. code-block:: python

	from django.contrib import admin
	admin.autodiscover()

Utility functions
-----------------

yawd-translations provides a set of utility functions to access the available languages.
To get a flat list of the available **language codes** (e.g. `['en', 'de', 'fr']`),
use :func:`translations.utils.get_supported_languages`. For example, in your views:

.. code-block:: python

	from translations.utils import get_supported_languages

	return render_to_response('mytemplate.html', {
    	'available_languages': get_supported_languages(),
	}, RequestContext(request))

...and then in your templates use it with django built-in template tags:

.. code-block:: django

	{% get_language_info_list for available_languages as langs %}
	{% for lang in langs %} ... {% endfor %}

To get the default **language code**, use :func:`translations.utils.get_default_language`.
For example to check if the english language is the default:

.. code-block:: python

	from translations.utils import get_default_language

	if 'en' == get_default_language():
		..do stuff..

Using the utility functions in your code is the recommended way of retrieving language
codes, since they do not produce database queries. For example the above snippet could
also be written as:

.. code-block:: python

	from translations.models import Language

	lang = Language.objects.get(pk='en')
	if lang.default:
		..do stuff..

...but this is not preferred over the previous solution since it would hit the database.

.. note::
	When no languages are set (e.g. when making your first ``syncdb``) these two methods
	will return the value of the global django
	`LANGUAGE_CODE <https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LANGUAGE_CODE>`_
	setting instead.

.. _translation-messages:

Static translation messages
+++++++++++++++++++++++++++

Once yawd-translations is enabled (see :ref:`languages-model` above) you can also edit
the static translation strings through the admin interface without the need of using
the `makemessages <https://docs.djangoproject.com/en/dev/ref/django-admin/#django-admin-makemessages>`_
and `compilemessages <https://docs.djangoproject.com/en/dev/ref/django-admin/#compilemessages>`_
commands, or restarting the web server. To activate this feature you need to define a
directory where yawd-translations will store the ``.po`` and ``.mo`` files.
yawd-translations uses for this purpose the **first** listing (could be more than one)
of django's `LOCALE_PATHS <https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOCALE_PATHS>`_
project setting. In your ``settings.py`` file:

.. code-block:: python

	...
	LOCALE_PATHS = (
		'/path/to/the/translations/folder/',
		...possibly more directories
	)

.. note::
	In some cases, depending on the deployment method of your web application,
	the '/path/to/the/translations/folder/'	may need to be an absolute path.

.. hint::

	yawd-translations allows you to modify the translation messages of all
	``INSTALLED_APPS`` using the admin interface. Overwriting original translation
	files inside an application's source code is not an option, therefore modified
	translation messages must be stored elsewhere. Since ``LOCALE_PATHS`` have a higher
	priority over an application's own translation files, we choose to use this setting
	for our purposes. Behind the scenes yawd-translations will ``makemessages``
	for a given language and then move the generated files to the directory
	dictated by this setting. When you modify a translation message using the admin
	interface, your change will be stored to the copied ``.po`` file, yawd-translations
	will ``compilemessages`` and load the new translations.

To use this feature navigate to the change page of a Language (image below) and select
the `'Translate messages'` tool in the upper-right corner.

.. image:: yawd-translations-translate-messages.jpg

In the `'Translate messages'` page you can see two new tool buttons - again located
in the upper-right corner:
`'Regenerate messages'` and `'Update messages'` (if no messages exist for this language
you will only see the first tool, labeled `'Generate messages'` instead). Both actions
will scan the installed applications for static translation messages. The only
difference between them is that the first will **override any changes** you might
have made so far, while the latter will just update your existing translations with
possible new translation strings added to the code since your last scan.

.. note::

	yawd-translations will generate translation messages only for applications having
	a `locale` directory in their source code. More information can be found on the
	django documentation `here <https://docs.djangoproject.com/en/dev/topics/i18n/translation/#how-django-discovers-translations>`_.

You can control which users and groups can view or edit the translation messages
(e.g. through the admin interface). yawd-translations provides two custom permissions
for this matter: `'Can see translation messages for a language'` and
`'Can edit the language's translation messages'`.

.. _translatable-models:

Translatable models API
+++++++++++++++++++++++

To allow for models whose fields can be translated in all languages,
yawd-translations implements two abstract models;
:class:`translations.models.Translatable` and
:class:`translations.models.Translation`. Use the first to define a model that can
be translated and the latter to define its translations. With this approach we can
have both fields that are common to all languages and fields that must have a
different translation in each language.

A `Translatable` defines a model that can be translated in all languages. Its
models fields will be **common** to all languages. The `Translation` model
defines all fields that should have a different version in each language. It
should have a `ForeignKey <https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey>`_
to the `Translatable`.

.. code-block:: python

	from django.db import models
	from translations.models import Translatable, Translation

	class Product(Translatable):
		sku = models.CharField(max_length=20)
		price = models.FloatField()

	class ProductTranslation(Translation)
		#note the related_name, this is important
		product = models.ForeignKey(Product, related_name='translations')
		title = models.CharField(max_length=100)
		description = models.TextField(blank=True)

		def __unicode__(self):
			return u'%s' % self.title

The above example implements a `Product` model whose `'sku'` and `'price'` will be always the same
regardless of the language, and a `ProductTranslation` whose `'description'` and `'title'`
depend on the language. There are two things to notice here:

* The reverse relation **must** be named 'translations'. Given a `Product` instance we should be able to access its translations through the ``product.translations`` attribute since yawd-translations uses this property in various places.
* In the `Product` model we have not defined a ``__unicode__()`` method. yawd-translations provides a default implementation that will attempt to load the related translation's unicode for the active language. For more information on how this works view the :func:`translations.models.Translatable.get_name` method. You can always override the default ``__unicode__()`` implementation in your models.

.. _access-translations:

How to access translations
--------------------------

The recommended way of retrieving a translation for a given language is using the
:func:`translations.models.Translatable.translation` method provided in the API.
Since `Translatable` models use a custom
`Queryset Manager <https://docs.djangoproject.com/en/dev/topics/db/managers/>`_
to prefetch related translations and minimize the db hits, this method takes advantage
of the cached translations to quickly locate the desired translation. This is a typical
example::

	>>> from django.utils.translation import activate
	>>> product = Product.objects.get(sku='123')
	>>> activate('en')
	>>> product.translation()
	<ProductTranslation: English product title>
	>>> activate('de')
	>>> product.translation()
	<ProductTranslation: German product title>
	>>> product.translation('en')
	<ProductTranslation: English product title>
	>>> product.translation().description
	u'Fancy german product description'

The `'translation()'` method can also be used in your templates:

.. code-block:: django

	{{product.translation.description}}

To generate a filtered list of translations it is always a good idea to  use the
``translations.all()`` queryset. For example to filter translations that have a
`'description'` we should prefer::

	>>> translations = [p for p in product.translations.all() if p.description]

...over::

	>>> translations = product.translations.exclude(description='')

...since the first approach will not hit the database.

.. note::
	There exist several approaches for storing multilingual content in databases.
	If you need a different approach than the one implemented in yawd-translations,
	you could just use the :ref:`languages-model` and design your own application
	models from scratch. The :ref:`translatable-models` comes with a
	:ref:`custom-admin-inline` (to manage translations through the admin interface)
	which you will not be able to use while not using the API. The :ref:`translation-urls`
	could still be used if your models provide a ``get_absolute_url()``
	method.

.. note::
	If when using the Translatable API along with the django admin
	site your translations appear as ``None`` in changelist views
	(or you see a `not translated in 'en-us'` message), you should
	change the value of the default ``LANGUAGE_CODE`` django setting
	to the code of a language defined in your Language model
	(usually just change it from 'en-us' to 'en'). This happens if
	your admin site itself is not multilingual (not declared with the
	:func:`translations.urls.translation_patterns` method) and the
	default admin language is not among the languages by
	yawd-translations.

.. _custom-admin-inline:

Translation admin inline
++++++++++++++++++++++++

When using the :ref:`translatable-models`, an elegant and easy to use way of presenting
`Translation` models in the admin interface is using
`admin inlines <https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin>`_.
It allows the user to edit a `Translatable` and its `Translation` objects in a single
web page.

You can use the :class:`translations.admin.TranslationInline` like you would normally
use any django ``StackedInline`` or ``TabularInline`` in your admin.py, but it will
work for :class:`translations.models.Translation` models only. In your ``admin.py``:

.. code-block:: python

	from django.contrib import admin
	from translations.admin import TranslationInline

	class ProductTranslationAdmin(TranslationInline):
		model =  ProductTranslation

	class ProductAdmin(admin.ModelAdmin):
		inlines = [ProductTranslationAdmin]

	admin.site.register(Product, ProductAdmin)

The above snippet refers to the `Product` and `ProductTranslation` models of the previous :ref:`products example <translatable-models>`.

Screenshot of the :ref:`translatable-models` of the :ref:`yawd-translations demo project <demo-project>`:

.. image:: yawd-translations-custom-inline.jpg

.. _translations-middleware:

The Translations middleware
+++++++++++++++++++++++++++

Django provides a `django.middleware.locale.LocaleMiddleware <https://docs.djangoproject.com/en/dev/topics/i18n/translation/#how-django-discovers-language-preference>`_
that should be enabled when working with internationalized projects. Although
yawd-translations builds upon the original django translation mechanism,
this middleware is unaware of our default language (which is stored in the database if
at least one :class:`translations.models.Language` is set) and will not use it as
the default project language. To solve this issue we have implemented the
:class:`translations.middleware.TranslationMiddleware` middleware that will determine
the current language as follows (as opposed to the original
`language discovery algorithm <https://docs.djangoproject.com/en/dev/topics/i18n/translation/#how-django-discovers-language-preference>`_):

* First, it looks for the language prefix in the requested URL. This is only performed when you are using the `i18n_patterns <https://docs.djangoproject.com/en/dev/topics/i18n/translation/#django.conf.urls.i18n.i18n_patterns>`_ or the :func:`translations.urls.translation_patterns` function in your root URLconf.
* Failing that, it looks for a django_language key in the current user's session.
* Failing that, it looks for a cookie. The name of the cookie used is set by the LANGUAGE_COOKIE_NAME setting. (The default name is django_language.)
* Failing that, it uses the global default :class:`translations.models.Language` (if no Language is set, the :func:`translations.utils.get_default_language` will return the  global ``LANGUAGE_CODE`` setting, so this will be used instead).

To enable the Translations middleware in your global settings.py:

.. code-block:: python

	...
	MIDDLEWARE_CLASSES = (
		'translations.middleware.TranslationMiddleware',
		...
	)

If you use the ``SessionMiddleware``, ``TranslationMiddleware`` should come after it
since the latter could use session data. Also make sure the ``TranslationMiddleware``
is one of your first middlewares and that the original
:class:`django.middleware.locale.LocaleMiddleware` is not enabled.

The Translations middleware can be used in conjuction with both
`i18n_patterns <https://docs.djangoproject.com/en/dev/topics/i18n/translation/#django.conf.urls.i18n.i18n_patterns>`_
and :ref:`translation_patterns <translation-patterns>`. When using the first
(and the default language is english for example) it will redirect all calls
to the `'/whatever/'` URL to `'/en/whatever/'`, while when using the latter it will
*not* redirect URLs.

Another enchancement of the Translations middleware against the original
is that it uses permanent redirects (301) instead of temporary (302) when redirecting
URLs. For more information on this, see
`django ticket #19277 <https://code.djangoproject.com/ticket/19277>`_ and
`The impact of Django page redirects to SEO - Fixing internationalized pattern URLs <http://blog.yawd.eu/2012/impact-django-page-redirects-seo/>`_.

In theory you do not need to have `yawd-translations` in your installed applications
to use this middleware. If you do not want to build upon yawd-translations' db Language
functionality and you're ok with the modified language discovery algorithm, you could
use it in conjuction with the :ref:`translation_patterns <translation-patterns>` or just for the permanent
redirect fix.

.. _translation-patterns:

Translation patterns
--------------------

In Django 1.4 `i18n_patterns <https://docs.djangoproject.com/en/dev/topics/i18n/translation/#django.conf.urls.i18n.i18n_patterns>`_
were introduced to allow for URLs that change based on the language. For example
`'/en/contact/'` could show the english contact page and `'/fr/contact/'` could
show the french contact page. i18n_patterns do not match against a default
language. A `'/contact/'` url will not match and the default ``LocaleMiddleware``
will redirect to `'/en/contact/'` if the default language is english.

yawd-translations implements the :func:`translations.urls.translation_patterns`
pattern function, that will do the exact opposite: it will match `'/contact/'` as the default permalink and reject
`'/en/contact/'`. :ref:`translations-middleware` will then make sure all cals to
`'/en/contact/'` are redirected to `'/contact/'`. This is a more common practise in
web development, both for search-engine optimization and consistency reasons.

An example use of translation_patterns is the following (in your urls.py):

.. code-block:: python

	from django.conf.urls import url
	from translations.urls import translation_patterns
	#import the view as well :)

	urlpatterns += translation_patterns('',
		url(r'^contact/$', ContactView.as_view(), name='contact-view'),
		...
	)

To use the ``translation_patterns``, the :ref:`TranslationMiddleware <translations-middleware>` must be enabled.

Additional tools
++++++++++++++++

.. _languages-context-processor:

Languages context processor
---------------------------

You can use the ``languages`` context processor
to add a list of the available languages, the default language code and the clean
current url (the url path with the language code prefix stripped out) to templates
``RequestContext``. For more information on what is being added, view
:func:`translations.context_processors`. You can enable the processor as follows
(in your global `settings.py`):

.. code-block:: python

	...
	TEMPLATE_CONTEXT_PROCESSORS = (
		'translations.context_processors.languages',
		...
	)

.. _translation-urls:

translation_urls template tag
-----------------------------

A common operation when working with multilingual websites is to implement
a 'language switcher', that links to the equivalent URL for each available language.
yawd-translations provides a simple template tag that accepts a model object as
argument and prints out all urls for this object, using the ``get_absolute_url()``
method. If no url exists for a certain language it will link to the homepage
(e.g. `'/de/'`) of that language. Example use:

.. code-block:: django

	{% load translations_tags %}

	<div class="clanguages">{% translation_urls product %}</div>

... where product could be an instance of the following model:

.. code-block:: python

	class Product(Translatable):

		....
		@models.permalink
		get_absolute_url(self):
			return ('my-view', (), {'pk' : self.pk })

If the context object variable is an instance of :class:`translations.models.Translatable`
and it has no ``get_absolute_url()`` method, the tag will search for a
``get_absolute_url()`` implementation in the related
:class:`translations.models.Translation` and use that instead. Failing that, it
will return the home url for that language.

.. note::

	If the argument is a string, the tag will assume it's a URL and prepend
	the language prefix to the string (e.g. ``{% translation_urls 'contact' %}``
	will return `'\de\contact\'` for the german language.

You can replace the tag's html output by overriding the
``language_switcher.html`` template.

To see the ``translation_urls`` template tag in action take a look at the
:ref:`demo-project`.


text:
namespace _09.FirstFiftyMembersOfSequance
{
    /* We are given the following sequence:
        S1 = N;
        S2 = S1 + 1;
        S3 = 2*S1 + 1;
        S4 = S1 + 2;
        S5 = S2 + 1;
        S6 = 2*S2 + 1;
        S7 = S2 + 2;
        ...
      Using the Queue<T> class write a program to print its first 50 members for given N.
      Example: N=2 -> 2, 3, 5, 4, 4, 7, 5, 6, 11, 7, 5, 9, 6, ... */

    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class FirstFiftyMembers
    {
        public static void Main()
        {
            int n = 2;
            Queue<int> numbers = new Queue<int>();

            numbers.Enqueue(n);
            Console.WriteLine(numbers.Peek());

            for (int i = 0; i < 50; i++)
            {
                int currentNumber = numbers.Dequeue();

                numbers.Enqueue(currentNumber + 1);
                Console.WriteLine(numbers.Last());

                numbers.Enqueue(currentNumber * 2 + 1);
                Console.WriteLine(numbers.Last());

                numbers.Enqueue(currentNumber + 2);
                Console.WriteLine(numbers.Last());
            }
        }
    }
}


text:
require 'erb'
require 'active_support'
require 'active_support/core_ext'
require 'ari/generators/api'
require 'ari/generators/attribute'
require 'ari/generators/model'
require 'ari/generators/operation'
require 'ari/generators/parameter'
require 'ari/generators/property'

module Ari
  module Generators
    class ResourceGenerator

      def initialize(resource_name, specification, options = {})
        @resource_name = resource_name.underscore
        @klass_name = @resource_name.classify
        @specification = specification
        @options = options
      end

      def template_path(klass)
        File.join(__dir__, 'templates', "#{klass}.rb.erb")
      end

      def destination_path(klass)
        File.join(__dir__, '..', klass)
      end

      def generate_only_models?
        @options.fetch(:only_models, false)
      end

      def generate
        generate_resource
        generate_models
      end

      def generate_resource
        erb = ERB.new(IO.read(template_path('resource')), nil, '-')
        File.open(File.join(destination_path('resources'), "#{resource_name}.rb"), 'w') do |f|
          f.write erb.result(binding)
        end
      end

      def generate_models
        erb = ERB.new(IO.read(template_path('model')), nil, '-')
        models.each do |model|
          next if model.name == resource_name
          File.open(File.join(destination_path('models'), "#{model.name}.rb"), 'w') do |f|
            f.write erb.result(model.instance_eval { binding })
          end
        end
      end

      def klass_name
        @klass_name
      end

      def resource_klass_name
        options.fetch(:resource_klass_name, klass_name)
      end

      def resource_attributes
        models.detect { |m| m.klass_name == klass_name }.properties rescue []
      end

      def resource_name
        @resource_name.singularize
      end

      def resource_plural_name
        @resource_name
      end

      def id_attribute_name
        @options.fetch(:id_attribute_name, "#{klass_name.camelcase(:lower)}Id")
      end

      def apis
        @apis ||= @specification['apis'].map { |api| Api.new(api) }
      end

      def models
        @models ||= @specification['models'].map { |klass_name, options| Model.new(klass_name, self, options) }
      end

      def inherits_from
        generate_only_models? ? 'Model' : 'Resource'
      end

    end
  end
end


text:
package com.google.cloud.genomics.api.client.commands;

import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.google.api.services.genomics.Genomics;
import com.google.api.services.genomics.model.CallSet;

import java.io.IOException;

@Parameters(commandDescription = "Updates a call set")
public class UpdateCallSetCommand extends BaseCommand {

  @Parameter(names = {"--id", "--call_set_id" },
      description = "The ID of the call set that will be changed",
      required = true)
  public String callSetId;

  @Parameter(names = "--name",
      description = "The new name of the call set",
      required = true)
  public String name;

  @Override
  public void handleRequest(Genomics genomics) throws IOException {
    CallSet callSet = new CallSet().setName(name);
    callSet = genomics.callsets().patch(callSetId, callSet).execute();

    System.out.println("The call set was updated: " + callSet.toPrettyString());
  }
}


text:
#pragma once
#include <aws/glue/Glue_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/glue/model/Sort.h>
#include <utility>

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

  /**
   *
Specifies a field to sort by and a sort order.

See Also:
   AWS
   * API Reference

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

    /**
     *
The name of the field on which to sort.

     */
    inline const Aws::String& GetFieldName() const{ return m_fieldName; }

    /**
     *
The name of the field on which to sort.

     */
    inline bool FieldNameHasBeenSet() const { return m_fieldNameHasBeenSet; }

    /**
     *
The name of the field on which to sort.

     */
    inline void SetFieldName(const Aws::String& value) { m_fieldNameHasBeenSet = true; m_fieldName = value; }

    /**
     *
The name of the field on which to sort.

     */
    inline void SetFieldName(Aws::String&& value) { m_fieldNameHasBeenSet = true; m_fieldName = std::move(value); }

    /**
     *
The name of the field on which to sort.

     */
    inline void SetFieldName(const char* value) { m_fieldNameHasBeenSet = true; m_fieldName.assign(value); }

    /**
     *
The name of the field on which to sort.

     */
    inline SortCriterion& WithFieldName(const Aws::String& value) { SetFieldName(value); return *this;}

    /**
     *
The name of the field on which to sort.

     */
    inline SortCriterion& WithFieldName(Aws::String&& value) { SetFieldName(std::move(value)); return *this;}

    /**
     *
The name of the field on which to sort.

     */
    inline SortCriterion& WithFieldName(const char* value) { SetFieldName(value); return *this;}

    /**
     *
An ascending or descending sort.

     */
    inline const Sort& GetSort() const{ return m_sort; }

    /**
     *
An ascending or descending sort.

     */
    inline bool SortHasBeenSet() const { return m_sortHasBeenSet; }

    /**
     *
An ascending or descending sort.

     */
    inline void SetSort(const Sort& value) { m_sortHasBeenSet = true; m_sort = value; }

    /**
     *
An ascending or descending sort.

     */
    inline void SetSort(Sort&& value) { m_sortHasBeenSet = true; m_sort = std::move(value); }

    /**
     *
An ascending or descending sort.

     */
    inline SortCriterion& WithSort(const Sort& value) { SetSort(value); return *this;}

    /**
     *
An ascending or descending sort.

     */
    inline SortCriterion& WithSort(Sort&& value) { SetSort(std::move(value)); return *this;}

  private:

    Aws::String m_fieldName;
    bool m_fieldNameHasBeenSet;

    Sort m_sort;
    bool m_sortHasBeenSet;
  };

} // namespace Model
} // namespace Glue
} // namespace Aws


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/dialogflow/v2beta1/intent.proto

package com.google.cloud.dialogflow.v2beta1;

public interface DeleteIntentRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.dialogflow.v2beta1.DeleteIntentRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. The name of the intent to delete. If this intent has direct or
   * indirect followup intents, we also delete them.
   * Supported formats:
   * - `projects/<Project ID>/agent/intents/<Intent ID>`
   * - `projects/<Project ID>/locations/<Location ID>/agent/intents/<Intent ID>`
   *

   *
   *
   * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The name.
   */
  java.lang.String getName();
  /**
   *
   *
   *

   * Required. The name of the intent to delete. If this intent has direct or
   * indirect followup intents, we also delete them.
   * Supported formats:
   * - `projects/<Project ID>/agent/intents/<Intent ID>`
   * - `projects/<Project ID>/locations/<Location ID>/agent/intents/<Intent ID>`
   *

   *
   *
   * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The bytes for name.
   */
  com.google.protobuf.ByteString getNameBytes();
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Custom Elements - Ember Starter</title>
  <link rel="stylesheet" href="https://js.arcgis.com/4.0beta3/esri/css/main.css">


text:
* local OS X install, R 3.1.2
* ubuntu 12.04 (on travis-ci), R 3.1.2
* win-builder (devel and release)

## R CMD check results
There were no ERRORs, WARNINGs, or NOTEs.


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 317663 $ -->

<refentry xml:id="solrquery.setstats" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>SolrQuery::setStats</refname>
  <refpurpose>Enables or disables the Stats component</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <modifier>public</modifier> <type>SolrQuery</type><methodname>SolrQuery::setStats</methodname>
   <methodparam><type>bool</type><parameter>flag</parameter></methodparam>
  </methodsynopsis>
  <para>
   Enables or disables the Stats component.
  </para>

 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>flag</parameter></term>
     <listitem>
      <para>
      &true; turns on the stats component and &false; disables it.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   Returns the current SolrQuery object, if the return value is used.
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


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

	<title>Grids CSS Example - YUI Grids - Preset Template T5, 240px Right-Aligned Narrow Column</title>
	<link rel="stylesheet" type="text/css" href="../../build/reset-fonts-grids/reset-fonts-grids.css">

Header - Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas sit amet metus. Nunc quam elit, posuere nec, auctor in, rhoncus quis, dui. Aliquam erat volutpat. Ut dignissim, massa sit amet dignissim cursus, quam lacus feugiat.

Main B - Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

B - Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Footer - Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas sit amet metus. Nunc quam elit, posuere nec, auctor in, rhoncus quis, dui. Aliquam erat volutpat. Ut dignissim, massa sit amet dignissim cursus, quam lacus feugiat.


text:
namespace ash {

namespace {

// The time duration for fading out when closing an item.
constexpr base::TimeDelta kCloseFadeOut = base::Milliseconds(100);

// The time duration for scaling down when an item is closed.
constexpr base::TimeDelta kCloseScale = base::Milliseconds(100);

// The time duration for widgets to fade in.
constexpr base::TimeDelta kFadeInDelay = base::Milliseconds(83);
constexpr base::TimeDelta kFadeIn = base::Milliseconds(167);

// The time duration for widgets to fade out.
constexpr base::TimeDelta kFadeOut = base::Milliseconds(100);

constexpr base::TimeDelta kFromHomeLauncherDelay = base::Milliseconds(250);
constexpr base::TimeDelta kHomeLauncherTransition = base::Milliseconds(350);

// Time duration of the show animation of the drop target.
constexpr base::TimeDelta kDropTargetFade = base::Milliseconds(250);

// Time duration to fade in overview windows when a window drag slows down or
// stops.
constexpr base::TimeDelta kFadeInOnWindowDrag = base::Milliseconds(350);

base::TimeDelta GetAnimationDuration(OverviewAnimationType animation_type) {
  switch (animation_type) {
    case OVERVIEW_ANIMATION_NONE:
      return base::TimeDelta();
    case OVERVIEW_ANIMATION_ENTER_OVERVIEW_MODE_FADE_IN:
      return kFadeIn;
    case OVERVIEW_ANIMATION_EXIT_OVERVIEW_MODE_FADE_OUT:
      return kFadeOut;
    case OVERVIEW_ANIMATION_LAYOUT_OVERVIEW_ITEMS_ON_ENTER:
    case OVERVIEW_ANIMATION_LAYOUT_OVERVIEW_ITEMS_IN_OVERVIEW:
    case OVERVIEW_ANIMATION_LAYOUT_OVERVIEW_ITEMS_ON_EXIT:
    case OVERVIEW_ANIMATION_RESTORE_WINDOW:
    case OVERVIEW_ANIMATION_RESTORE_WINDOW_ZERO:
    case OVERVIEW_ANIMATION_SPAWN_ITEM_IN_OVERVIEW:
      return kTransition;
    case OVERVIEW_ANIMATION_CLOSING_OVERVIEW_ITEM:
      return kCloseScale;
    case OVERVIEW_ANIMATION_CLOSE_OVERVIEW_ITEM:
      return kCloseFadeOut;
    case OVERVIEW_ANIMATION_ENTER_FROM_HOME_LAUNCHER:
    case OVERVIEW_ANIMATION_EXIT_TO_HOME_LAUNCHER:
      return kHomeLauncherTransition;
    case OVERVIEW_ANIMATION_DROP_TARGET_FADE:
      return kDropTargetFade;
    case OVERVIEW_ANIMATION_NO_RECENTS_FADE:
      return kTransition;
    case OVERVIEW_ANIMATION_OPACITY_ON_WINDOW_DRAG:
      return kFadeInOnWindowDrag;
  }
  NOTREACHED();
  return base::TimeDelta();
}

void ReportCloseSmoothness(int smoothness) {
  UMA_HISTOGRAM_PERCENTAGE_IN_CLAMSHELL(
      "Ash.Overview.AnimationSmoothness.Close.ClamshellMode", smoothness);
  UMA_HISTOGRAM_PERCENTAGE_IN_TABLET(
      "Ash.Overview.AnimationSmoothness.Close.TabletMode", smoothness);
}

}  // namespace

ScopedOverviewAnimationSettings::ScopedOverviewAnimationSettings(
    OverviewAnimationType animation_type,
    aura::Window* window)
    : ScopedOverviewAnimationSettings(animation_type,
                                      window->layer()->GetAnimator()) {}

ScopedOverviewAnimationSettings::ScopedOverviewAnimationSettings(
    OverviewAnimationType animation_type,
    ui::LayerAnimator* animator)
    : animation_settings_(
          std::make_unique<ui::ScopedLayerAnimationSettings>(animator)) {
  switch (animation_type) {
    case OVERVIEW_ANIMATION_NONE:
      animation_settings_->SetPreemptionStrategy(
          ui::LayerAnimator::REPLACE_QUEUED_ANIMATIONS);
      break;
    case OVERVIEW_ANIMATION_ENTER_OVERVIEW_MODE_FADE_IN:
      animation_settings_->SetTweenType(gfx::Tween::FAST_OUT_SLOW_IN);
      animation_settings_->SetPreemptionStrategy(
          ui::LayerAnimator::REPLACE_QUEUED_ANIMATIONS);
      animator->SchedulePauseForProperties(kFadeInDelay,
                                           ui::LayerAnimationElement::OPACITY);
      break;
    case OVERVIEW_ANIMATION_EXIT_OVERVIEW_MODE_FADE_OUT:
      animation_settings_->SetTweenType(gfx::Tween::FAST_OUT_SLOW_IN);
      animation_settings_->SetPreemptionStrategy(
          ui::LayerAnimator::REPLACE_QUEUED_ANIMATIONS);
      break;
    case OVERVIEW_ANIMATION_LAYOUT_OVERVIEW_ITEMS_ON_ENTER:
    case OVERVIEW_ANIMATION_LAYOUT_OVERVIEW_ITEMS_IN_OVERVIEW:
    case OVERVIEW_ANIMATION_LAYOUT_OVERVIEW_ITEMS_ON_EXIT:
    case OVERVIEW_ANIMATION_RESTORE_WINDOW:
    case OVERVIEW_ANIMATION_SPAWN_ITEM_IN_OVERVIEW:
      animation_settings_->SetTweenType(gfx::Tween::EASE_OUT);
      animation_settings_->SetPreemptionStrategy(
          ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
      break;
    case OVERVIEW_ANIMATION_RESTORE_WINDOW_ZERO:
      animation_settings_->SetTweenType(gfx::Tween::ZERO);
      animation_settings_->SetPreemptionStrategy(
          ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
      break;
    case OVERVIEW_ANIMATION_CLOSING_OVERVIEW_ITEM:
    case OVERVIEW_ANIMATION_CLOSE_OVERVIEW_ITEM:
      animation_settings_->SetTweenType(gfx::Tween::EASE_OUT);
      animation_settings_->SetPreemptionStrategy(
          ui::LayerAnimator::ENQUEUE_NEW_ANIMATION);
      break;
    case OVERVIEW_ANIMATION_ENTER_FROM_HOME_LAUNCHER:
      animation_settings_->SetTweenType(gfx::Tween::FAST_OUT_SLOW_IN);
      animation_settings_->SetPreemptionStrategy(
          ui::LayerAnimator::ENQUEUE_NEW_ANIMATION);
      // Add animation delay when entering from home launcher.
      animator->SchedulePauseForProperties(kFromHomeLauncherDelay,
                                           ui::LayerAnimationElement::OPACITY);
      break;
    case OVERVIEW_ANIMATION_EXIT_TO_HOME_LAUNCHER:
      animation_settings_->SetTweenType(gfx::Tween::FAST_OUT_SLOW_IN);
      animation_settings_->SetPreemptionStrategy(
          ui::LayerAnimator::REPLACE_QUEUED_ANIMATIONS);
      break;
    case OVERVIEW_ANIMATION_DROP_TARGET_FADE:
      animation_settings_->SetTweenType(gfx::Tween::EASE_IN);
      animation_settings_->SetPreemptionStrategy(
          ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
      break;
    case OVERVIEW_ANIMATION_NO_RECENTS_FADE:
      animation_settings_->SetTweenType(gfx::Tween::EASE_IN_OUT);
      animation_settings_->SetPreemptionStrategy(
          ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
      break;
    case OVERVIEW_ANIMATION_OPACITY_ON_WINDOW_DRAG:
      animation_settings_->SetTweenType(gfx::Tween::FAST_OUT_SLOW_IN);
      animation_settings_->SetPreemptionStrategy(
          ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
      break;
  }
  animation_settings_->SetTransitionDuration(
      GetAnimationDuration(animation_type));
  if (animation_type == OVERVIEW_ANIMATION_CLOSING_OVERVIEW_ITEM ||
      animation_type == OVERVIEW_ANIMATION_CLOSE_OVERVIEW_ITEM) {
    close_reporter_.emplace(animation_settings_->GetAnimator(),
                            metrics_util::ForSmoothness(
                                base::BindRepeating(&ReportCloseSmoothness)));
  }
}

ScopedOverviewAnimationSettings::~ScopedOverviewAnimationSettings() = default;

void ScopedOverviewAnimationSettings::AddObserver(
    ui::ImplicitAnimationObserver* observer) {
  animation_settings_->AddObserver(observer);
}

void ScopedOverviewAnimationSettings::CacheRenderSurface() {
  animation_settings_->CacheRenderSurface();
}

void ScopedOverviewAnimationSettings::DeferPaint() {
  animation_settings_->DeferPaint();
}

void ScopedOverviewAnimationSettings::TrilinearFiltering() {
  animation_settings_->TrilinearFiltering();
}

ui::LayerAnimator* ScopedOverviewAnimationSettings::GetAnimator() {
  return animation_settings_->GetAnimator();
}

}  // namespace ash


text:
package controller

import (
	"crypto/tls"
	"crypto/x509"
	"net/http"
	"time"

	"github.com/golang/glog"

	utilwait "k8s.io/apimachinery/pkg/util/wait"
	apifilters "k8s.io/apiserver/pkg/endpoints/filters"
	apirequest "k8s.io/apiserver/pkg/endpoints/request"
	apiserver "k8s.io/apiserver/pkg/server"
	apiserverfilters "k8s.io/apiserver/pkg/server/filters"
	"k8s.io/apiserver/pkg/server/healthz"
	genericmux "k8s.io/apiserver/pkg/server/mux"
	genericroutes "k8s.io/apiserver/pkg/server/routes"
	authzwebhook "k8s.io/apiserver/plugin/pkg/authorizer/webhook"
	clientgoclientset "k8s.io/client-go/kubernetes"

	"github.com/openshift/origin/pkg/authorization/authorizer"
	configapi "github.com/openshift/origin/pkg/cmd/server/api"
	serverauthenticator "github.com/openshift/origin/pkg/cmd/server/authenticator"
	"github.com/openshift/origin/pkg/cmd/server/crypto"
	serverhandlers "github.com/openshift/origin/pkg/cmd/server/handlers"
	cmdutil "github.com/openshift/origin/pkg/cmd/util"
)

// TODO make this an actual API server built on the genericapiserver
func RunControllerServer(servingInfo configapi.HTTPServingInfo, kubeExternal clientgoclientset.Interface) error {
	clientCAs, err := getClientCertCAPool(servingInfo)
	if err != nil {
		return err
	}

	mux := genericmux.NewPathRecorderMux("master-healthz")

	healthz.InstallHandler(mux, healthz.PingHealthz)
	initReadinessCheckRoute(mux, "/healthz/ready", func() bool { return true })
	genericroutes.Profiling{}.Install(mux)
	genericroutes.MetricsWithReset{}.Install(mux)

	// TODO: replace me with a service account for controller manager
	tokenReview := kubeExternal.AuthenticationV1beta1().TokenReviews()
	authn, err := serverauthenticator.NewRemoteAuthenticator(tokenReview, clientCAs, 5*time.Minute)
	if err != nil {
		return err
	}
	sarClient := kubeExternal.AuthorizationV1beta1().SubjectAccessReviews()
	remoteAuthz, err := authzwebhook.NewFromInterface(sarClient, 5*time.Minute, 5*time.Minute)
	if err != nil {
		return err
	}

	// requestInfoFactory for controllers only needs to be able to handle non-API endpoints
	requestInfoResolver := apiserver.NewRequestInfoResolver(&apiserver.Config{})
	// the request context mapper for controllers is always separate
	requestContextMapper := apirequest.NewRequestContextMapper()
	authorizationAttributeBuilder := authorizer.NewAuthorizationAttributeBuilder(requestContextMapper, requestInfoResolver)

	// we use direct bypass to allow readiness and health to work regardless of the master health
	authz := serverhandlers.NewBypassAuthorizer(remoteAuthz, "/healthz", "/healthz/ready")
	handler := serverhandlers.AuthorizationFilter(mux, authz, authorizationAttributeBuilder, requestContextMapper)
	handler = serverhandlers.AuthenticationHandlerFilter(handler, authn, requestContextMapper)
	handler = apiserverfilters.WithPanicRecovery(handler)
	handler = apifilters.WithRequestInfo(handler, requestInfoResolver, requestContextMapper)
	handler = apirequest.WithRequestContext(handler, requestContextMapper)

	return serveControllers(servingInfo, handler)
}

// initReadinessCheckRoute initializes an HTTP endpoint for readiness checking
// TODO this looks pointless
func initReadinessCheckRoute(mux *genericmux.PathRecorderMux, path string, readyFunc func() bool) {
	mux.HandleFunc(path, func(w http.ResponseWriter, req *http.Request) {
		if readyFunc() {
			w.WriteHeader(http.StatusOK)
			w.Write([]byte("ok"))

		} else {
			w.WriteHeader(http.StatusServiceUnavailable)
		}
	})
}

// serve starts serving the provided http.Handler using security settings derived from the MasterConfig
func serveControllers(servingInfo configapi.HTTPServingInfo, handler http.Handler) error {
	timeout := servingInfo.RequestTimeoutSeconds
	if timeout == -1 {
		timeout = 0
	}

	server := &http.Server{
		Addr:           servingInfo.BindAddress,
		Handler:        handler,
		ReadTimeout:    time.Duration(timeout) * time.Second,
		WriteTimeout:   time.Duration(timeout) * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	clientCAs, err := getClientCertCAPool(servingInfo)
	if err != nil {
		return err
	}

	go utilwait.Forever(func() {
		glog.Infof("Started health checks at %s", servingInfo.BindAddress)

		extraCerts, err := configapi.GetNamedCertificateMap(servingInfo.NamedCertificates)
		if err != nil {
			glog.Fatal(err)
		}
		server.TLSConfig = crypto.SecureTLSConfig(&tls.Config{
			// Populate PeerCertificates in requests, but don't reject connections without certificates
			// This allows certificates to be validated by authenticators, while still allowing other auth types
			ClientAuth: tls.RequestClientCert,
			ClientCAs:  clientCAs,
			// Set SNI certificate func
			GetCertificate: cmdutil.GetCertificateFunc(extraCerts),
			MinVersion:     crypto.TLSVersionOrDie(servingInfo.MinTLSVersion),
			CipherSuites:   crypto.CipherSuitesOrDie(servingInfo.CipherSuites),
		})
		glog.Fatal(cmdutil.ListenAndServeTLS(server, servingInfo.BindNetwork, servingInfo.ServerCert.CertFile, servingInfo.ServerCert.KeyFile))
	}, 0)

	return nil
}

func getClientCertCAPool(servingInfo configapi.HTTPServingInfo) (*x509.CertPool, error) {
	roots := x509.NewCertPool()
	// Add CAs for API
	certs, err := cmdutil.CertificatesFromFile(servingInfo.ClientCA)
	if err != nil {
		return nil, err
	}
	for _, root := range certs {
		roots.AddCert(root)
	}

	return roots, nil
}


text:
FROM env/vim/base
MAINTAINER zachbray@googlemail.com

RUN sudo apt-get update && \
    sudo apt-get install wget

# INSTALL OPAM
RUN wget https://raw.github.com/ocaml/opam/master/shell/opam_installer.sh -O - | sh -s /usr/local/bin
RUN opam init
RUN eval `opam config env`
RUN sudo apt-get update && \
    sudo apt-get install -y m4

# INSTALL MERLIN
RUN opam install merlin

# CONFIGURE VIM
RUN mv ~/.vimrc ~/.vimrc.backup
RUN opam user-setup install
RUN cat ~/.vimrc.backup >> ~/.vimrc

# INSTALL COMMON PACKAGES
RUN opam install batteries core lwt

# ADD VIM CONFIGURATION
ADD home $HOME

# INSTALL VIM PLUGINS
RUN vim -u $HOME/.vim/plugins.vim +PluginInstall +qall

# SET UP PROFILE
ENV PATH $HOME/.opam/system/bin:$PATH
RUN echo -n ". ~/.opam/opam-init/init.sh > /dev/null 2> /dev/null || true" >> ~/.profile

ENTRYPOINT bash -l -c vim


text:
<?php namespace Limoncello\Contracts\Serializable;

/**
 * @package Limoncello\Contracts
 */
interface ArraySerializableInterface
{
    /**
     * @return array
     */
    public function serialize(): array;

    /**
     * @param array $serialized
     *
     * @return void
     */
    public function unserialize(array $serialized): void;
}


text:
import DS from 'ember-data';

export default DS.Model.extend({
  username: DS.attr('string'),
  password: DS.attr('string'),
  role: DS.attr('string')
});

//DS.Model.reopenClass({
//  FIXTURES: [
//    {id: 1, username: 'pineauk', password: 'blah', role: 'admin'},
//    {id: 2, username: 'bob', password: 'bob', roles: 'user'}
//  ]
//});


text:
You can create a big number object with the function
'''
new bigNumber()
'''. You can pass a javascript number, a string with decimal digits, a scientific number or accounting number (i.e. 2,5437,987.50). If you do not inside a paramether, you will create a big number with value zero (0).
The properties of the bigNumber object are:
1. value --> the value of the big number without the sign
2. sign --> the sign of the number can be '+' or '-'
3. didits
4. integer --> the integer part of a number
5. float --> the digits after the floating point. If do not exist is equal to '0'
If you want to pass another bigNumber object you have to use the function:
``` javascript
bigNumber.toBigNumber()
```
wich gets javascript numbers, stringified numbers and bigNumbers.
If you want to pass a non-decimal integer number you must convert it to decimal with the function:
``` javascript
bigNumber.convertToDecimal()
```
The methods of bigNumbers return bigNumber objects that allows you to chain methods.

## Methods:

**_update()_**

Returns new bigNumber with the changed integer or float parts.

_Example:_
```javascript
let a = new bigNumber(1234.56789);
console.log(a.value);//'1234.56789'
a.float = '1234';
a.integer = '56789';
a = a.update();
console.log(a); //'56789.1234'
```
**_Number()_**

Returns new instance of a bigNumber (= bigNumber.toBigNumber)

_Example_
```javascript
let a = new bigNumber(100),
b = a.Number();
a.integer = '99';
a = a.update();
console.log(a.value);//'99'
console.log(b.value);//100
```
**_Digits()_**

Returns the digits of an bigNumber like bigNumber

_Example_
```javascript
let a = new bigNumber('123456789098765432123456789087654321');
console.log(a.Digits);
bigNumber { value: '35', sign: '+', digits: 1, integer: '35', float: '0' }
```
**_Integer()_ and _Float()_**

Return the integer and the float part of a bigNumber like bigNumber object.

_Example_
```javascript
let n = new bigNumber('3.14159');
let m = n.Integer();
let l = n.Float();
console.log(m.value);//'3'
console.log(l.value);//'14159'
```

**_convertToNumber()_ or _convertToJSNumber()_**

converts the number from bigNumber to javascript (float) format.

_Example_
```javascript
let k = new bigNumber('21');
k.convertToNumber()//21
let l = new bigNumber('1234567890987654321234567890987654321234567890987654321');
l.convertToNumber()//1.2345678909876544e+54
```
**_setSign()_**

Returns the same number with changed the sign. (1 or '+' for positive and -1 or '-' for negative sign)

_Example_
```javascript
let u = new bigNumber('-213');
let v = u.setSign(1);
console.log(v.value);//213
```
**_compareAbs(number)_**

Returns 1 if the absolute value of the first number is greater than the second (passed as method parameter), 0 if is equal and -1 if is smaller

_Example_
```javascript
let f = new bigNumber(123)
f.compareAbs(-321);// -1
f.compareAbs(-123);//0
f.compareAbs(-120)//1
```
**_compare(number)_**

Returns 1 if the first number is greater from the second, 0 if is equals and -1 if is smaller

**_absGt(n)_ or _absoluteGreater(n)_**

Returns true if the first number is absolute bigger than the second and false otherwise

_Example_
```javascript
let a = new bigNumber('500');
a.absGt(-499);//true
a.absGt(500);//false
a.absGt(-600);//false
```
**_absGeq(n)_ or _absoluteGreaterOrEquals(n)_**

Returns true if the first number is absolute bigger or equals than the second and false otherwise

_Example_
```javascript
let a = new bigNumber('500');
a.absGeq(-499);//true
a.absGeq(500);//true
a.absGeq(-600);//false
```
**_absLt(n)_ or _absoluteLesser(n)_**

Returns true if the first number is lesser than the second and false otherwise

_Example_
```javascript
let a = new bigNumber(100);
a.absLt(190);//true
a.absLt(-120);//false
a.absLt(100);//false
```
**_absLeq(n)_ or _absoluteLesserOrEquals(n)_**

Returns true if the first number is lesser or equals than the second and false otherwise

_Example_
```javascript
let a = new bigNumber(100);
a.absLeq(190);//true
a.absLeq(-120);//false
a.absLeq(100);//true
```
**_absEq(n)_ or _absoluteEquals(n)_**

Returns true if the first number is absolute equals to the second and javascript false otherwise

**_absNeq(n)_ or _absoluteNotEquals(n)_**

Returns true if the first number is not equals to the second and false otherwise
Similar behavior also have the methods: **_eq(n)_ or _equals(n)_**, **_lt(n)_ or _lesser(n)_**,**_gt(n)_ or _greater(n)_**, **_geq(n)_ or _greaterOrEquals(n)_**, **_leq(n)_ or _lesserOrEquals(n)_**, **_isEven()_** and **_isOdd()_**.

**_toBase(toBase, fromBase)_**

Convert a number from base with radix fromBase to base with radix toBase. By default the fromBase argument is equal to 10. The method returns bigNumber instance for radix <= 10 and string for radix > 10. To convert an number (in string type) with base greater than 10 use the function
 ```javascript
bigNumber.convertToDecimal(number)
```

_Example_
```javascript
let x = new bigNumber('12345678').toBase(8);
console.log(x);
=> bigNumber {
  value: '57060516',
  sign: '+',
  digits: 7,
  integer: '57060516',
  float: '0'
  }
  let y = new bigNumber('1000000').toBase(64);
  console.log(y);
  '3Q90'
```
**_plus(n)_**

Returns the addition of the two numbers. The argument can be string, number or bigNumber type.

_Example_
```javascript
let a = new bigNumber('5567129807');
let b = new bigNumber('-12647786');
a.plus(b).plus('100').plus(-50);
=> bigNumber {
  value: '5554482071',
  sign: '+',
  digits: 9,
  integer: '5554482071',
  float: '0' }
```
**_minus(n)_**

Returns the sibstract between two mumbers (the bigNumber and the n).

_Example_
```javascript
let a = new bigNumber('342516709182');
a.minus('9876543212345');
=> bigNumber {
  value: '9534026503163',
  sign: '-',
  digits: 12,
  integer: '9534026503163',
  float: '0'
  }
  ```
  **_times(n)_**

Returns the product of two numbers (the big Number with the number n). The function uses implementation of Karatsuba algorithm.

_Example_
  ```javascript
let a = new bigNumber('4453168985467234567656764577256885011399867');
a.times('-998112776998.13568755788997545678109432886932011547767912387');
=> bigNumber {
  value: '4444764862526672038487862634569782914040950755899945101.17515215074671594665844920445159552843079452529',
  sign: '-',
  digits: 102,
  integer: '4444764862526672038487862634569782914040950755899945101',
  float: '17515215074671594665844920445159552843079452529'
  }
  ```
**_divide(n, precision)_**

Returns the division result between the bigNumber and the number n with precision selected from the user. If precision is not inserted, then by default is 10 (10 digits after the floating point).
The function uses the binary devision method. In the code are available also 'divide and conquer' division algorithms (recursionDivision and unbalancedDivision. For more details see: https://members.loria.fr/PZimmermann/mca/mca-0.4.pdf).

_Example_
```javascript
let a = new bigNumber('919283466198762342533777198111377160977127');
a.divide('9981127785789456765432178997897899775600922461.9432467567574', 30)
=> bigNumber {
  value: '0.000092102163796318099760089502',
  sign: '+',
  digits: 31,
  integer: '0',
  float: '000092102163796318099760089502'
  }
```
**_divInt(n)_**

Returns the integer part from the division between two numbers.

_Example_
```javascript
let a = new bigNumber('1234567890')
   .divInt('987654321');
a.value;
=> '12'
```
**_mod(n)_**

Returns the reminder from the division between two numbers.

_Example_
```javascript
let a = new bigNumber('1234567890')
   .mod('98765432');
a.value;
=> '49382706'
```
**_factorial()_**

Returns the factorial of an integer.

_Example_
```javascript
let a = new bigNumber(200).factorial();
a.value;
=>'788657867364790503552363213932185062295135977687173263294742533244359449963403342920304284011984623904177212138919638830257642790242637105061926624952829931113462857270763317237396988943922445621451664240254033291864131227428294853277524242407573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000000000000000'
```
**_primesList()_**

Returns an array with prime numbers until to the big number.

_Example_
```javascript
let a = new bigNumber(30).primesList();
=> [ bigNumber { value: '2', sign: '+', digits: 0, integer: '2', float: '0' },
  bigNumber { value: '3', sign: '+', digits: 0, integer: '3', float: '0' },
  bigNumber { value: '5', sign: '+', digits: 0, integer: '5', float: '0' },
  bigNumber { value: '7', sign: '+', digits: 0, integer: '7', float: '0' },
  bigNumber { value: '11', sign: '+', digits: 1, integer: '11', float: '0' },
  bigNumber { value: '13', sign: '+', digits: 1, integer: '13', float: '0' },
  bigNumber { value: '17', sign: '+', digits: 1, integer: '17', float: '0' },
  bigNumber { value: '19', sign: '+', digits: 1, integer: '19', float: '0' },
  bigNumber { value: '23', sign: '+', digits: 1, integer: '23', float: '0' },
  bigNumber { value: '29', sign: '+', digits: 1, integer: '29', float: '0' }
  ]
```
**_exp(precision)_**

Returns e^bigNumber

_Example_
```javascript
let a = new bigNumber(1).exp(30)
a.value
=> '2.718281828459045235360287471338'
```
## Bugs and other errors

If you find an error in the algorithms structure or bugs, you can refer it in exel_mmm@abv.bg

## License : MIT


text:
/**
 * Authentication Controller
 *
 */

var SettingsController = {

    getSettings : function(req, res) {

        Settings.find().limit(1).exec(function(err, data){
            if(err) return res.negotiate(err);

            return res.json(data[0])
        });
    },
    upsertSettings : function(req, res) {

        Settings.updateOrCreate({version:req.body.version}, req.body,function(err, created){
            if(err) return res.negotiate(err);

            return res.created(created)
        });
    }

};

module.exports = SettingsController;


text:
var throttle = require('lodash/function/throttle');

// #FIXME jQuery crap here

var element;

var reload = throttle(function(ctrl) {
  var route = ctrl.data.player.spectator ? ctrl.router.Round.watcherText(ctrl.data.game.id, ctrl.data.player.color) : ctrl.router.Round.playerText(ctrl.data.game.id + ctrl.data.player.id);
  $(element).load(route.url, function() {
    $(this).find('form').submit(function() {
      var text = $(this).find('.move').val();
      var move = {
        from: text.substr(0, 2),
        to: text.substr(2, 2),
        promotion: text.substr(4, 1)
      };
      ctrl.socket.send("move", move, {
        ackable: true
      });
      return false;
    }).find('.move').focus();
  });
}, 1000);

module.exports = {
  reload: reload,
  init: function(el, ctrl) {
    element = el;
    reload(ctrl);
  }
};


text:
#region License

#endregion

using System;
using System.Collections.Generic;
using System.Text;

namespace Irony.Parsing
{
    public class SourceStream : ISourceStream
    {
        private StringComparison _stringComparison;
        private int _tabWidth;
        private char[] _chars;
        private int _textLength;

        public SourceStream(string text, bool caseSensitive, int tabWidth)
            : this(text, caseSensitive, tabWidth, new SourceLocation())
        { }

        public SourceStream(string text, bool caseSensitive, int tabWidth, SourceLocation initialLocation)
        {
            this._text = text;
            this._textLength = this._text.Length;
            this._chars = this.Text.ToCharArray();
            this._stringComparison = caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase;
            this._tabWidth = tabWidth;
            this._location = initialLocation;
            this._previewPosition = this._location.Position;
            if (this._tabWidth <= 1)
            {
                this._tabWidth = 8;
            }
        }

        #region ISourceStream Members
        public string Text
        {
            get { return this._text; }
        }
        private string _text;

        public int Position
        {
            get
            {
                return this._location.Position;
            }
            set
            {
                if (this._location.Position != value)
                {
                    this.SetNewPosition(value);
                }
            }
        }

        public SourceLocation Location
        {
            [System.Diagnostics.DebuggerStepThrough]
            get
            {
                return this._location;
            }
            set
            {
                this._location = value;
            }
        }
        private SourceLocation _location;

        public int PreviewPosition
        {
            get
            {
                return this._previewPosition;
            }
            set
            {
                this._previewPosition = value;
            }
        }
        private int _previewPosition;

        public char PreviewChar
        {
            [System.Diagnostics.DebuggerStepThrough]
            get
            {
                if (this._previewPosition >= this._textLength)
                {
                    return '\0';
                }

                return this._chars[this._previewPosition];
            }
        }

        public char NextPreviewChar
        {
            [System.Diagnostics.DebuggerStepThrough]
            get
            {
                if (this._previewPosition + 1 >= this._textLength)
                {
                    return '\0';
                }

                return this._chars[this._previewPosition + 1];
            }
        }

        public bool MatchSymbol(string symbol)
        {
            try
            {
                int cmp = string.Compare(this._text, this.PreviewPosition, symbol, 0, symbol.Length, this._stringComparison);
                return cmp == 0;
            }
            catch
            {
                //exception may be thrown if Position + symbol.length > text.Length;
                // this happens not often, only at the very end of the file, so we don't check this explicitly
                //but simply catch the exception and return false. Again, try/catch block has no overhead
                // if exception is not thrown.
                return false;
            }
        }

        public Token CreateToken(Terminal terminal)
        {
            var tokenText = this.GetPreviewText();
            return new Token(terminal, this.Location, tokenText, tokenText);
        }
        public Token CreateToken(Terminal terminal, object value)
        {
            var tokenText = this.GetPreviewText();
            return new Token(terminal, this.Location, tokenText, value);
        }

        [System.Diagnostics.DebuggerStepThrough]
        public bool EOF()
        {
            return this._previewPosition >= this._textLength;
        }
        #endregion

        //returns substring from Location.Position till (PreviewPosition - 1)
        private string GetPreviewText()
        {
            var until = this._previewPosition;
            if (until > this._textLength)
            {
                until = this._textLength;
            }

            var p = this._location.Position;
            string text = this.Text.Substring(p, until - p);
            return text;
        }

        // To make debugging easier: show 20 chars from current position
        public override string ToString()
        {
            string result;
            try
            {
                var p = this.Location.Position;
                if (p + 20 < this._textLength)
                {
                    result = this._text.Substring(p, 20) + Resources.LabelSrcHaveMore;// " ..."
                }
                else
                {
                    result = this._text.Substring(p) + Resources.LabelEofMark; //"(EOF)"
                }
            }
            catch (Exception)
            {
                result = this.PreviewChar + Resources.LabelSrcHaveMore;
            }
            return string.Format(Resources.MsgSrcPosToString, result, this.Location); //"[{0}], at {1}"
        }

        //Computes the Location info (line, col) for a new source position.
        private void SetNewPosition(int newPosition)
        {
            if (newPosition < this.Position)
            {
                throw new Exception(Resources.ErrCannotMoveBackInSource);
            }

            int p = this.Position;
            int col = this.Location.Column;
            int line = this.Location.Line;
            while (p < newPosition)
            {
                if (p >= this._textLength)
                {
                    break;
                }

                var curr = this._chars[p];
                switch (curr)
                {
                    case '\n': line++; col = 0; break;
                    case '\r': break;
                    case '\t': col = (col / this._tabWidth + 1) * this._tabWidth; break;
                    default: col++; break;
                } //switch
                p++;
            }
            this.Location = new SourceLocation(p, line, col);
        }
    }//class
}//namespace


text:
import RPi.GPIO as GPIO
import os

gpio_pin_number=40

GPIO.setmode(GPIO.BOARD)

GPIO.setup(gpio_pin_number, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#It's very important the pin is an input to avoid short-circuits
#The pull-up resistor means the pin is high by default

try:
    GPIO.wait_for_edge(gpio_pin_number, GPIO.FALLING)
    #Use falling edge detection to see if pin is pulled
    #low to avoid repeated polling
    os.system("sudo shutdown -h now")
    #Send command to system to shutdown
except:
    pass

GPIO.cleanup()
#Revert all GPIO pins to their normal states (i.e. input = safe)


text:
[fork]: https://github.com/github/primer/fork
[pr]: https://github.com/github/primer/compare
[style]: http://primercss.io/guidelines/

Hi there! We're thrilled that you'd like to contribute to this project. Your help is essential for keeping it great.

Before you do, would you mind reading [this license agreement](CLA.md)? If you open a PR, we'll assume you agree to it. If you have any hesitation or disagreement, please do open a PR still, but note your concerns as well.

## Using the issue tracker

The [issue tracker](https://github.com/primer/primer/issues) is the preferred channel for [bug reports](#bug-reports), [features requests](#feature-requests) and [submitting pull requests](#pull-requests), but please respect the following restrictions:

* Please **do not** use the issue tracker for personal support requests.
* Please **do not** derail or troll issues. Keep the discussion on topic and respect the opinions of others.
* Please **do not** open issues or pull requests regarding the code in [`Normalize`](https://github.com/necolas/normalize.css) (open them in their respective repositories).

## Bug reports

A bug is a _demonstrable problem_ that is caused by the code in the repository. Good bug reports are extremely helpful, so thanks!

Guidelines for bug reports:

0. **Validate and lint your code** — [validate your HTML](http://html5.validator.nu) to ensure your problem isn't caused by a simple error in your own code.

1. **Use the GitHub issue search** — check if the issue has already been reported.

2. **Check if the issue has been fixed** — try to reproduce it using the latest `master` or development branch in the repository.

3. **Isolate the problem** — ideally create a [reduced test case](https://css-tricks.com/reduced-test-cases/) and a live example. [This JS Bin](http://jsbin.com/lefey/1/edit?html,output) is a helpful template.

A good bug report shouldn't leave others needing to chase you up for more information. Please try to be as detailed as possible in your report. What is your environment? What steps will reproduce the issue? What browser(s) and OS experience the problem? Do other browsers show the bug differently? What would you expect to be the outcome? All these details will help people to fix any potential bugs.

Example:

> Short and descriptive example bug report title
>
> A summary of the issue and the browser/OS environment in which it occurs. If
> suitable, include the steps required to reproduce the bug.
>
> 1. This is the first step
> 2. This is the second step
> 3. Further steps, etc.
>
> `<url>` - a link to the reduced test case
>
> Any other information you want to share that is relevant to the issue being reported. This might include the lines of code that you have identified as causing the bug, and potential solutions (and your opinions on their merits).

## Feature requests

Feature requests are welcome. But take a moment to find out whether your idea fits with the scope and aims of the project. It's up to *you* to make a strong case to convince the project's developers of the merits of this feature. Please provide as much detail and context as possible.

## Pull requests

Good pull requests—patches, improvements, new features—are a fantastic help. They should remain focused in scope and avoid containing unrelated commits.

**Please ask first** before embarking on any significant pull request (e.g. implementing features, refactoring code, porting to a different language), otherwise you risk spending a lot of time working on something that the project's developers might not want to merge into the project.

Adhering to the following process is the best way to get your work included in the project:

1. Fork and clone the repository
2. Configure and install the dependencies: `bower install`
3. Create a new branch: `git checkout -b my-branch-name`
4. Make your change, add tests, and make sure the tests still pass
5. Push to your fork and [submit a pull request](https://help.github.com/articles/creating-a-pull-request/)
6. Pat your self on the back and wait for your pull request to be reviewed and merged.

Here are a few things you can do that will increase the likelihood of your pull request being accepted:

- Follow the [style guide][style].
- Keep your change as focused as possible. If there are multiple changes you would like to make that are not dependent upon each other, consider submitting them as separate pull requests.
- Write a [good commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html).

## Resources

- [Contributing to Open Source on GitHub](https://guides.github.com/activities/contributing-to-open-source/)
- [Using Pull Requests](https://help.github.com/articles/using-pull-requests/)
- [GitHub Help](https://help.github.com)


text:
/**
 * @fileoverview Blockly constants.
 * @author fenichel@google.com (Rachel Fenichel)
 */
'use strict';

goog.provide('Blockly.constants');

/**
 * Number of pixels the mouse must move before a drag starts.
 */
Blockly.DRAG_RADIUS = 5;

/**
 * Number of pixels the mouse must move before a drag/scroll starts from the
 * flyout.  Because the drag-intention is determined when this is reached, it is
 * larger than Blockly.DRAG_RADIUS so that the drag-direction is clearer.
 */
Blockly.FLYOUT_DRAG_RADIUS = 10;

/**
 * Maximum misalignment between connections for them to snap together.
 */
Blockly.SNAP_RADIUS = 20;

/**
 * Delay in ms between trigger and bumping unconnected block out of alignment.
 */
Blockly.BUMP_DELAY = 250;

/**
 * Number of characters to truncate a collapsed block to.
 */
Blockly.COLLAPSE_CHARS = 30;

/**
 * Length in ms for a touch to become a long press.
 */
Blockly.LONGPRESS = 750;

/**
 * Prevent a sound from playing if another sound preceded it within this many
 * milliseconds.
 */
Blockly.SOUND_LIMIT = 100;

/**
 * When dragging a block out of a stack, split the stack in two (true), or drag
 * out the block healing the stack (false).
 */
Blockly.DRAG_STACK = true;

/**
 * The richness of block colours, regardless of the hue.
 * Must be in the range of 0 (inclusive) to 1 (exclusive).
 */
Blockly.HSV_SATURATION = 0.45;

/**
 * The intensity of block colours, regardless of the hue.
 * Must be in the range of 0 (inclusive) to 1 (exclusive).
 */
Blockly.HSV_VALUE = 0.65;

/**
 * Sprited icons and images.
 */
Blockly.SPRITE = {
  width: 96,
  height: 124,
  url: 'sprites.png'
};

// Constants below this point are not intended to be changed.

/**
 * Required name space for SVG elements.
 * @const
 */
Blockly.SVG_NS = 'http://www.w3.org/2000/svg';

/**
 * Required name space for HTML elements.
 * @const
 */
Blockly.HTML_NS = 'http://www.w3.org/1999/xhtml';

/**
 * ENUM for a right-facing value input.  E.g. 'set item to' or 'return'.
 * @const
 */
Blockly.INPUT_VALUE = 1;

/**
 * ENUM for a left-facing value output.  E.g. 'random fraction'.
 * @const
 */
Blockly.OUTPUT_VALUE = 2;

/**
 * ENUM for a down-facing block stack.  E.g. 'if-do' or 'else'.
 * @const
 */
Blockly.NEXT_STATEMENT = 3;

/**
 * ENUM for an up-facing block stack.  E.g. 'break out of loop'.
 * @const
 */
Blockly.PREVIOUS_STATEMENT = 4;

/**
 * ENUM for an dummy input.  Used to add field(s) with no input.
 * @const
 */
Blockly.DUMMY_INPUT = 5;

/**
 * ENUM for left alignment.
 * @const
 */
Blockly.ALIGN_LEFT = -1;

/**
 * ENUM for centre alignment.
 * @const
 */
Blockly.ALIGN_CENTRE = 0;

/**
 * ENUM for right alignment.
 * @const
 */
Blockly.ALIGN_RIGHT = 1;

/**
 * ENUM for no drag operation.
 * @const
 */
Blockly.DRAG_NONE = 0;

/**
 * ENUM for inside the sticky DRAG_RADIUS.
 * @const
 */
Blockly.DRAG_STICKY = 1;

/**
 * ENUM for inside the non-sticky DRAG_RADIUS, for differentiating between
 * clicks and drags.
 * @const
 */
Blockly.DRAG_BEGIN = 1;

/**
 * ENUM for freely draggable (outside the DRAG_RADIUS, if one applies).
 * @const
 */
Blockly.DRAG_FREE = 2;

/**
 * Lookup table for determining the opposite type of a connection.
 * @const
 */
Blockly.OPPOSITE_TYPE = [];
Blockly.OPPOSITE_TYPE[Blockly.INPUT_VALUE] = Blockly.OUTPUT_VALUE;
Blockly.OPPOSITE_TYPE[Blockly.OUTPUT_VALUE] = Blockly.INPUT_VALUE;
Blockly.OPPOSITE_TYPE[Blockly.NEXT_STATEMENT] = Blockly.PREVIOUS_STATEMENT;
Blockly.OPPOSITE_TYPE[Blockly.PREVIOUS_STATEMENT] = Blockly.NEXT_STATEMENT;

/**
 * ENUM for toolbox and flyout at top of screen.
 * @const
 */
Blockly.TOOLBOX_AT_TOP = 0;

/**
 * ENUM for toolbox and flyout at bottom of screen.
 * @const
 */
Blockly.TOOLBOX_AT_BOTTOM = 1;

/**
 * ENUM for toolbox and flyout at left of screen.
 * @const
 */
Blockly.TOOLBOX_AT_LEFT = 2;

/**
 * ENUM for toolbox and flyout at right of screen.
 * @const
 */
Blockly.TOOLBOX_AT_RIGHT = 3;

/**
 * ENUM representing that an event is not in any delete areas.
 * Null for backwards compatibility reasons.
 * @const
 */
Blockly.DELETE_AREA_NONE = null;

/**
 * ENUM representing that an event is in the delete area of the trash can.
 * @const
 */
Blockly.DELETE_AREA_TRASH = 1;

/**
 * ENUM representing that an event is in the delete area of the toolbox or
 * flyout.
 * @const
 */
Blockly.DELETE_AREA_TOOLBOX = 2;

/**
 * String for use in the "custom" attribute of a category in toolbox xml.
 * This string indicates that the category should be dynamically populated with
 * variable blocks.
 * @const {string}
 */
Blockly.VARIABLE_CATEGORY_NAME = 'VARIABLE';

/**
 * String for use in the "custom" attribute of a category in toolbox xml.
 * This string indicates that the category should be dynamically populated with
 * procedure blocks.
 * @const {string}
 */
Blockly.PROCEDURE_CATEGORY_NAME = 'PROCEDURE';

/**
 * String for use in the dropdown created in field_variable.
 * This string indicates that this option in the dropdown is 'Rename
 * variable...' and if selected, should trigger the prompt to rename a variable.
 * @const {string}
 */
Blockly.RENAME_VARIABLE_ID = 'RENAME_VARIABLE_ID';

/**
 * String for use in the dropdown created in field_variable.
 * This string indicates that this option in the dropdown is 'Delete the "%1"
 * variable' and if selected, should trigger the prompt to delete a variable.
 * @const {string}
 */
Blockly.DELETE_VARIABLE_ID = 'DELETE_VARIABLE_ID';


text:
layout: post
date: '2016-03-11'
title: "Long Bari Jay 914 Strapless Chiffon Bridesmaid Dress"
category: Long
tags: [Long]
---
### Long Bari Jay 914 Strapless Chiffon Bridesmaid Dress
Just **$215.99**
###

Buy it: [https://www.eudances.com/en/long/1933-bari-jay-914-strapless-chiffon-bridesmaid-dress.html](https://www.eudances.com/en/long/1933-bari-jay-914-strapless-chiffon-bridesmaid-dress.html)


text:
import os
from collections import defaultdict
import random
from pylab import *
import sys
from munkres import Munkres
import numpy

# Compute the loss for one user (i.e., one set of circles for one ego-network)
# usersPerCircle: list of sets of users (groundtruth). Order doesn't matter.
# usersPerCircleP: list of sets of users (predicted). Order doesn't matter.
def loss1(usersPerCircle, usersPerCircleP):
  #psize: either the number of groundtruth, or the number of predicted circles (whichever is larger)
  psize = max(len(usersPerCircle),len(usersPerCircleP)) # Pad the matrix to be square
  # mm: matching matrix containing costs of matching groundtruth circles to predicted circles.
  #     mm[i][j] = cost of matching groundtruth circle i to predicted circle j
  mm = numpy.zeros((psize,psize))
  # mm2: copy of mm since the Munkres library destroys the data during computation
  mm2 = numpy.zeros((psize,psize))
  for i in range(psize):
    for j in range(psize):
      circleP = set() # Match to an empty circle (delete all users)
      circle = set() # Match to an empty circle (add all users)
      if (i < len(usersPerCircleP)):
        circleP = usersPerCircleP[i]
      if (j < len(usersPerCircle)):
        circle = usersPerCircle[j]
      nedits = len(circle.union(circleP)) - len(circle.intersection(circleP)) # Compute the edit distance between the two circles
      mm[i][j] = nedits
      mm2[i][j] = nedits

  if psize == 0:
    return 0 # Edge case in case there are no circles
  else:
    m = Munkres()
    #print mm2 # Print the pairwise cost matrix
    indices = m.compute(mm) # Compute the optimal alignment between predicted and groundtruth circles
    editCost = 0
    for row, column in indices:
      #print row,column # Print the optimal value selected by matching
      editCost += mm2[row][column]
    return int(editCost)

if len(sys.argv) != 3:
  print "Expected two arguments (ground-truth and prediction filenames)"
  sys.exit(0)

groundtruthFile = sys.argv[1] # Ground-truth
predictionFile = sys.argv[2] # Prediction

gf = open(groundtruthFile, 'r') # Read the ground-truth
pf = open(predictionFile, 'r') # Read the predictions

# Should just be header
gf.readline()
pf.readline()

gLines = gf.readlines()
pLines = pf.readlines()

gf.close()
pf.close()

if len(gLines) != len(pLines):
  print "Ground-truth and prediction files should have the same number of lines"
  sys.exit(0)

circlesG = {}
circlesP = {}
for gl, pl in zip(gLines, pLines):
  uidG,friendsG = gl.split(',')
  uidP,friendsP = pl.split(',')
  circlesG[int(uidG)] = [set([int(x) for x in c.split()]) for c in friendsG.split(';')]
  circlesP[int(uidP)] = [set([int(x) for x in c.split()]) for c in friendsP.split(';')]

totalLoss = 0
for k in circlesP.keys():
  if not circlesG.has_key(k):
    print "Ground-truth has prediction for circle", k, "but prediction does not"
    sys.exit(0)
  l = loss1(circlesG[k], circlesP[k])
  print "loss for user", k, "=", l
  totalLoss += l

print "total loss for all users =", totalLoss


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

namespace SolutionInspector.Api.Extensions
{
  /// <summary>
  ///   Extension methods for <see cref="IEnumerable{T}" />.
  /// </summary>
  public static class EnumerableExtensions
  {
    /// <summary>
    ///   Checks if the given <paramref name="enumerable" /> contains more than one elements.
    /// </summary>
    public static bool ContainsMoreThanOne<T> (this IEnumerable<T> enumerable)
    {
      return enumerable.ContainsMoreThan(1);
    }

    /// <summary>
    ///   Checks if the given <paramref name="enumerable" /> contains more than <paramref name="count" /> elements.
    /// </summary>
    private static bool ContainsMoreThan<T> (this IEnumerable<T> enumerable, int count)
    {
      return enumerable.Skip(count).Any();
    }
  }
}


text:
class Projects::PagesController < Projects::ApplicationController
  layout 'project_settings'

  before_action :require_pages_enabled!
  before_action :authorize_read_pages!, only: [:show]
  before_action :authorize_update_pages!, except: [:show]

  def show
    @domains = @project.pages_domains.order(:domain)
  end

  def destroy
    project.remove_pages
    project.pages_domains.destroy_all

    respond_to do |format|
      format.html  do
        redirect_to(namespace_project_pages_path(@project.namespace, @project),
                    notice: 'Pages were removed')
      end
    end
  end
end