text:
.. _device-tree:

Device Tree
###########

Introduction
************

Device tree is a way of describing hardware and configuration information
for boards.  Device tree was adopted for use in the Linux kernel for the
PowerPC architecture.  However, it is now in use for ARM and other
architectures.

The device tree is a data structure for dynamically describing hardware
using a Device Tree Source (DTS) data structure language, and compiled
into a compact Device Tree Blob (DTB) using a Device Tree Compiler (DTC).
Rather than hard coding every detail of a board's hardware into the
operating system, the hardware-describing DTB is passed to the operating
system at boot time. This allows the same compiled Linux kernel to support
different hardware configurations within an architecture family (e.g., ARM,
x86, PowerPC) and moves a significant part of the hardware description out of
the kernel binary itself.

Traditional usage of device tree involves storing of the Device Tree Blob.
The DTB is then used during runtime for configuration of device drivers.  In
Zephyr, the DTS information will be used only during compile time.
Information about the system is extracted from the compiled DTS and used to
create the application image.

Device tree uses a specific format to describe the device nodes in a system.
This format is described in the `Device Tree Specification`_.

.. _Device Tree Specification: https://github.com/devicetree-org/devicetree-specification/releases

More device tree information can be found at the `device tree repository`_.

.. _device tree repository: https://git.kernel.org/pub/scm/utils/dtc/dtc.git

System build requirements
*************************

The Zephyr device tree feature requires a device tree compiler (DTC) and Python
YAML packages.  Refer to the installation guide for your specific host OS:

* :ref:`installing_zephyr_win`
* :ref:`installation_linux`
* :ref:`installing_zephyr_mac`

Zephyr and Device Tree
**********************

In Zephyr, device tree is used to not only describe hardware, but also to
describe Zephyr-specific configuration information.  The Zephyr-specific
information is intended to augment the device tree descriptions.  The main
reason for this is to leverage existing device tree files that a SoC vendor may
already have defined for a given platform.

Device Tree provides a unified description of a hardware system used in an
application. It is used in Zephyr to describe hardware and provide a boot-time
configuration of this hardware.

The device tree files are compiled using the device tree compiler.  The compiler
runs the .dts file through the C preprocessor to resolve any macro or #defines
utilized in the file.  The output of the compile is another dts formatted file.

After compilation, a python script extracts information from the compiled device
tree file using a set of rules specified in YAML files.  The extracted
information is placed in a header file that is used by the rest of the code as
the project is compiled.

A temporary fixup file is required for device tree support on most devices.
This fixup file by default resides in the board directory and is named
dts_fixup.h.  This fixup file maps the generated include information to the
current driver/source usage.

.. _dt_vs_kconfig:

Device Tree vs Kconfig
**********************

As mentioned above there are several tools used to configure the build with
Zephyr.
The two main ones, Device Tree and Kconfig, might seem to overlap in purpose,
but in fact they do not. This section serves as a reference to help you decide
whether to place configuration items in Device Tree or Kconfig.

The scope of each configuration tool can be summarized as follows:

* Device Tree is used to describe the **hardware** and its **boot-time
  configuration**.
* Kconfig is used to describe which **software features** will be built into
  the final image, and their **configuration**.

Hence Device Tree deals mostly with hardware and Kconfig with software.
A couple of noteworthy exceptions are:

* Device Tree's ``chosen`` keyword, which allows the user to select a
  particular instance of a hardware device to be used for a concrete purpose
  by the software. An example of this is selecting a particular UART for use as
  the system's console.
* Device Tree's ``status`` keyword, which allows the user to enable or disable
  a particular instance of a hardware device in the Device Tree file itself.
  This takes precedence over Kconfig.

To further clarify this separation, let's use a particular, well-known
example to illustrate this: serial ports a.k.a. UARTs. Let's consider a
board containing a SoC with 2 UART instances:

* The fact that the target hardware **contains** 2 UARTs is described with Device
  Tree. This includes the UART type, its driver compatibility and certain
  immutable (i.e. not software-configurable) settings such as the base address
  of the hardware peripheral in memory or its interrupt line.
* Additionally, **hardware boot-time configuration** is also described with Device
  Tree. This includes things such as the IRQ priority and boot-time UART
  baudrate. These may also be modifiable at runtime later, but their boot-time
  default configuration is described in Device Tree.
* The fact that the user intends to include **software support** for UART in the
  build is described in Kconfig. Through the use of Kconfig, users can opt not
  to include support for this particular hardware item if they don't require it.

Another example is a device with a 2.4GHz, multi-protocol radio supporting
both the Bluetooth Low Energy and 802.15.4 wireless technologies. In this case:

* Device Tree describes the presence of a radio peripheral compatible with a
  certain radio driver.
* Additional hardware boot-time configuration settings may also be present
  in the Device Tree files. In this particular case it could be a
  default TX power in dBm if the hardware does have a simple, cross-wireless
  technology register for that.
* Kconfig will describe which **protocol stack** is to be used with that radio.
  The user may decide to select BLE or 802.15.4, which will both depend on
  the presence of a compatible radio in the Device Tree files.

Device tree file formats
************************

Hardware and software is described inside of device tree files in clear text format.
These files have the file suffix of .dtsi or .dts.  The .dtsi files are meant to
be included by other files.  Typically for a given board you have some number of
.dtsi include files that pull in common device descriptions that are used across
a given SoC family.

Example: FRDM K64F Board and Hexiwear K64
=========================================

Both of these boards are based on the same NXP Kinetis SoC family, the K6X.  The
following shows the include hierarchy for both boards.

boards/arm/frdm_k64f/frdm_k64f.dts includes the following files::

  dts/arm/nxp/nxp_k6x.dtsi
  dts/arm/armv7-m.dtsi

boards/arm/hexiwear_k64/hexiwear_k64.dts includes the same files::

  dts/arm/nxp/nxp_k6x.dtsi
  dts/arm/armv7-m.dtsi

The board-specific .dts files enable nodes, define the Zephyr-specific items,
and also adds board-specific changes like gpio/pinmux assignments.  These types
of things will vary based on the board layout and application use.

Currently supported boards
**************************

Device tree is currently supported on all ARM targets.  Support for all other
architectures is to be completed by release 1.11.

Adding support for a board
**************************

Adding device tree support for a given board requires adding a number of files.
These files will contain the DTS information that describes a platform, the
YAML descriptions that define the contents of a given Device Tree peripheral
node, and also any fixup files required to support the platform.

When writing Device Tree Source files, it is good to separate out common
peripheral information that could be used across multiple SoC families or
boards.  DTS files are identified by their file suffix.  A .dtsi suffix denotes
a DTS file that is used as an include in another DTS file.  A .dts suffix
denotes the primary DTS file for a given board.

The primary DTS file will contain at a minimum a version line, optional
includes, and the root node definition.  The root node will contain a model and
compatible that denotes the unique board described by the .dts file.

Device Tree Source File Template
================================

.. code-block:: yaml

  /dts-v1/
  / {
          model = "Model name for your board";
          compatible = "compatible for your board";
          /* rest of file */
  };

One suggestion for starting from scratch on a platform/board is to examine other
boards and their device tree source files.

The following is a more precise list of required files:

* Base architecture support

  * Add architecture-specific DTS directory, if not already present.
    Example: dts/arm for ARM.
  * Add target specific device tree files for base SoC.  These should be
    .dtsi files to be included in the board-specific device tree files.
  * Add target specific YAML files in the dts/bindings/ directory.
    Create the yaml directory if not present.

* SoC family support

  * Add one or more SoC family .dtsi files that describe the hardware
    for a set of devices.  The file should contain all the relevant
    nodes and base configuration that would be applicable to all boards
    utilizing that SoC family.
  * Add SoC family YAML files that describe the nodes present in the .dtsi file.

* Board specific support

  * Add a board level .dts file that includes the SoC family .dtsi files
    and enables the nodes required for that specific board.
  * Board .dts file should specify the SRAM and FLASH devices, if present.

    * Flash device node might specify flash partitions. For more details see
      :ref:`flash_partitions`

  * Add board-specific YAML files, if required.  This would occur if the
    board has additional hardware that is not covered by the SoC family
    .dtsi/.yaml files.

* Fixup files

  * Fixup files contain mappings from existing Kconfig options to the actual
    underlying DTS derived configuration #defines.  Fixup files are temporary
    artifacts until additional DTS changes are made to make them unnecessary.

* Overlay Files (optional)

  * Overlay files contain tweaks or changes to the SoC and Board support files
    described above. They can be used to modify Device Tree configurations
    without having to change the SoC and Board files. See
    :ref:`application_dt` for more information on overlay files and the Zephyr
    build system.

.. _dt-alias-chosen:

``aliases`` and ``chosen`` nodes
================================

Using an alias with a common name for a particular node makes it easier for you
to write board-independent source code. Device Tree ``aliases`` nodes  are used
for this purpose, by mapping certain generic, commonly used names to specific
hardware resources:

.. code-block:: yaml

   aliases {
      led0 = &led0;
      sw0 = &button0;
      sw1 = &button1;
      uart-0 = &uart0;
      uart-1 = &uart1;
   };

Certain software subsystems require a specific hardware resource to bind to in
order to function properly. Some of those subsystems are used with many
different boards, which makes using the Device Tree ``chosen`` nodes very
convenient. By doing, so the software subsystem can rely on having the specific
hardware peripheral assigned to it. In the following example we bind the shell
to ``uart1`` in this board:

.. code-block:: yaml

   chosen {
      zephyr,shell-uart = &uart1;
   };

The full set of Zephyr-specific ``chosen`` nodes follows:

.. list-table::
   :header-rows: 1

   * - ``chosen`` node name
     - Generated symbol

   * - ``zephyr,flash``
     - ``CONFIG_FLASH``
   * - ``zephyr,sram``
     - ``CONFIG_SRAM``
   * - ``zephyr,ccm``
     - ``CONFIG_CCM``
   * - ``zephyr,console``
     - :option:`CONFIG_UART_CONSOLE_ON_DEV_NAME`
   * - ``zephyr,shell-uart``
     - :option:`CONFIG_UART_SHELL_ON_DEV_NAME`
   * - ``zephyr,bt-uart``
     - :option:`CONFIG_BT_UART_ON_DEV_NAME`
   * - ``zephyr,uart-pipe``
     - :option:`CONFIG_UART_PIPE_ON_DEV_NAME`
   * - ``zephyr,bt-mon-uart``
     - :option:`CONFIG_BT_MONITOR_ON_DEV_NAME`
   * - ``zephyr,uart-mcumgr``
     - :option:`CONFIG_UART_MCUMGR_ON_DEV_NAME`

As chosen properties tend to be related to software configuration, it can be
useful for the build system to know if a chosen property was defined. We
generate a define for each chosen property, for example:

``zephyr,flash`` will generate: ``#define DT_CHOSEN_ZEPHYR_FLASH 1``

Adding support for device tree in drivers
*****************************************

As drivers and other source code is converted over to make use of device tree
generated information, these drivers may require changes to match the generated
#define information.

Source Tree Hierarchy
*********************

The device tree files are located in a couple of different directories.  The
directory split is done based on architecture, and there is also a common
directory where architecture agnostic device tree and yaml files are located.

Assuming the current working directory is the ZEPHYR_BASE, the directory
hierarchy looks like the following::

  dts/common/
  dts/<ARCH>/
  dts/bindings/
  boards/<ARCH>/<BOARD>/

The common directories contain a skeleton.dtsi include file that defines the
address and size cells.  The yaml subdirectory contains common yaml files for
Zephyr-specific nodes/properties and generic device properties common across
architectures.

Example: Subset of DTS/YAML files for NXP FRDM K64F (Subject to Change)::

  dts/arm/armv7-m.dtsi
  dts/arm/k6x/nxp_k6x.dtsi
  boards/arm/frdm_k64f/frdm_k64f.dts
  dts/bindings/interrupt-controller/arm,v7m-nvic.yaml
  dts/bindings/gpio/nxp,kinetis-gpio.yaml
  dts/bindings/pinctrl/nxp,kinetis-pinmux.yaml
  dts/bindings/serial/nxp,kinetis-uart.yaml

YAML definitions for device nodes
*********************************

Device tree can describe hardware and configuration, but it doesn't tell the
system which pieces of information are useful, or how to generate configuration
data from the device tree nodes.  For this, we rely on YAML files to describe
the contents or definition of a device tree node.

A YAML description must be provided for every device node that is to be a source
of information for the system.  This YAML description can be used for more than
one purpose.  It can be used in conjunction with the device tree to generate
include information.  It can also be used to validate the device tree files
themselves.  A device tree file can successfully compile and still not contain
the necessary pieces required to build the rest of the software.  YAML provides
a means to detect that issue.

YAML files reside in a subdirectory inside the common and architecture-specific
device tree directories.  A YAML template file is provided to show the required
format.  This file is located at::

  dts/bindings/device_node.yaml.template

YAML files must end in a .yaml suffix.  YAML files are scanned during the
information extraction phase and are matched to device tree nodes via the
compatible property.

redpajama_set_name: RedPajamaGithub


text:
"""
Django settings for ImpaQto project.

Generated by 'django-admin startproject' using Django 1.8.4.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from django.conf.global_settings import LOGIN_URL, LOGOUT_URL, MEDIA_ROOT,\
    MEDIA_URL, AUTH_USER_MODEL
#BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '5#je0k%9@6dgz2r9ul)pwdo&)-=+ke4^4+$nvar%*w%c^8ha8j'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG =False

ALLOWED_HOSTS = ['localhost']

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'coworkersimpaqto',
    'accounts',
    'api',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'ImpaQto.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
                 os.path.join(BASE_DIR,'coworkersimpaqto/templates').replace('\\','/'),
                 os.path.join(BASE_DIR,'accounts/templates').replace('\\','/')
                 ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.core.context_processors.request',
                "django.core.context_processors.media",
                "django.core.context_processors.static",
            ],
        },
    },
]

WSGI_APPLICATION = 'ImpaQto.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'impaqto_2',
        'USER': 'postgres',
        'PASSWORD': 'vime2014',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'es'

TIME_ZONE = 'America/Guayaquil'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_ROOT = "/opt/ImpaQto/static/"
STATIC_URL = '/static/'
STATICFILES_DIRS = (
                    os.path.join(BASE_DIR,'static').replace('\\','/'),
)
#STATICFILES_DIRS = ('/opt/ImpaQto/static/',)
LOGIN_URL = '/accounts/login/'
LOGOUT_URL = '/accounts/logout/'

MEDIA_ROOT = os.path.join(BASE_DIR, '../../media').replace('\\','/')
MEDIA_URL = '/media/'
SESSION_EXPIRE_AT_BROWSER_CLOSE = True

'''
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',),

}'''


text:
package eu.coldrye.settings.examples.simple.pojos;

/**
 *
 *
 */
public enum EAudioBitDepth {

  AUDIO_BIT_DEPTH_16BIT,
  AUDIO_BIT_DEPTH_24BIT;
}


text:
<?php

class Google_Service_Analytics_GoalVisitTimeOnSiteDetails extends Google_Model
{
  public $comparisonType;
  public $comparisonValue;

  public function setComparisonType($comparisonType)
  {
    $this->comparisonType = $comparisonType;
  }
  public function getComparisonType()
  {
    return $this->comparisonType;
  }
  public function setComparisonValue($comparisonValue)
  {
    $this->comparisonValue = $comparisonValue;
  }
  public function getComparisonValue()
  {
    return $this->comparisonValue;
  }
}


text:
package org.apache.flink.graph.generator;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.functions.FunctionAnnotation.ForwardedFields;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.graph.Edge;
import org.apache.flink.graph.Graph;
import org.apache.flink.graph.Vertex;
import org.apache.flink.types.LongValue;
import org.apache.flink.types.NullValue;
import org.apache.flink.util.Collector;
import org.apache.flink.util.LongValueSequenceIterator;
import org.apache.flink.util.Preconditions;

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

/**
 * @see Grid Graph at Wolfram MathWorld
 */
public class GridGraph
extends AbstractGraphGenerator<LongValue, NullValue, NullValue> {

	// Required to create the DataSource
	private final ExecutionEnvironment env;

	// Required configuration
	private List<Tuple2<Long, Boolean>> dimensions = new ArrayList<>();

	private long vertexCount = 1;

	/**
	 * An undirected {@code Graph} connecting vertices in a regular tiling in
	 * one or more dimensions and where the endpoints are optionally connected.
	 *
	 * @param env the Flink execution environment
	 */
	public GridGraph(ExecutionEnvironment env) {
		this.env = env;
	}

	/**
	 * Required configuration for each dimension of the graph.
	 *
	 * @param size number of vertices; dimensions of size 1 are prohibited due to having no effect
	 *             on the generated graph
	 * @param wrapEndpoints whether to connect first and last vertices; this has no effect on
	 *                      dimensions of size 2
	 * @return this
	 */
	public GridGraph addDimension(long size, boolean wrapEndpoints) {
		Preconditions.checkArgument(size >= 2, "Dimension size must be at least 2");

		vertexCount *= size;

		// prevent duplicate edges
		if (size == 2) {
			wrapEndpoints = false;
		}

		dimensions.add(new Tuple2<>(size, wrapEndpoints));

		return this;
	}

	@Override
	public Graph<LongValue, NullValue, NullValue> generate() {
		Preconditions.checkState(!dimensions.isEmpty(), "No dimensions added to GridGraph");

		// Vertices
		DataSet<Vertex<LongValue, NullValue>> vertices = GraphGeneratorUtils.vertexSequence(env, parallelism, vertexCount);

		// Edges
		LongValueSequenceIterator iterator = new LongValueSequenceIterator(0, this.vertexCount - 1);

		DataSet<Edge<LongValue, NullValue>> edges = env
			.fromParallelCollection(iterator, LongValue.class)
				.setParallelism(parallelism)
				.name("Edge iterators")
			.flatMap(new LinkVertexToNeighbors(vertexCount, dimensions))
				.setParallelism(parallelism)
				.name("Grid graph edges");

		// Graph
		return Graph.fromDataSet(vertices, edges, env);
	}

	@ForwardedFields("*->f0")
	private static class LinkVertexToNeighbors
	implements FlatMapFunction<LongValue, Edge<LongValue, NullValue>> {

		private long vertexCount;

		private List<Tuple2<Long, Boolean>> dimensions;

		private LongValue target = new LongValue();

		private Edge<LongValue, NullValue> edge = new Edge<>(null, target, NullValue.getInstance());

		public LinkVertexToNeighbors(long vertexCount, List<Tuple2<Long, Boolean>> dimensions) {
			this.vertexCount = vertexCount;
			this.dimensions = dimensions;
		}

		@Override
		public void flatMap(LongValue source, Collector<Edge<LongValue, NullValue>> out)
				throws Exception {
			edge.f0 = source;
			long val = source.getValue();

			// the distance between neighbors in a given iteration
			long increment = vertexCount;

			// the value in the remaining dimensions
			long remainder = val;

			for (Tuple2<Long, Boolean> dimension : dimensions) {
				increment /= dimension.f0;

				// the index within this dimension
				long index = remainder / increment;

				if (index > 0) {
					target.setValue(val - increment);
					out.collect(edge);
				} else if (dimension.f1) {
					target.setValue(val + increment * (dimension.f0 - 1));
					out.collect(edge);
				}

				if (index < dimension.f0 - 1) {
					target.setValue(val + increment);
					out.collect(edge);
				} else if (dimension.f1) {
					target.setValue(val - increment * (dimension.f0 - 1));
					out.collect(edge);
				}

				remainder %= increment;
			}
		}
	}
}


text:
from pupa.scrape import Organization, Membership, Person
from .base import OpenstatesBaseScraper

birthdays = {
    'ALL000035': '1965-03-20',
    'ALL000138': '0000',
}

class OpenstatesPersonScraper(OpenstatesBaseScraper):

    _committees = {}
    _people = {}
    _roles = set()

    def get_term_years(self, term_name=None):
        if term_name is None:
            return self.metadata['terms'][-1]['start_year'], self.metadata['terms'][-1]['end_year']
        for term in self.metadata['terms']:
            if term['name'] == term_name:
                return term['start_year'], term['end_year']

    def process_role(self, new, role, leg_id, skip_member=False):
        if self.state == 'la' and len(role['term']) == 4:
            role['term'] = '2008-2011'

        start, end = self.get_term_years(role['term'])
        com_id = role.get('committee_id', None)
        if role['type'] == 'committee member':
            if com_id:
                self._roles.add((leg_id, com_id, role.get('position', 'member'), start, end))
        elif role['type'] == 'chair':
            if com_id:
                self._roles.add((leg_id, com_id, 'chair', start, end))
        elif role['type'] == 'member':
            if not skip_member:
                # add party & district for this old role
                district = role['district'].strip('(').strip(')').strip().replace('\u200b', '').lstrip('0')
                district = district.replace(' And ', ' and ')
                if district.endswith(' -'):
                    district = district[:-2]
                if district == 'Second Essex, Consiting Of Boxford: Precincts 2, 3; Georgetown; Groveland; Haverhill: Ward 4: Precinct 3, Ward 7: Precinct 3; Merrimac; Newbury; West Newbury':
                    district = 'Second Essex'
                if district == 'Seventeenth Essex, Consistng Of Andover: Precincts 2, 3, 4; Lawrence: Ward C, Precincts 1, 2, 3, Ward D, Ward E, Precinct 1; Methuen: Precinct 2':
                    district = 'Seventeenth Essex'

                if role['chamber'] == 'upper' and self.state == 'pr':
                    pr_district = {
                        '1': 'I',
                        '2': 'II',
                        '3': 'III',
                        '4': 'IV',
                        '5': 'V',
                        '6': 'VI',
                        '7': 'VII',
                        '8': 'VIII',
                    }
                    if district in pr_district:
                        district = pr_district[district]

                if 'Replication or Save Conflict' in district:
                    return

                mem_type = self.metadata["chambers"][role["chamber"]]["title"]

                if self.state in('ne', 'dc'):
                    role['chamber'] = 'legislature'

                new.add_term(role=mem_type,
                                org_classification=role['chamber'],
                                district=district,
                                start_date=str(start),
                                end_date=str(end))
        elif role['type'] == 'Lt. Governor':
            pass # handle this!
        elif role['type'] in ('Senate President', 'Minority Whip', 'Majority Whip',
                              'Majority Floor Leader', 'Speaker Pro Tem', 'Majority Caucus Chair',
                              'Minority Caucus Chair', 'Minority Floor Leader', 'Speaker of the House',
                              'President Pro Tem',
                             ):
            new.add_term(role=role['type'],
                            org_classification=role['chamber'],
                            start_date=str(start),
                            end_date=str(end),
                            label=role['type'])
        elif role['type'] == 'substitute':
            pass
        else:
            raise Exception("unknown role type: " + role['type'])

    def scrape_legislator(self, legislator_id):
        old = self.api('legislators/' + legislator_id + '?')
        # just not needed
        id = old.pop('id')

        old.pop('created_at')
        old.pop('updated_at')
        old.pop('country', None)
        old.pop('level', None)
        old.pop('state')
        old.pop('leg_id')
        old.pop('active')
        # junk keys
        old.pop('suffix', None)
        old.pop('notice', None)
        old.pop('csrfmiddlewaretoken', None)
        old.pop('office_address', None)
        old.pop('office_phone', None)

        # translated
        district = old.pop('district', None)
        chamber = old.pop('chamber', None)
        image = old.pop('photo_url', '')
        name = old.pop('full_name')
        party = old.pop('party', None)

        if party in ('Nonpartisan', 'unknown', 'Unknown', 'Unaffiliated', "Non Affiliated", " "):
            party = None
        elif party == 'Democrat':
            party = 'Democratic'

        if self.state in('ne', 'dc'):
            chamber = 'legislature'

        if chamber == 'upper' and self.state == 'pr':
            pr_district = {
                '1': 'I',
                '2': 'II',
                '3': 'III',
                '4': 'IV',
                '5': 'V',
                '6': 'VI',
                '7': 'VII',
                '8': 'VIII',
            }
            if district in pr_district:
                district = pr_district[district]

        if '2008-2011' in old:
            old['old_roles']['2008-2011'] = old.pop('2008-2011')

        old_roles = old.pop('old_roles', {})

        if old['roles'] and 'Lt. Governor' in [x['type'] for x in old['roles']]:
            new = Person(name=name, district=district, party=party, image=image)
            self.jurisdiction._executive.add_post(
                'Lt. Governor',
                'lt-gov'
            )
            membership = Membership(
                person_id=new._id,
                role="Lt. Governor",
                organization_id=self.jurisdiction._executive._id
            )
            new._related.append(membership)
        else:
            new = Person(name=name, party=party, image=image)

        if id in birthdays:
            new.birth_date = birthdays[id]

        # various ids
        id_types = {'votesmart_id': 'votesmart',
                    'transparencydata_id': 'influence-explorer',
                    'nimsp_id': 'nimsp',
                    'nimsp_candidate_id': 'nimsp-candidate',
                   }
        for idname, scheme in id_types.items():
            val = old.pop(idname, None)
            if val:
                new.add_identifier(val, scheme=scheme)
        for id in old.pop('all_ids'):
            new.add_identifier(id, scheme='openstates')
            self._people[id] = new

        # contact details
        email = old.pop('email', None)
        if email:
            new.add_contact_detail(type='email', value=email, note='')
        office_keys = {'fax': 'fax',
                       'phone': 'voice',
                       'email': 'email',
                       'address': 'address'}
        for office in old.pop('offices'):
            for key, type in office_keys.items():
                if office.get(key):
                    if 'Office Hours' in office[key] and self.state == 'pa':
                        for x in office[key].split('Office Hours: '):
                            if x:
                                new.add_contact_detail(type=type, value=x, note=office['name'])
                    else:
                        new.add_contact_detail(type=type, value=office[key], note=office['name'])

        # links
        link = old.pop('url', None)
        if link:
            new.add_link(link)

        #for utah, conflict of interest is in links
        if self.state == 'ut':
            links = old.pop('+links',[])
            for l in links:
                new.add_link(note="conflict of interest form",url=l)

        # sources
        for source in old.pop('sources'):
            source.pop('retrieved', None)
            source.pop('+page', None)
            new.add_source(**source)

        # roles
        for role in old.pop('roles'):
            self.process_role(new, role, leg_id=id)

        for role_list in old_roles.values():
            for role in role_list:
                self.process_role(new, role, leg_id=id)

        # ignore most of the names for now
        old.pop('first_name')
        old.pop('middle_name')
        old.pop('suffixes')
        old.pop('nickname', None)
        new.sort_name = old.pop('last_name')

        #some places have legacy names without underscores
        old.pop('+firstname', None)
        old.pop('+lastname', None)

        gender = old.pop('+gender', None)
        if gender:
            new.gender = gender
        biography = old.pop('+biography', None)
        if biography:
            new.biography = biography
        birth_date = old.pop('+birth_date', None)
        if birth_date:
            new.birth_date = birth_date

        # keys to keep
        to_extras = ['+occupation', '+twitter', '+facebook_url', '+sworn_in_date', '+profession',
                     '+secretary', '+office_hours', '+resident_county', '+district_name',
                     '+leg_status', '+legal_position', '+title', '+start_year',
                     '+end_date', 'occupation', '+oregon_member_id',
                     '+facebook', '+youtube', '+instagram']
        for k in to_extras:
            v = old.pop(k, None)
            if v:
                new.extras[k.replace('+', '')] = v

        # keys not to keep
        to_pop = ['+office_fax', '+phone', '+room', '+fax', '+email', '+url', '+photo', '+notice',
                  '+page', '+suffix', '+city', '+address', '+additional_info_url', '+contact_form',
                  '+fax_number', '+phone_number', '+business_phone', '+email_address', '+img_url',
                  '+office_phone', '+disctict_name', '+office_loc', '+leg_url', '+office',
                  '+district_address', '+capital_address', '+bis_phone', '+capital_phone',
                  '+org_info', '+role', '+other_phone', '+home_phone', '+zip', '+zipcode',
                  '+county', '+capitol_phone', '+image_url', '+header', '+town_represented',
                  '+full_address', '+capitol_address', '+website', '+district_phone',
                  '+district_offices', '+party', '+district', '+capitol_office', '+office_address',
                 ]
        for k in to_pop:
            old.pop(k, None)

        # ensure we got it all
        assert not old, old.keys()

        return new

    def scrape_committee(self, committee_id):
        old = self.api('committees/' + committee_id + '?')
        id = old.pop('id')
        old.pop('created_at')
        old.pop('updated_at')
        old.pop('country', None)
        old.pop('level', None)
        old.pop('state')
        old.pop('votesmart_id', None)
        old.pop('+short_name', None)
        old.pop('+session', None)
        old.pop('+az_committee_id', None)

        com = old.pop('committee')
        sub = old.pop('subcommittee')
        parent_id = old.pop('parent_id')
        chamber = old.pop('chamber')
        if chamber == 'joint':
            chamber = ''
        if self.state in('ne', 'dc'):
            chamber = 'legislature'

        if sub:
            if parent_id:
                parent = self._committees[parent_id]._id
                new = Organization(sub, parent_id=parent, classification='committee')
            else:
                new = Organization(com + ': ' + sub, chamber=chamber, classification='committee')
        else:
            new = Organization(com, chamber=chamber, classification='committee')
            assert parent_id is None

        # all_ids
        for id in old.pop('all_ids'):
            new.add_identifier(id, scheme='openstates')
            self._committees[id] = new

        # sources
        for source in old.pop('sources'):
            new.add_source(**source)

        # members
        start, end = self.get_term_years()
        for role in old.pop('members'):
            # leg_id, com_id, role, start, end
            if role['leg_id']:
                self._roles.add((role['leg_id'], id, role['role'], start, end))

        to_extras = ['+twitter', '+description', '+code', '+secretary', '+office_hours',
                     '+office_phone', '+meetings_info', '+status', '+aide', '+contact_info',
                     '+comm_type', 'comm_type', 'aide', 'contact_info', '+town_represented',
                     '+action_code',
                    ]
        for k in to_extras:
            v = old.pop(k, None)
            if v:
                new.extras[k.replace('+', '')] = v

        assert not old, old.keys()

        return new

    def scrape(self):
        method = 'metadata/{}?'.format(self.state)
        self.metadata = self.api(method)

        method = 'legislators/?state={}&fields=id&active=False'.format(self.state)
        for result in self.api(method):
            if result['id'] not in ('NJL000013',):
                yield self.scrape_legislator(result['id'])

        method = 'committees/?state={}&fields=id,parent_id'.format(self.state)
        results = sorted(self.api(method), key=lambda x: x.get('parent_id', '') or '')
        for result in results:
            yield self.scrape_committee(result['id'])

        for leg_id, com_id, role, start, end in self._roles:

            # resolve OpenStates committee id to JSON ids
            if com_id in self._committees:
                com_id = self._committees[com_id]._id
            else:
                continue

            if leg_id == 'NJL000013':
                leg_id = 'NJL000015'
            yield Membership(person_id=self._people[leg_id]._id, organization_id=com_id,
                             role=role, label=role, start_date=str(start), end_date=str(end))


text:
#import "MDCButton.h"

#import "MDFTextAccessibility.h"
#import "MaterialInk.h"
#import "MaterialMath.h"
#import "MaterialShadowElevations.h"
#import "MaterialShadowLayer.h"
#import "MaterialTypography.h"
#import "private/MDCButton+Subclassing.h"

// TODO(ajsecord): Animate title color when animating between enabled/disabled states.
// Non-trivial: http://corecocoa.wordpress.com/2011/10/04/animatable-text-color-of-uilabel/

static NSString *const MDCButtonEnabledBackgroundColorKey = @"MDCButtonEnabledBackgroundColorKey";
static NSString *const MDCButtonDisabledBackgroundColorLightKey =
    @"MDCButtonDisabledBackgroundColorLightKey";
static NSString *const MDCButtonDisabledBackgroundColorDarkKey =
    @"MDCButtonDisabledBackgroundColorDarkKey";
static NSString *const MDCButtonInkViewInkStyleKey = @"MDCButtonInkViewInkStyleKey";
static NSString *const MDCButtonInkViewInkColorKey = @"MDCButtonInkViewInkColorKey";
static NSString *const MDCButtonInkViewInkMaxRippleRadiusKey =
    @"MDCButtonInkViewInkMaxRippleRadiusKey";
static NSString *const MDCButtonShouldRaiseOnTouchKey = @"MDCButtonShouldRaiseOnTouchKey";
// Previous value kept for backwards compatibility.
static NSString *const MDCButtonUppercaseTitleKey = @"MDCButtonShouldCapitalizeTitleKey";
// Previous value kept for backwards compatibility.
static NSString *const MDCButtonUnderlyingColorHintKey = @"MDCButtonUnderlyingColorKey";
static NSString *const MDCButtonDisableAlphaKey = @"MDCButtonDisableAlphaKey";
static NSString *const MDCButtonCustomTitleColorKey = @"MDCButtonCustomTitleColorKey";
static NSString *const MDCButtonAreaInsetKey = @"MDCButtonAreaInsetKey";

static NSString *const MDCButtonUserElevationsKey = @"MDCButtonUserElevationsKey";
static NSString *const MDCButtonBackgroundColorsKey = @"MDCButtonBackgroundColorsKey";
static NSString *const MDCButtonAccessibilityLabelsKey = @"MDCButtonAccessibilityLabelsKey";

static const NSTimeInterval MDCButtonAnimationDuration = 0.2;

// https://material.io/guidelines/components/buttons.html#buttons-main-buttons
static const CGFloat MDCButtonDisabledAlpha = 0.1f;

// Blue 500 from https://material.io/guidelines/style/color.html#color-color-palette .
static const uint32_t MDCButtonDefaultBackgroundColor = 0x2196F3;

// Creates a UIColor from a 24-bit RGB color encoded as an integer.
static inline UIColor *MDCColorFromRGB(uint32_t rgbValue) {
  return [UIColor colorWithRed:((CGFloat)((rgbValue & 0xFF0000) >> 16)) / 255
                         green:((CGFloat)((rgbValue & 0x00FF00) >> 8)) / 255
                          blue:((CGFloat)((rgbValue & 0x0000FF) >> 0)) / 255
                         alpha:1];
}

static NSAttributedString *uppercaseAttributedString(NSAttributedString *string) {
  // Store the attributes.
  NSMutableArray<NSDictionary *> *attributes = [NSMutableArray array];
  [string enumerateAttributesInRange:NSMakeRange(0, [string length])
                             options:0
                          usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
                            [attributes addObject:@{
                              @"attrs" : attrs,
                              @"range" : [NSValue valueWithRange:range]
                            }];
                          }];

  // Make the string uppercase.
  NSString *uppercaseString = [[string string] uppercaseStringWithLocale:[NSLocale currentLocale]];

  // Apply the text and attributes to a mutable copy of the title attributed string.
  NSMutableAttributedString *mutableString = [string mutableCopy];
  [mutableString replaceCharactersInRange:NSMakeRange(0, [string length])
                               withString:uppercaseString];
  for (NSDictionary *attribute in attributes) {
    [mutableString setAttributes:attribute[@"attrs"] range:[attribute[@"range"] rangeValue]];
  }

  return [mutableString copy];
}

@interface MDCButton () {
  NSMutableDictionary<NSNumber *, NSNumber *> *_userElevations;   // For each UIControlState.
  NSMutableDictionary<NSNumber *, UIColor *> *_backgroundColors;  // For each UIControlState.

  // Cached accessibility settings.
  NSMutableDictionary<NSNumber *, NSString *> *_accessibilityLabelForState;
  NSString *_accessibilityLabelExplicitValue;

  BOOL _mdc_adjustsFontForContentSizeCategory;
}
@property(nonatomic, strong) MDCInkView *inkView;
@end

@implementation MDCButton

+ (Class)layerClass {
  return [MDCShadowLayer class];
}

- (instancetype)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
    [self commonMDCButtonInit];
  }
  return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
  self = [super initWithCoder:aDecoder];
  if (self) {
    [self commonMDCButtonInit];

    // TODO(randallli): Add backward compatibility to background colors
    //    if ([aDecoder containsValueForKey:MDCButtonEnabledBackgroundColorKey]) {
    //      self.enabledBackgroundColor =
    //          [aDecoder decodeObjectForKey:MDCButtonEnabledBackgroundColorKey];
    //    }
    //    if ([aDecoder containsValueForKey:MDCButtonDisabledBackgroundColorLightKey]) {
    //      self.disabledBackgroundColorLight =
    //          [aDecoder decodeObjectForKey:MDCButtonDisabledBackgroundColorLightKey];
    //    }
    //    if ([aDecoder containsValueForKey:MDCButtonDisabledBackgroundColorDarkKey]) {
    //      self.disabledBackgroundColorDark =
    //          [aDecoder decodeObjectForKey:MDCButtonDisabledBackgroundColorDarkKey];
    //    }
    if ([aDecoder containsValueForKey:MDCButtonInkViewInkStyleKey]) {
      self.inkView.inkStyle = [aDecoder decodeIntegerForKey:MDCButtonInkViewInkStyleKey];
    }

    if ([aDecoder containsValueForKey:MDCButtonInkViewInkColorKey]) {
      self.inkView.inkColor = [aDecoder decodeObjectForKey:MDCButtonInkViewInkColorKey];
    }

    if ([aDecoder containsValueForKey:MDCButtonInkViewInkMaxRippleRadiusKey]) {
      self.inkView.maxRippleRadius =
          (CGFloat)[aDecoder decodeDoubleForKey:MDCButtonInkViewInkMaxRippleRadiusKey];
    }

    if ([aDecoder containsValueForKey:MDCButtonShouldRaiseOnTouchKey]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
      self.shouldRaiseOnTouch = [aDecoder decodeBoolForKey:MDCButtonShouldRaiseOnTouchKey];
#pragma clang diagnostic pop
    }

    if ([aDecoder containsValueForKey:MDCButtonUppercaseTitleKey]) {
      self.uppercaseTitle = [aDecoder decodeBoolForKey:MDCButtonUppercaseTitleKey];
    }

    if ([aDecoder containsValueForKey:MDCButtonUnderlyingColorHintKey]) {
      self.underlyingColorHint = [aDecoder decodeObjectForKey:MDCButtonUnderlyingColorHintKey];
    }

    if ([aDecoder containsValueForKey:MDCButtonCustomTitleColorKey]) {
      self.customTitleColor = [aDecoder decodeObjectForKey:MDCButtonCustomTitleColorKey];
    }

    if ([aDecoder containsValueForKey:MDCButtonDisableAlphaKey]) {
      self.disabledAlpha = (CGFloat)[aDecoder decodeDoubleForKey:MDCButtonDisableAlphaKey];
    }

    if ([aDecoder containsValueForKey:MDCButtonAreaInsetKey]) {
      self.hitAreaInsets = [aDecoder decodeUIEdgeInsetsForKey:MDCButtonAreaInsetKey];
    }

    if ([aDecoder containsValueForKey:MDCButtonUserElevationsKey]) {
      _userElevations = [aDecoder decodeObjectForKey:MDCButtonUserElevationsKey];
    }

    if ([aDecoder containsValueForKey:MDCButtonBackgroundColorsKey]) {
      _backgroundColors = [aDecoder decodeObjectForKey:MDCButtonBackgroundColorsKey];
    }

    if ([aDecoder containsValueForKey:MDCButtonAccessibilityLabelsKey]) {
      _accessibilityLabelForState = [aDecoder decodeObjectForKey:MDCButtonAccessibilityLabelsKey];
    }
  }
  return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
  [super encodeWithCoder:aCoder];

  [aCoder encodeInteger:_inkView.inkStyle forKey:MDCButtonInkViewInkStyleKey];
  if (_inkView.inkColor) {
    [aCoder encodeObject:_inkView.inkColor forKey:MDCButtonInkViewInkColorKey];
  }

  [aCoder encodeDouble:_inkView.maxRippleRadius forKey:MDCButtonInkViewInkMaxRippleRadiusKey];
  [aCoder encodeBool:_shouldRaiseOnTouch forKey:MDCButtonShouldRaiseOnTouchKey];
  [aCoder encodeBool:_uppercaseTitle forKey:MDCButtonUppercaseTitleKey];
  if (_underlyingColorHint) {
    [aCoder encodeObject:_underlyingColorHint forKey:MDCButtonUnderlyingColorHintKey];
  }
  [aCoder encodeDouble:self.disabledAlpha forKey:MDCButtonDisableAlphaKey];
  if (self.customTitleColor) {
    [aCoder encodeObject:self.customTitleColor forKey:MDCButtonCustomTitleColorKey];
  }
  [aCoder encodeUIEdgeInsets:self.hitAreaInsets forKey:MDCButtonAreaInsetKey];
  [aCoder encodeObject:_userElevations forKey:MDCButtonUserElevationsKey];
  [aCoder encodeObject:_backgroundColors forKey:MDCButtonBackgroundColorsKey];
  [aCoder encodeObject:_accessibilityLabelForState forKey:MDCButtonAccessibilityLabelsKey];
}

- (void)commonMDCButtonInit {
  _disabledAlpha = MDCButtonDisabledAlpha;
  _shouldRaiseOnTouch = YES;
  _uppercaseTitle = YES;
  _userElevations = [NSMutableDictionary dictionary];
  _backgroundColors = [NSMutableDictionary dictionary];
  _accessibilityLabelForState = [NSMutableDictionary dictionary];

  // Disable default highlight state.
  self.adjustsImageWhenHighlighted = NO;
  self.showsTouchWhenHighlighted = NO;

  // Set up title label attributes.
  self.titleLabel.font = [MDCTypography buttonFont];
  [self updateAlphaAndBackgroundColorAnimated:NO];

  // Default content insets
  self.contentEdgeInsets = [self defaultContentEdgeInsets];

  MDCShadowLayer *shadowLayer = [self shadowLayer];
  shadowLayer.shadowPath = [self boundingPath].CGPath;
  shadowLayer.shadowColor = [UIColor blackColor].CGColor;
  shadowLayer.elevation = [self elevationForState:self.state];

  // Set up ink layer.
  _inkView = [[MDCInkView alloc] initWithFrame:self.bounds];
  [self insertSubview:_inkView belowSubview:self.imageView];

  // UIButton has a drag enter/exit boundary that is outside of the frame of the button itself.
  // Because this is not exposed externally, we can't use -touchesMoved: to calculate when to
  // change ink state. So instead we fall back on adding target/actions for these specific events.
  [self addTarget:self
                action:@selector(touchDragEnter:forEvent:)
      forControlEvents:UIControlEventTouchDragEnter];
  [self addTarget:self
                action:@selector(touchDragExit:forEvent:)
      forControlEvents:UIControlEventTouchDragExit];

  // Block users from activating multiple buttons simultaneously by default.
  self.exclusiveTouch = YES;

  // Default background colors.
  [self setBackgroundColor:MDCColorFromRGB(MDCButtonDefaultBackgroundColor)
                  forState:UIControlStateNormal];

  self.inkColor = [UIColor colorWithWhite:1 alpha:0.2f];

  // Uppercase all titles
  if (_uppercaseTitle) {
    [self uppercaseAllTitles];
  }
}

- (void)dealloc {
  [self removeTarget:self action:NULL forControlEvents:UIControlEventAllEvents];

  [[NSNotificationCenter defaultCenter] removeObserver:self
                                                  name:UIContentSizeCategoryDidChangeNotification
                                                object:nil];
}

- (void)setCustomTitleColor:(UIColor *)customTitleColor {
  _customTitleColor = customTitleColor;
  [self updateTitleColor];
}

- (void)setUnderlyingColorHint:(UIColor *)underlyingColorHint {
  _underlyingColorHint = underlyingColorHint;
  [self updateAlphaAndBackgroundColorAnimated:NO];
}

- (void)setDisabledAlpha:(CGFloat)disabledAlpha {
  _disabledAlpha = disabledAlpha;
  [self updateAlphaAndBackgroundColorAnimated:NO];
}

#pragma mark - UIView

- (void)layoutSubviews {
  [super layoutSubviews];
  self.layer.shadowPath = [self boundingPath].CGPath;
  self.layer.cornerRadius = [self cornerRadius];

  // Center the ink view frame taking into account possible insets using contentRectForBounds.

  CGRect contentRect = [self contentRectForBounds:self.bounds];
  CGPoint contentCenterPoint = CGPointMake(CGRectGetMidX(contentRect), CGRectGetMidY(contentRect));
  CGPoint boundsCenterPoint = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));

  CGFloat offsetX = contentCenterPoint.x - boundsCenterPoint.x;
  CGFloat offsetY = contentCenterPoint.y - boundsCenterPoint.y;
  _inkView.frame = CGRectMake(offsetX, offsetY, self.bounds.size.width, self.bounds.size.height);
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
  return CGRectContainsPoint(UIEdgeInsetsInsetRect(self.bounds, _hitAreaInsets), point);
}

#pragma mark - UIResponder

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  [super touchesBegan:touches withEvent:event];

  [self handleBeginTouches:touches];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  [super touchesMoved:touches withEvent:event];

  // Drag events handled by -touchDragExit:forEvent: and -touchDragEnter:forEvent:
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  [super touchesEnded:touches withEvent:event];

  CGPoint location = [self locationFromTouches:touches];
  [_inkView startTouchEndedAnimationAtPoint:location completion:nil];

  BOOL inside = CGRectContainsPoint(self.bounds, location);
  if (inside && _shouldRaiseOnTouch) {
    [self animateButtonToHeightForState:UIControlStateNormal];
  }
}

// Note - in some cases, event may be nil (e.g. view removed from window).
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
  [super touchesCancelled:touches withEvent:event];

  [self evaporateInkToPoint:[self locationFromTouches:touches]];
}

#pragma mark - UIButton methods

- (void)setEnabled:(BOOL)enabled {
  [self setEnabled:enabled animated:NO];
}

- (void)setEnabled:(BOOL)enabled animated:(BOOL)animated {
  [super setEnabled:enabled];
  [self updateAlphaAndBackgroundColorAnimated:animated];
}

#pragma mark - Title Uppercasing

- (void)setUppercaseTitle:(BOOL)uppercaseTitle {
  _uppercaseTitle = uppercaseTitle;
  if (_uppercaseTitle) {
    [self uppercaseAllTitles];
  }
}

- (void)uppercaseAllTitles {
  // This ensures existing titles will get uppercased.
  UIControlState allControlStates = UIControlStateNormal | UIControlStateHighlighted |
                                    UIControlStateDisabled | UIControlStateSelected;
  for (UIControlState state = 0; state <= allControlStates; ++state) {
    NSString *title = [self titleForState:state];
    if (title) {
      [self setTitle:[title uppercaseStringWithLocale:[NSLocale currentLocale]] forState:state];
    }

    NSAttributedString *attributedTitle = [self attributedTitleForState:state];
    if (attributedTitle) {
      [self setAttributedTitle:uppercaseAttributedString(attributedTitle) forState:state];
    }
  }
}

- (void)setTitle:(NSString *)title forState:(UIControlState)state {
  // Intercept any setting of the title and store a copy in case the accessibilityLabel
  // is requested and the original non-uppercased version needs to be returned.
  if ([title length]) {
    _accessibilityLabelForState[@(state)] = [title copy];
  } else {
    [_accessibilityLabelForState removeObjectForKey:@(state)];
  }

  if (_uppercaseTitle) {
    title = [title uppercaseStringWithLocale:[NSLocale currentLocale]];
  }
  [super setTitle:title forState:state];
}

- (void)setAttributedTitle:(NSAttributedString *)title forState:(UIControlState)state {
  // Intercept any setting of the title and store a copy in case the accessibilityLabel
  // is requested and the original non-uppercased version needs to be returned.
  if ([title length]) {
    _accessibilityLabelForState[@(state)] = [[title string] copy];
  } else {
    [_accessibilityLabelForState removeObjectForKey:@(state)];
  }

  if (_uppercaseTitle) {
    title = uppercaseAttributedString(title);
  }
  [super setAttributedTitle:title forState:state];
}

#pragma mark - Accessibility

- (void)setAccessibilityLabel:(NSString *)accessibilityLabel {
  // Intercept any explicit setting of the accessibilityLabel so it can be returned
  // later before the accessibiilityLabel is inferred from the setTitle:forState:
  // argument values.
  _accessibilityLabelExplicitValue = [accessibilityLabel copy];
  [super setAccessibilityLabel:accessibilityLabel];
}

- (NSString *)accessibilityLabel {
  if (!_uppercaseTitle) {
    return [super accessibilityLabel];
  }

  NSString *label = _accessibilityLabelExplicitValue;
  if ([label length]) {
    return label;
  }

  label = _accessibilityLabelForState[@(self.state)];
  if ([label length]) {
    return label;
  }

  label = _accessibilityLabelForState[@(UIControlStateNormal)];
  if ([label length]) {
    return label;
  }

  label = [super accessibilityLabel];
  if ([label length]) {
    return label;
  }

  return nil;
}

- (UIAccessibilityTraits)accessibilityTraits {
  return [super accessibilityTraits] | UIAccessibilityTraitButton;
}

#pragma mark - Ink

- (MDCInkStyle)inkStyle {
  return _inkView.inkStyle;
}

- (void)setInkStyle:(MDCInkStyle)inkStyle {
  _inkView.inkStyle = inkStyle;
}

- (UIColor *)inkColor {
  return _inkView.inkColor;
}

- (void)setInkColor:(UIColor *)inkColor {
  _inkView.inkColor = inkColor;
}

- (CGFloat)inkMaxRippleRadius {
  return _inkView.maxRippleRadius;
}

- (void)setInkMaxRippleRadius:(CGFloat)inkMaxRippleRadius {
  _inkView.maxRippleRadius = inkMaxRippleRadius;
}

#pragma mark - Shadows

- (MDCShadowLayer *)shadowLayer {
  return (MDCShadowLayer *)self.layer;
}

- (void)animateButtonToHeightForState:(UIControlState)state {
  [CATransaction begin];
  [CATransaction setAnimationDuration:MDCButtonAnimationDuration];
  [self shadowLayer].elevation = [self elevationForState:state];
  [CATransaction commit];
}

#pragma mark - BackgroundColor

- (UIColor *)backgroundColorForState:(UIControlState)state {
  return _backgroundColors[@(state)];
}

- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
  _backgroundColors[@(state)] = backgroundColor;
  [self updateAlphaAndBackgroundColorAnimated:NO];
}

#pragma mark - Elevations

- (CGFloat)elevationForState:(UIControlState)state {
  NSNumber *elevation = _userElevations[@(state)];
  return elevation ? (CGFloat)[elevation doubleValue] : [self defaultElevationForState:state];
}

- (void)setElevation:(CGFloat)elevation forState:(UIControlState)state {
  _userElevations[@(state)] = @(elevation);
  [self shadowLayer].elevation = [self elevationForState:self.state];

  // The elevation of the normal state controls whether this button is flat or not, and flat buttons
  // have different background color requirements than raised buttons.
  // TODO(ajsecord): Move to MDCFlatButton and update this comment.
  if (state == UIControlStateNormal) {
    [self updateAlphaAndBackgroundColorAnimated:NO];
  }
}

- (void)resetElevationForState:(UIControlState)state {
  [_userElevations removeObjectForKey:@(state)];
  [self shadowLayer].elevation = [self elevationForState:self.state];
}

#pragma mark - Private methods

- (UIColor *)currentBackgroundColor {
  UIColor *color = _backgroundColors[@(self.state)];
  if (color) {
    return color;
  }
  return [self backgroundColorForState:UIControlStateNormal];
}

/**
 The background color that a user would see for this button. If self.backgroundColor is not
 transparent, then returns that. Otherwise, returns self.underlyingColorHint.
 @note If self.underlyingColorHint is not set, then this method will return nil.
 */
- (UIColor *)effectiveBackgroundColor {
  if (![self isTransparentColor:self.currentBackgroundColor]) {
    return self.currentBackgroundColor;
  } else {
    return self.underlyingColorHint;
  }
}

/** Returns YES if the color is not transparent and is a "dark" color. */
- (BOOL)isDarkColor:(UIColor *)color {
  // TODO: have a components/private/ColorCalculations/MDCColorCalculations.h|m
  //  return ![self isTransparentColor:color] && [QTMColorGroup luminanceOfColor:color] < 0.5f;
  return ![self isTransparentColor:color];
}

/** Returns YES if the color is transparent (including a nil color). */
- (BOOL)isTransparentColor:(UIColor *)color {
  return !color || [color isEqual:[UIColor clearColor]] || CGColorGetAlpha(color.CGColor) == 0.0f;
}

- (void)touchDragEnter:(MDCButton *)button forEvent:(UIEvent *)event {
  [self handleBeginTouches:event.allTouches];
}

- (void)touchDragExit:(MDCButton *)button forEvent:(UIEvent *)event {
  CGPoint location = [self locationFromTouches:event.allTouches];
  [self evaporateInkToPoint:location];
}

- (void)handleBeginTouches:(NSSet *)touches {
  [_inkView startTouchBeganAnimationAtPoint:[self locationFromTouches:touches] completion:nil];
  if (_shouldRaiseOnTouch) {
    [self animateButtonToHeightForState:UIControlStateSelected];
  }
}

- (CGPoint)locationFromTouches:(NSSet *)touches {
  UITouch *touch = [touches anyObject];
  return [touch locationInView:self];
}

- (void)evaporateInkToPoint:(CGPoint)toPoint {
  [_inkView startTouchEndedAnimationAtPoint:toPoint completion:nil];
  if (_shouldRaiseOnTouch) {
    [self animateButtonToHeightForState:UIControlStateNormal];
  }
}

- (UIBezierPath *)boundingPath {
  return [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:[self cornerRadius]];
}

- (CGFloat)cornerRadius {
  return 2.0f;
}

- (UIEdgeInsets)defaultContentEdgeInsets {
  return UIEdgeInsetsMake(8, 16, 8, 16);
}

- (CGFloat)defaultElevationForState:(UIControlState)state {
  if (state == UIControlStateNormal) {
    return 0;
  }

  if ((state & UIControlStateSelected) == UIControlStateSelected) {
    CGFloat normalElevation = [self elevationForState:UIControlStateNormal];
    return normalElevation > 0 ? 2 * normalElevation : 1;
  }

  return [self elevationForState:UIControlStateNormal];
}

- (BOOL)shouldHaveOpaqueBackground {
  BOOL isFlatButton = MDCCGFloatIsExactlyZero([self elevationForState:UIControlStateNormal]);
  return !isFlatButton;
}

- (void)updateAlphaAndBackgroundColorAnimated:(BOOL)animated {
  void (^animations)() = ^{
    self.alpha = self.enabled ? 1.0f : _disabledAlpha;
    [self updateBackgroundColor];
  };

  if (animated) {
    [UIView animateWithDuration:MDCButtonAnimationDuration animations:animations];
  } else {
    animations();
  }
}

- (void)updateBackgroundColor {
  //  UIColor *color = nil;
  //  if ([self shouldHaveOpaqueBackground]) {
  //    if (self.enabled) {
  ////      color = self.enabledBackgroundColor;
  //    } else {
  //      color = [self isDarkColor:_underlyingColorHint] ? _disabledBackgroundColorLight
  //                                                  : _disabledBackgroundColorDark;
  //    }
  //  }
  [self updateTitleColor];
  [self updateDisabledTitleColor];
  super.backgroundColor = self.currentBackgroundColor;
}

- (void)updateDisabledTitleColor {
  // Disabled buttons have very low opacity, so we full-opacity text color here to make the text
  // readable. Also, even for non-flat buttons with opaque backgrounds, the correct background color
  // to examine is the underlying color, since disabled buttons are so transparent.
  BOOL darkBackground = [self isDarkColor:[self underlyingColorHint]];
  [self setTitleColor:darkBackground ? [UIColor whiteColor] : [UIColor blackColor]
             forState:UIControlStateDisabled];
}

- (void)updateTitleColor {
  if (_customTitleColor) {
    [self setTitleColor:_customTitleColor forState:UIControlStateNormal];
    return;
  }

  if (![self isTransparentColor:[self effectiveBackgroundColor]]) {
    MDFTextAccessibilityOptions options = 0;
    if ([MDFTextAccessibility isLargeForContrastRatios:self.titleLabel.font]) {
      options = MDFTextAccessibilityOptionsLargeFont;
    }
    UIColor *color =
        [MDFTextAccessibility textColorOnBackgroundColor:[self effectiveBackgroundColor]
                                         targetTextAlpha:[MDCTypography buttonFontOpacity]
                                                 options:options];
    [self setTitleColor:color forState:UIControlStateNormal];
  }
}

- (BOOL)mdc_adjustsFontForContentSizeCategory {
  return _mdc_adjustsFontForContentSizeCategory;
}

- (void)mdc_setAdjustsFontForContentSizeCategory:(BOOL)adjusts {
  _mdc_adjustsFontForContentSizeCategory = adjusts;
  if (_mdc_adjustsFontForContentSizeCategory) {
    UIFont *font = [UIFont mdc_preferredFontForMaterialTextStyle:MDCFontTextStyleButton];
    self.titleLabel.font = font;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(contentSizeCategoryDidChange:)
                                                 name:UIContentSizeCategoryDidChangeNotification
                                               object:nil];
  } else {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIContentSizeCategoryDidChangeNotification
                                                  object:nil];
  }
}

- (void)contentSizeCategoryDidChange:(NSNotification *)notification {
  UIFont *font = [UIFont mdc_preferredFontForMaterialTextStyle:MDCFontTextStyleButton];
  self.titleLabel.font = font;
  [self sizeToFit];
}

#pragma mark - Deprecations

- (BOOL)shouldCapitalizeTitle {
  return [self isUppercaseTitle];
}

- (void)setShouldCapitalizeTitle:(BOOL)shouldCapitalizeTitle {
  [self setUppercaseTitle:shouldCapitalizeTitle];
}

- (UIColor *)underlyingColor {
  return [self underlyingColorHint];
}

- (void)setUnderlyingColor:(UIColor *)underlyingColor {
  [self setUnderlyingColorHint:underlyingColor];
}

@end


text:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.msf.msf.Fragments.Events.EventInfoFragment">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="10dip" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal" >

            <Button android:id="@+id/delBtn"
                android:text="Delete"
                android:background="#ff6347"
                android:textColor="#fff"
                android:textSize="15dp"
                android:layout_height="wrap_content"
                android:layout_width="120dp"
                android:clickable="true"
                android:layout_marginLeft="20dp"/>

            <Button android:id="@+id/editButton"
                android:text="Edit"
                android:layout_width="100dp"
                android:layout_height="wrap_content"
                android:background="#ff6347"
                android:textColor="#fff"
                android:textSize="15dp"
                android:clickable="true"
                android:layout_marginLeft="50dp"/>

        </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Event Title"
        android:id="@+id/textView4"
        android:textStyle="bold"
        android:textSize="20dp"
        android:paddingTop="10dp"
        android:paddingBottom="10dp" />

    <TextView
        android:text=""
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/eventTitleTV" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Date"
        android:id="@+id/textView5"
        android:textStyle="bold"
        android:textSize="20dp"
        android:paddingTop="10dp"
        android:paddingBottom="10dp" />

    <TextView
        android:text=""
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/eventDateTV" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start time"
        android:id="@+id/textView11"
        android:textStyle="bold"
        android:textSize="20dp"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"/>

    <TextView
        android:text=""
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/eventStartTV" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="End time"
        android:id="@+id/textView12"
        android:textStyle="bold"
        android:textSize="20dp"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"/>

    <TextView
        android:text=""
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/eventEndTV" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Description"
        android:id="@+id/textView13"
        android:textStyle="bold"
        android:textSize="20dp"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"/>

    <TextView
        android:text=""
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/eventDescriptionTV" />

</LinearLayout>

</ScrollView>


text:
DIRNAME=`dirname $0`

java -cp ${DIRNAME}/ApacheJMeter.jar org.apache.jmeter.util.ShutdownClient Shutdown "$@"


text:
/**
 * Utility classes providing and augmenting support for {@link java.security.KeyStore KeyStore} management.
 */
package org.wildfly.security.keystore;


text:
var MSG = {
  title: "Webduino Blockly Editor",
  gotoTutorials: "Go to Tutorials",
  blocks: "Blocks",
  linkTooltip: "Save and link to blocks.",
  runTooltip: "Run the program defined by the blocks in the workspace.",
  badCode: "Program error:\n%1",
  timeout: "Maximum execution iterations exceeded.",
  discard: "Delete all %1 blocks?",
  trashTooltip: "Discard all blocks.",
  catLogic: "Logic",
  catLoops: "Loops",
  catMath: "Math",
  catText: "Text",
  catLists: "Lists",
  catColour: "Colour",
  catVariables: "Variables",
  catFunctions: "Functions",
  catExec: "Execute",
  catBoard: "Board",
  catLed: "Led",
  catRelay: "Relay",
  catRGBLed: "RGBLed",
  catUltraSonic: "Ultra Sonic",
  catDht: "DHT",
  catButton: "Button",
  catShock: "Shock",
  catPir: "PIR Detect",
  catSound: "Sound Detect",
  catBuzzer: "Buzzer",
  catServo: "Servo",
  listVariable: "list",
  textVariable: "text",
  httpRequestError: "There was a problem with the request.",
  linkAlert: "Share your blocks with this link:\n\n%1",
  hashError: "Sorry, '%1' doesn't correspond with any saved program.",
  xmlError: "Could not load your saved file. Perhaps it was created with a different version of Blockly?",
  badXml: "Error parsing XML:\n%1\n\nSelect 'OK' to abandon your changes or 'Cancel' to further edit the XML.",
  catConsole: "Console",
  backIndex: "Webduino Blockly Tutorials",
  demoTitle: "Blockly Demo Area",
  catTutorials: "Blockly",
  linkToBin: "Let's Coding",
  catDatabase: "Data base - Firebase",
  update: "update 2015.8.11",
  catCarTest: "Demo - Car (2)",
  catCar: "Demo - Car (1)",
  catFish: "Demo - Fly Fish",
};


text:
import factory
import mock
import requests

class ResponseF(factory.Factory):
    FACTORY_FOR = requests.Response

    status_code = 200
    headers = {}
    url = 'http://example.com/'
    content = 'Example content'

    @classmethod
    def _prepare(cls, create, **kwargs):
        r = requests.Response()
        kwargs['_content'] = kwargs.pop('content')
        r.raw = mock.Mock()
        for attr, value in kwargs.iteritems():
            setattr(r, attr, value)
        return r


text:
const path = require('path')
const assert = require('assert')
const fs = require('fs-extra')

const test = require('../../lib/test')

const Test = test.Test()

const sourcePath = './GetSet.sol'

const source = fs.readFileSync(path.join(__dirname, sourcePath)).toString()
const {abi, bytecode} = test.compile(source, ':GetSet')

const testUint = 42
const testBytes = 'DEADBEEF00000000000000000000000000000000000000000000000000000000'
const testString = 'Hello World!'
const testBool = true

let TestContract

// Create a factory for the contract with the JSON interface 'myAbi'.

describe('Setting and Getting Values:', function () {
  this.timeout(10 * 1000)

  before(Test.before((burrow) => {
    return burrow.contracts.deploy(abi, bytecode).then((contract) => {
      TestContract = contract
    })
  }))
  after(Test.after())

  it('Uint', Test.it(function (burrow) {
    return new Promise((resolve, reject) => {
      TestContract.setUint(testUint, function (err) {
        if (err) { reject(err) }

        TestContract.getUint(function (err, output) {
          if (err) { reject(err) }

          assert.equal(output[0], testUint)
          resolve()
        })
      })
    })
  }))

  it('Bool', Test.it(function (burrow) {
    return new Promise((resolve, reject) => {
      TestContract.setBool(testBool, function (err) {
        if (err) { reject(err) }

        TestContract.getBool(function (err, output) {
          if (err) { reject(err) }

          assert.equal(output[0], testBool)
          resolve()
        })
      })
    })
  }))

  it('Bytes', Test.it(function (burrow) {
    return new Promise((resolve, reject) => {
      TestContract.setBytes(testBytes, function (err) {
        if (err) { reject(err) }

        TestContract.getBytes(function (err, output) {
          if (err) { reject(err) }

          assert.equal(output[0], testBytes)
          resolve()
        })
      })
    })
  }))

  it('String', Test.it(function (burrow) {
    return new Promise((resolve, reject) => {
      TestContract.setString(testString, function (err) {
        if (err) { reject(err) }

        TestContract.getString(function (err, output) {
          if (err) { reject(err) }

          assert.equal(output[0], testString)
          resolve()
        })
      })
    })
  }))
})


text:
class PrefService;

namespace base {
class DictionaryValue;
}  // namespace base

namespace user_prefs {
class PrefRegistrySyncable;
}  // namespace user_prefs

namespace proximity_auth {

// Implementation of ProximityAuthPrefManager for a logged in session with a
// user profile.
class ProximityAuthProfilePrefManager
    : public ProximityAuthPrefManager,
      public chromeos::multidevice_setup::MultiDeviceSetupClient::Observer {
 public:
  // Creates a pref manager backed by preferences registered in
  // |pref_service| (persistent across browser restarts). |pref_service| should
  // have been registered using RegisterPrefs(). Not owned, must out live this
  // instance.
  ProximityAuthProfilePrefManager(
      PrefService* pref_service,
      chromeos::multidevice_setup::MultiDeviceSetupClient*
          multidevice_setup_client);

  ProximityAuthProfilePrefManager(const ProximityAuthProfilePrefManager&) =
      delete;
  ProximityAuthProfilePrefManager& operator=(
      const ProximityAuthProfilePrefManager&) = delete;

  ~ProximityAuthProfilePrefManager() override;

  // Initializes the manager to listen to pref changes and sync prefs to the
  // user's local state.
  void StartSyncingToLocalState(PrefService* local_state,
                                const AccountId& account_id);

  // Registers the prefs used by this class to the given |pref_service|.
  static void RegisterPrefs(user_prefs::PrefRegistrySyncable* registry);

  // ProximityAuthPrefManager:
  bool IsEasyUnlockAllowed() const override;
  void SetIsEasyUnlockEnabled(bool is_easy_unlock_enabled) const override;
  bool IsEasyUnlockEnabled() const override;
  void SetEasyUnlockEnabledStateSet() const override;
  bool IsEasyUnlockEnabledStateSet() const override;
  bool IsSmartLockEligible() const override;
  void SetLastPromotionCheckTimestampMs(int64_t timestamp_ms) override;
  int64_t GetLastPromotionCheckTimestampMs() const override;
  void SetPromotionShownCount(int count) override;
  int GetPromotionShownCount() const override;
  bool IsChromeOSLoginAllowed() const override;
  void SetIsChromeOSLoginEnabled(bool is_enabled) override;
  bool IsChromeOSLoginEnabled() const override;
  void SetHasShownLoginDisabledMessage(bool has_shown) override;
  bool HasShownLoginDisabledMessage() const override;

  // chromeos::multidevice_setup::MultiDeviceSetupClient::Observer:
  void OnFeatureStatesChanged(
      const chromeos::multidevice_setup::MultiDeviceSetupClient::
          FeatureStatesMap& feature_states_map) override;

 private:
  const base::DictionaryValue* GetRemoteBleDevices() const;

  void SyncPrefsToLocalState();

  // Contains perferences that outlive the lifetime of this object and across
  // process restarts. Not owned and must outlive this instance.
  PrefService* pref_service_ = nullptr;

  // Listens to pref changes so they can be synced to the local state.
  PrefChangeRegistrar registrar_;

  // The local state to which to sync the profile prefs.
  PrefService* local_state_ = nullptr;

  // The account id of the current profile.
  AccountId account_id_;

  // Used to determine the FeatureState of Smart Lock.
  chromeos::multidevice_setup::MultiDeviceSetupClient*
      multidevice_setup_client_ = nullptr;

  base::WeakPtrFactory<ProximityAuthProfilePrefManager> weak_ptr_factory_{this};
};

}  // namespace proximity_auth

#endif  // ASH_COMPONENTS_PROXIMITY_AUTH_PROXIMITY_AUTH_PROFILE_PREF_MANAGER_H_


text:
using System.Web;
using System.Web.Optimization;

namespace Lucas.Solutions
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            //
            // Require JS modules
            bundles.Add(new ScriptBundle("~/require.js").Include(
                        "~/Scripts/require.js"));

            // Require JS main for My Account
            bundles.Add(new ScriptBundle("~/account.js").Include(
                        "~/Scripts/account.js"));

            // Require JS main for Dashboard
            bundles.Add(new ScriptBundle("~/dashboard.js").Include(
                        "~/Scripts/dashboard.js"));

            // Require JS main for My Status
            bundles.Add(new ScriptBundle("~/status.js").Include(
                        "~/Scripts/status.js"));

            //
            // Vendors
            bundles.Add(new ScriptBundle("~/scripts/jquery").Include(
                        "~/Scripts/jquery-{version}.js",
                        "~/Scripts/jquery.event.drag.js",
                        "~/Scripts/jquery.event.drag.live.js",
                        "~/Scripts/q.js"));

            bundles.Add(new ScriptBundle("~/scripts/slick-grid").Include(
                        "~/Scripts/slick.core.js",
                        "~/Scripts/slick.grid.js",
                        "~/Scripts/slick.dataview.js",
                        "~/Scripts/slick.formatters.js",
                        "~/Scripts/slick.editor.js",
                        "~/Scripts/slick.remotemodel.js",
                        "~/Scripts/slick.groupitemmetadataprovider.js",
                        "~/Scripts/controls/slick.columnpicker.js",
                        "~/Scripts/controls/slick.pager.js",
                        "~/Scripts/plugins/slick.autotooltips.js",
                        "~/Scripts/plugins/slick.cellcopymanager.js",
                        "~/Scripts/plugins/slick.cellrangedecorator.js",
                        "~/Scripts/plugins/slick.cellrangeselector.js",
                        "~/Scripts/plugins/slick.cellselectionmodel.js",
                        "~/Scripts/plugins/slick.checkboxselectcolumn.js",
                        "~/Scripts/plugins/slick.headermenu.js",
                        "~/Scripts/plugins/slick.rowselectionmanager.js",
                        "~/Scripts/plugins/slick.rowselectionmodel.js"));

            bundles.Add(new ScriptBundle("~/scripts/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/scripts/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/scripts/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new ScriptBundle("~/scripts/knockout").Include(
                      "~/Scripts/knockout-{version}.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css",
                      "~/Styles/grid.css"));

            bundles.Add(new StyleBundle("~/styles/slick-grid").Include(
                      "~/Styles/slick.grid.css",
                      "~/Styles/slick.pager.css",
                      "~/Styles/slick.columnpicker.css",
                      "~/Styles/slick.headerbuttons.css",
                      "~/Styles/slick.headermenu.css",
                      "~/Styles/slick-default-theme.css"));

            // Set EnableOptimizations to false for debugging. For more information,
            // visit http://go.microsoft.com/fwlink/?LinkId=301862
            BundleTable.EnableOptimizations = true;
        }
    }
}


text:
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'test');

defined('YII_APP_BASE_PATH') or define('YII_APP_BASE_PATH', dirname(dirname(__DIR__)));

require_once YII_APP_BASE_PATH . '/vendor/autoload.php';
require_once YII_APP_BASE_PATH . '/vendor/yiisoft/yii2/Yii.php';

 Yii::setAlias('@web', '/');

require YII_APP_BASE_PATH . '/common/config/aliases.php';
Yii::setAlias('@tests', dirname(__DIR__));


text:
from unittest.case import TestCase

from refunite_drc_admin import DrcReverseGeoCoder

class TestDrcReverseGeoCoder(TestCase):

    def test_get_territories(self):
        drc_reverse_geocoder = DrcReverseGeoCoder()
        territories = drc_reverse_geocoder.get_territories(29.1811337, -1.6587838)

        self.assertEqual(len(territories), 1)
        territory = territories[0]
        self.assertEqual(territory.properties['admin1_nam'], 'Nord-Kivu')
        self.assertEqual(territory.properties['admin2_nam'], 'Goma')
        self.assertEqual(territory.properties['admin3_nam'], 'Goma')
        self.assertEqual(territory.properties['admin3_alt'], None)


text:
import '../amp-video-iframe';
import {Services} from '../../../../src/services';
import {VideoEvents} from '../../../../src/video-interface';
import {
  addAttributesToElement,
  createElementWithAttributes,
  whenUpgradedToCustomElement,
} from '../../../../src/dom';
import {listenOncePromise} from '../../../../src/event-helper';
import {tryParseJson} from '../../../../src/json';

function getIntersectionMessage(id) {
  return {data: {id, method: 'getIntersection'}};
}

describes.realWin(
  'amp-video-iframe',
  {
    amp: {
      extensions: ['amp-video-iframe'],
    },
  },
  (env) => {
    const defaultFixture = 'video-iframe.html';

    let win;
    let doc;
    let videoManagerStub;

    beforeEach(() => {
      win = env.win;
      doc = win.document;

      videoManagerStub = {
        register: env.sandbox.spy(),
      };

      env.sandbox
        .stub(Services, 'videoManagerForDoc')
        .returns(videoManagerStub);
    });

    function getIframeSrc(fixture = null) {
      const {port} = location;
      return `http://iframe.localhost:${port}/test/fixtures/served/${
        fixture || defaultFixture
      }`;
    }

    const layoutConfigAttrs = (size) =>
      !size
        ? {layout: 'fill'}
        : {
            layout: 'fixed',
            width: size[0],
            height: size[1],
          };

    function createVideoIframe(attrs = {}, opt_size) {
      const el = createElementWithAttributes(doc, 'amp-video-iframe', attrs);
      const {src = getIframeSrc(), poster = 'foo.png'} = attrs;
      addAttributesToElement(el, {src, poster});
      addAttributesToElement(el, layoutConfigAttrs(opt_size));
      doc.body.appendChild(el);
      return el;
    }

    function acceptMockedMessages(videoIframe) {
      env.sandbox
        ./*OK*/ stub(videoIframe.implementation_, 'originMatches_')
        .returns(true);
    }

    async function layoutAndLoad(element) {
      await whenUpgradedToCustomElement(element);
      // getLayoutBox() affects looksLikeTrackingIframe().
      // Use default width/height of 100 since element is not sized
      // as expected in test fixture.
      env.sandbox.stub(element, 'getLayoutBox').returns({
        width: Number(element.getAttribute('width')) || 100,
        height: Number(element.getAttribute('height')) || 100,
      });
      element.implementation_.layoutCallback();
      return listenOncePromise(element, VideoEvents.LOAD);
    }

    function stubPostMessage(videoIframe) {
      return env.sandbox./*OK*/ stub(
        videoIframe.implementation_,
        'postMessage_'
      );
    }

    function stubIntersectionEntry(element, time, intersectionRatio) {
      const entry = {time, intersectionRatio};
      env.sandbox
        ./*OK*/ stub(element, 'getIntersectionChangeEntry')
        .returns(entry);
      return entry;
    }

    describe('#layoutCallback', () => {
      it('uses data-param-* in src', async () => {
        const element = createVideoIframe({
          'data-param-vid': 'my_vid',
          'data-param-foo-bar': 'foo bar',
        });
        await layoutAndLoad(element);
        const {src} = element.querySelector('iframe');
        expect(src).to.match(/\?vid=my_vid&fooBar=foo%20bar#.*$/);
      });

      it('sets metadata in iframe name', async () => {
        const metadata = {
          canonicalUrl: 'foo.html',
          sourceUrl: 'bar.html',
        };

        env.sandbox.stub(Services, 'documentInfoForDoc').returns(metadata);

        const videoIframe = createVideoIframe();

        await layoutAndLoad(videoIframe);

        const {name} = videoIframe.implementation_.iframe_;

        expect(tryParseJson(name)).to.deep.equal(metadata);
      });

      it('sets amp=1 fragment in src', async () => {
        const rawSrc = getIframeSrc();
        const videoIframe = createVideoIframe({src: rawSrc});

        await layoutAndLoad(videoIframe);

        const {src} = videoIframe.implementation_.iframe_;
        expect(src).to.equal(`${rawSrc}#amp=1`);
      });

      it('does not set amp=1 fragment in src when fragment present', async () => {
        const rawSrc = `${getIframeSrc()}#my-fragment`;
        const videoIframe = createVideoIframe({src: rawSrc});

        await layoutAndLoad(videoIframe);

        const {src} = videoIframe.implementation_.iframe_;
        expect(src).to.equal(rawSrc);
      });
    });

    describe('#buildCallback', () => {
      it('rejects tracking iframes', () => {
        const trackingSizes = [
          [10, 10],
          [9, 9],
          [8, 8],
          [7, 7],
          [6, 6],
          [5, 5],
          [4, 4],
          [3, 3],
          [2, 2],
          [1, 1],
        ];

        trackingSizes.forEach((size) => {
          const {implementation_} = createVideoIframe({}, size);
          allowConsoleError(() => {
            expect(() => implementation_.layoutCallback()).to.throw();
          });
        });
      });
    });

    describe('#createPlaceholderCallback', () => {
      it('creates an amp-img with the poster as src', () => {
        const poster = 'foo.bar';
        const placeholder = createVideoIframe({poster}).createPlaceholder();
        expect(placeholder).to.have.attribute('placeholder');
        expect(placeholder.tagName.toLowerCase()).to.equal('amp-img');
        expect(placeholder.getAttribute('layout')).to.equal('fill');
        expect(placeholder.getAttribute('src')).to.equal(poster);
      });

      it("uses data-param-* in the poster's src", () => {
        expect(
          createVideoIframe({
            'data-param-my-poster-param': 'my param',
            'data-param-another': 'value',
          })
            .createPlaceholder()
            .getAttribute('src')
        ).to.match(/\?myPosterParam=my%20param&another=value$/);
      });
    });

    describe('#onMessage_', () => {
      it('should load and register on canplay', async () => {
        // Fixture inside frame triggers `canplay`.
        const videoIframe = createVideoIframe();
        await layoutAndLoad(videoIframe);

        const register = videoManagerStub.register.withArgs(
          videoIframe.implementation_
        );

        expect(register).to.have.been.calledOnce;
      });

      it('should not dispatch invalid events', async () => {
        const videoIframe = createVideoIframe();

        await layoutAndLoad(videoIframe);

        const invalidEvents = 'tacos al pastor'.split(' ');

        invalidEvents.forEach((event) => {
          const spy = env.sandbox.spy();
          videoIframe.addEventListener(event, spy);
          videoIframe.implementation_.onMessage_({data: {event}});
          expect(spy).to.not.have.been.called;
        });
      });

      it('should dispatch valid events', async () => {
        const videoIframe = createVideoIframe();

        await layoutAndLoad(videoIframe);

        acceptMockedMessages(videoIframe);

        const validEvents = [
          VideoEvents.PLAYING,
          VideoEvents.PAUSE,
          VideoEvents.ENDED,
          VideoEvents.MUTED,
          VideoEvents.UNMUTED,
          VideoEvents.AD_START,
          VideoEvents.AD_END,
        ];

        for (let i = 0; i < validEvents.length; i++) {
          const event = validEvents[i];
          const spy = env.sandbox.spy();
          videoIframe.addEventListener(event, spy);
          videoIframe.implementation_.onMessage_({data: {event}});
          expect(spy).to.have.been.calledOnce;
        }
      });

      it('should return intersection ratio if in autoplay range', async () => {
        const id = 1234;
        const time = 1.234;
        const intersectionRatio = 2 / 3;

        const videoIframe = createVideoIframe();

        await layoutAndLoad(videoIframe);

        const postMessage = stubPostMessage(videoIframe);

        acceptMockedMessages(videoIframe);

        const message = getIntersectionMessage(id);

        const expectedResponseMessage = {
          id,
          args: stubIntersectionEntry(videoIframe, time, intersectionRatio),
        };

        videoIframe.implementation_.onMessage_(message);

        expect(postMessage.withArgs(env.sandbox.match(expectedResponseMessage)))
          .to.have.been.calledOnce;
      });

      it('should return 0 if not in autoplay range', async () => {
        const id = 1234;
        const time = 1.234;
        const intersectionRatio = 1 / 3;
        const reportedRatioShouldBe = 0;

        const videoIframe = createVideoIframe();

        await layoutAndLoad(videoIframe);

        const postMessage = stubPostMessage(videoIframe);

        stubIntersectionEntry(videoIframe, time, intersectionRatio);

        acceptMockedMessages(videoIframe);

        const message = getIntersectionMessage(id);

        const expectedResponseMessage = {
          id,
          args: {
            time,
            intersectionRatio: reportedRatioShouldBe,
          },
        };

        videoIframe.implementation_.onMessage_(message);

        expect(postMessage.withArgs(env.sandbox.match(expectedResponseMessage)))
          .to.have.been.calledOnce;
      });

      [
        {
          accept: true,
          sufix: 'without data',
          eventType: 'video-custom-foo',
        },
        {
          accept: true,
          sufix: 'with data',
          eventType: 'video-custom-foo',
          vars: {
            myVar: 'bar',
          },
        },
        {
          accept: false,
          eventType: 'tacos al pastor',
          sufix: 'with invalid event name',
        },
      ].forEach(({sufix, eventType, vars, accept}) => {
        const verb = accept ? 'dispatch' : 'reject';

        it(`should ${verb} custom analytics event ${sufix}`, async () => {
          const videoIframe = createVideoIframe();
          const eventSpy = env.sandbox.spy();
          videoIframe.addEventListener(VideoEvents.CUSTOM_TICK, eventSpy);

          await layoutAndLoad(videoIframe);

          acceptMockedMessages(videoIframe);

          const data = {
            event: 'analytics',
            analytics: {
              'eventType': eventType,
            },
          };

          if (vars) {
            Object.assign(data.analytics, {vars});
          }

          const {implementation_} = videoIframe;

          if (accept) {
            const expectedEventVars = {eventType, vars: vars || {}};
            implementation_.onMessage_({data});
            expect(eventSpy).to.be.calledOnce;
            const eventData = eventSpy.firstCall.firstArg.data;
            expect(eventData.eventType).to.equal(expectedEventVars.eventType);
            expect(eventData.vars).to.deep.equal(expectedEventVars.vars);
          } else {
            allowConsoleError(() => {
              expect(() => implementation_.onMessage_({data})).to.throw();
            });
            expect(eventSpy).to.not.have.been.called;
          }
        });
      });
    });

    describe('#mutatedAttributesCallback', () => {
      it('updates src', async () => {
        const defaultSrc = getIframeSrc(defaultFixture);
        const videoIframe = createVideoIframe({src: defaultSrc});
        const {implementation_} = videoIframe;

        await layoutAndLoad(videoIframe);

        const {iframe_} = implementation_;

        expect(iframe_.src).to.match(new RegExp(`^${defaultSrc}#`));

        const newSrc = getIframeSrc('video-iframe-2.html');

        videoIframe.setAttribute('src', newSrc);

        implementation_.mutatedAttributesCallback({'src': true});

        expect(iframe_.src).to.match(new RegExp(`^${newSrc}#`));
      });
    });

    const implementedVideoInterfaceMethods = [
      'play',
      'pause',
      'mute',
      'unmute',
      'hideControls',
      'showControls',
      'fullscreenEnter',
      'fullscreenExit',
    ];

    implementedVideoInterfaceMethods.forEach((method) => {
      describe(`#${method}`, () => {
        const lowercaseMethod = method.toLowerCase();

        it(`should post '${lowercaseMethod}'`, async () => {
          const videoIframe = createVideoIframe();

          await layoutAndLoad(videoIframe);

          const postMessage = stubPostMessage(videoIframe);

          videoIframe.implementation_[method]();

          expect(
            postMessage.withArgs(
              env.sandbox.match({
                event: 'method',
                method: lowercaseMethod,
              })
            )
          ).to.have.been.calledOnce;
        });
      });
    });
  }
);


text:
import os
from vigra import readImage
import h5py
from progressbar import AnimatedMarker, Bar, BouncingBar, Counter, ETA, \
     FileTransferSpeed, FormatLabel, Percentage, \
    ProgressBar, ReverseBar, RotatingMarker, \
    SimpleProgress, Timer
from colorama import Fore, Back, Style

import os.path
#from termcolor import colored

def getFiles(path,ending):
    fnames = []
    baseNames = []
    for root, dirs, files in os.walk(path):
        for f in files:
            if f.endswith(ending):
                fp          =  os.path.join(root, f)
                baseName    =  f.split('.')[0]
                #print baseName
                fnames.append(fp)
                baseNames.append(baseName)
    return fnames,baseNames

def makeFullPath(folder,baseNames,ending):
    fps = []
    if folder[-1]=='/':
        f=folder
    else :
        f='%s/'%folder

    if ending[0]=='.':
        e=ending
    else :
        e='.%s'%ending

    for baseName in baseNames :
        fp="%s%s%s"%(f,baseName,e)
        #print fp
        fps.append(fp)

    return fps

def pBar(size,name=""):
    #print(Back.CYAN+Fore.BLACK + self.name + Fore.RESET + Back.RESET + Style.RESET_ALL)
    widgets = [ Back.CYAN+Fore.BLACK ," %s :"%name ,Percentage(), ' ',
        Bar(marker=RotatingMarker()), ' ', ETA(), ' ', FileTransferSpeed(),Back.RESET + Style.RESET_ALL]

    if size == 1 :
        size+=1
    pbar = ProgressBar(widgets=widgets, maxval=size-1).start()
    return pbar

def h5Exist(f,dset):
    try :
        if os.path.isfile(f):
            h5file = h5py.File(f,'r')
            e = False
            if dset in h5file.keys():
                #h5file[dset]
                e = True
            h5file.close()

            return e
        return False
    except:
        return False

class LazyArrays(object):
    def __init__(self,files,dset=None,filetype="h5"):
        self.files      = files
        self.dset       = dset
        self.filetype   = filetype

    def __len__(self):
        return len(self.files)

    def __getitem__(self,index):

        if self.filetype == "image" :
            return readImage(self.files[index])
        elif self.filetype == "h5" :
            f = h5py.File(self.files[index],'r')
            value = f[self.dset].value
            f.close()
            return value

class LazyCaller(object):
    def __init__(self,f,skip=False,verbose=True,overwrite=False,
                name="",compress=False,skipAll=False,compressionOpts=2):
        self.f = f
        self._batchKWargs   = set()
        self.verbose        = verbose
        self.outputFiles    = None
        self.dset           = None
        self.overwrite      = overwrite
        self.name           = name
        self.compress       = compress
        self.compressionOpts= compressionOpts
        self.skipAll        = skipAll

    def setCompression(self,compress,compressionOpts=2):
        self.compress=compress
        self.compressionOpts=compressionOpts

    def setBatchKwargs(self,batchKWargs):
        self._batchKWargs = set(batchKWargs)

    def setOutput(self,files,dset):
        self.outputFiles=files
        self.dset=dset

    def __call__(self,*args,**kwargs):

        #print colored('Compute ', 'red'), colored(self.name, 'green')

        #from colorama import Fore, Back, Style
        #print(Back.CYAN+Fore.BLACK + self.name + Fore.RESET + Back.RESET + Style.RESET_ALL)
        #print( Back.GREEN+ 'some red text')
        #print(Back.GREEN + 'and with a green background')
        #print(Style.DIM + 'and in dim text')
        #print(Fore.RESET + Back.RESET + Style.RESET_ALL)
        #print('back to normal now')

        assert self.outputFiles is not None
        if len(args)>0 :
            raise RuntimeError("LazyCaller(...) does only support keyword arguments")
        if self.skipAll :
            if self.verbose :
                print(Back.CYAN+Fore.BLACK +" SKIP %s"%self.name+Back.RESET + Style.RESET_ALL)
        else :
            constKwargs=dict()
            batchKwargs=dict()
            callingKwargs=dict()
            batchLen = None
            for kwarg in kwargs.keys() :
                if kwarg in self._batchKWargs :
                    batchInput          = kwargs[kwarg]
                    batchKwargs[kwarg]  = batchInput

                    if batchLen is None :
                        batchLen = len(batchInput)
                    else:
                        assert batchLen == len(batchInput)
                else :
                    constKwargs[kwarg]=kwargs[kwarg]
                    callingKwargs[kwarg]=kwargs[kwarg]

            if self.verbose :
                pbar = pBar(batchLen,name=self.name)
            # iterate over all batch items

            for batchIndex in range(batchLen):

                #check if we need to do the computation
                exist = h5Exist(self.outputFiles[batchIndex],self.dset)
                if exist == False  or self.overwrite == True:

                    # set up the kwargs for a single function call
                    for batchKwarg in self._batchKWargs :
                        batchItem  = kwargs[batchKwarg][batchIndex]
                        callingKwargs[batchKwarg]=batchItem

                    #print "batchIndex",batchIndex,"len",batchLen
                    # call the actual function and store the result
                    self._local_call_(callingKwargs,self.outputFiles[batchIndex])

                if self.verbose :
                    pbar.update(batchIndex)
            if self.verbose :
                pbar.finish()

    def _local_call_(self,callingKwargs,outputFile):

        result = self.f(**callingKwargs)

        f = h5py.File(outputFile,'w')

        if self.compress :
            dataset = f.create_dataset(self.dset,shape=result.shape,compression='gzip',compression_opts=self.compressionOpts)
            dataset[...]=result
        else :
            f[self.dset]=result

        #f[self.dset] =result
        f.close()

if __name__ == "__main__" :

    imagePath   = "/home/tbeier/src/privatOpengm/experiments/datasets/bsd500/BSR/BSDS500/data/images/test/"
    files       = getFiles(imagePath,"jpg")
    images      = LazyArrays(files,filetype="image")

    print type(images)

    img = images[0]

    for img in images :
        print img.shape


text: server ip for ssh to connect it