text:
package org.apache.rya.indexing.IndexPlanValidator;

import java.util.List;

import org.eclipse.rdf4j.query.MalformedQueryException;
import org.eclipse.rdf4j.query.algebra.TupleExpr;
import org.eclipse.rdf4j.query.algebra.evaluation.impl.FilterOptimizer;
import org.eclipse.rdf4j.query.parser.ParsedQuery;
import org.eclipse.rdf4j.query.parser.sparql.SPARQLParser;
import org.junit.Assert;
import org.junit.Test;

public class TupleReArrangerTest {

    @Test
    public void tupleReArrangeTest1() throws MalformedQueryException {

        String queryString = ""//
                + "SELECT ?a ?b ?c ?d ?e" //
                + "{" //
                + "{ ?a a ?b .  ?a <http://www.w3.org/2000/01/rdf-schema#label> ?c  }"//
                + " UNION { ?a <uri:talksTo> ?d .  ?a <http://www.w3.org/2000/01/rdf-schema#label> ?e  }"//
                + "}";//

        SPARQLParser sp = new SPARQLParser();
        ParsedQuery pq = sp.parseQuery(queryString, null);
        List<TupleExpr> tuples = TupleReArranger.getTupleReOrderings(pq.getTupleExpr());

        Assert.assertEquals(4, tuples.size());

    }

    @Test
    public void tupleReArrangeTest2() throws MalformedQueryException {

        String queryString = ""//
                + "SELECT ?a ?b ?c ?d ?e ?x ?y" //
                + "{" //
                + " ?e <uri:laughsAt> ?x ." //
                + " ?e <uri:livesIn> ?y . "//
                + "{ ?a a ?b .  ?a <http://www.w3.org/2000/01/rdf-schema#label> ?c  }"//
                + " UNION { ?a <uri:talksTo> ?d .  ?a <http://www.w3.org/2000/01/rdf-schema#label> ?e  }"//
                + "}";//

        SPARQLParser sp = new SPARQLParser();
        ParsedQuery pq = sp.parseQuery(queryString, null);
        List<TupleExpr> tuples = TupleReArranger.getTupleReOrderings(pq.getTupleExpr());

        Assert.assertEquals(24, tuples.size());

    }

    @Test
    public void tupleReArrangeTest3() throws MalformedQueryException {

        String queryString = ""//
                + "SELECT ?a ?b ?c ?d ?e ?x ?y" //
                + "{" //
                + " Filter(?c = <uri:label2>)" //
                + " Filter(?x = <uri:somethingFunny>) "//
                + " ?e <uri:laughsAt> ?x ." //
                + " ?e <uri:livesIn> ?y . "//
                + "{ ?a a ?b .  ?a <http://www.w3.org/2000/01/rdf-schema#label> ?c  }"//
                + " UNION { ?a <uri:talksTo> ?d .  ?a <http://www.w3.org/2000/01/rdf-schema#label> ?e  }"//
                + "}";//

        SPARQLParser sp = new SPARQLParser();
        ParsedQuery pq = sp.parseQuery(queryString, null);
        List<TupleExpr> tuples = TupleReArranger.getTupleReOrderings(pq.getTupleExpr());

        Assert.assertEquals(24, tuples.size());

    }

    @Test
    public void tupleReArrangeTest4() throws MalformedQueryException {

        String queryString = ""//
                + "SELECT ?a ?b ?c ?d ?e ?x ?y" //
                + "{" //
                + " Filter(?c = <uri:label2>)" //
                + " Filter(?x = <uri:somethingFunny>) "//
                + " Filter(?d = <uri:Fred> ) " //
                + " ?e <uri:laughsAt> ?x ." //
                + " ?e <uri:livesIn> ?y . "//
                + "{ ?a a ?b .  ?a <http://www.w3.org/2000/01/rdf-schema#label> ?c  }"//
                + " UNION { ?a <uri:talksTo> ?d .  ?a <http://www.w3.org/2000/01/rdf-schema#label> ?e  }"//
                + "}";//

        SPARQLParser sp = new SPARQLParser();
        ParsedQuery pq = sp.parseQuery(queryString, null);
        TupleExpr te = pq.getTupleExpr();
        new FilterOptimizer().optimize(te, null, null);
        System.out.println(te);
        List<TupleExpr> tuples = TupleReArranger.getTupleReOrderings(te);
        System.out.println(tuples);

        Assert.assertEquals(24, tuples.size());

    }

}


text:
from rest_framework.test import APIRequestFactory

from olympia.amo.helpers import absolutify
from olympia.amo.tests import TestCase, user_factory
from olympia.users.models import UserProfile
from olympia.users.serializers import BaseUserSerializer

class TestBaseUserSerializer(TestCase):
    def setUp(self):
        self.request = APIRequestFactory().get('/')
        self.user = user_factory()

    def serialize(self):
        # Manually reload the user first to clear any cached properties.
        self.user = UserProfile.objects.get(pk=self.user.pk)
        serializer = BaseUserSerializer(context={'request': self.request})
        return serializer.to_representation(self.user)

    def test_basic(self):
        result = self.serialize()
        assert result['name'] == self.user.name
        assert result['url'] == absolutify(self.user.get_url_path())

redpajama_set_name: RedPajamaGithub


text:
===============
Command Objects
===============

Command objects are fundamental to how the SDK works. In normal usage of the SDK, you may never interact with command
objects. However, if you are :ref:`performing operations in parallel <parallel_commands>`,
:ref:`inspecting data from the request or response <requests_and_responses>`, or writing custom plugins, you will need
to understand how they work.

Typical SDK usage
-----------------

.. include:: _snippets/performing-operations.txt

A peek under the hood
---------------------

If you examine a client class, you will see that the methods corresponding to the operations do not actually exist. They
are implemented using the ``__call()`` magic method behavior. These pseudo-methods are actually shortcuts that
encapsulate the SDK's — and the underlying Guzzle library's — use of command objects.

For example, you could perform the same ``DescribeTable`` operation from the preceding section using command objects:

.. code-block:: php

    $command = $dynamoDbClient->getCommand('DescribeTable', array(
        'TableName' => 'YourTableName',
    ));
    $result = $command->getResult();

A **Command** is an object that represents the execution of a service operation. Command objects are an abstraction of
the process of formatting a request to a service, executing the request, receiving the response, and formatting the
results. Commands are created and executed by the client and contain references to **Request** and **Response** objects.
The **Result** object is a what we refer to as a :doc:`"modeled response" <feature-models>`.

Using command objects
---------------------

Using the pseudo-methods for performing operations is shorter and preferred for typical use cases, but command objects
provide greater flexibility and access to additional data.

Manipulating command objects before execution
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When you create a command using a client's ``getCommand()`` method, it does not immediately execute. Because commands
are lazily executed, it is possible to pass the command object around and add or modify the parameters. The following
examples show how to work with command objects:

.. code-block:: php

    // You can add parameters after instantiation
    $command = $s3Client->getCommand('ListObjects');
    $command->set('MaxKeys', 50);
    $command->set('Prefix', 'foo/baz/');
    $result = $command->getResult();

    // You can also modify parameters
    $command = $s3Client->getCommand('ListObjects', array(
        'MaxKeys' => 50,
        'Prefix'  => 'foo/baz/',
    ));
    $command->set('MaxKeys', 100);
    $result = $command->getResult();

    // The set method is chainable
    $result = $s3Client->getCommand('ListObjects')
        ->set('MaxKeys', 50);
        ->set('Prefix', 'foo/baz/');
        ->getResult();

    // You can also use array access
    $command = $s3Client->getCommand('ListObjects');
    $command['MaxKeys'] = 50;
    $command['Prefix'] = 'foo/baz/';
    $result = $command->getResult();

Also, see the `API docs for commands
<http://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Guzzle.Service.Command.AbstractCommand.html>`_.

.. _requests_and_responses:

Request and response objects
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

From the command object, you can access the request, response, and result objects. The availability of these objects
depend on the state of the command object.

Managing command state
^^^^^^^^^^^^^^^^^^^^^^

Commands must be prepared before the request object is available, and commands must executed before the response and
result objects are available.

.. code-block:: php

    // 1. Create
    $command = $client->getCommand('OperationName');

    // 2. Prepare
    $command->prepare();
    $request = $command->getRequest();
    // Note: `prepare()` also returns the request object

    // 3. Execute
    $command->execute();
    $response = $command->getResponse();
    $result = $command->getResult();
    // Note: `execute()` also returns the result object

This is nice, because it gives you a chance to modify the request before it is actually sent.

.. code-block:: php

    $command = $client->getCommand('OperationName');
    $request = $command->prepare();
    $request->addHeader('foo', 'bar');
    $result = $command->execute();

You don't have to manage each aspect of the state though, calling ``execute()`` will also prepare the command, and
calling ``getResult()`` will prepare and execute the command.

Using requests and responses
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Request and response objects contain data about the actual requests and responses to the service.

.. code-block:: php

    $command = $client->getCommand('OperationName');
    $command->execute();

    // Get and use the request object
    $request = $command->getRequest();
    $contentLength = $request->getHeader('Content-Length');
    $url = $request->getUrl();

    // Get and use the response object
    $response = $command->getResponse();
    $success = $response->isSuccessful();
    $status = $response->getStatusCode();

You can also take advantage of the ``__toString`` behavior of the request and response objects. If you print them
(e.g., ``echo $request;``), you can see the raw request and response data that was sent over the wire.

To learn more, read the API docs for the `Request
<http://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Guzzle.Http.Message.Request.html>`_ and `Response
<http://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Guzzle.Http.Message.Response.html>`_ classes.

.. _parallel_commands:

Executing commands in parallel
------------------------------

The AWS SDK for PHP allows you to execute multiple operations in parallel when you use command objects. This can reduce
the total time (sometimes drastically) it takes to perform a set of operations, since you can do them at the same time
instead of one after another. The following shows an example of how you could upload two files to Amazon S3 at the same
time.

.. code-block:: php

    $commands = array();
    $commands[] = $s3Client->getCommand('PutObject', array(
        'Bucket' => 'SOME_BUCKET',
        'Key'    => 'photos/photo01.jpg',
        'Body'   => fopen('/tmp/photo01.jpg', 'r'),
    ));
    $commands[] = $s3Client->getCommand('PutObject', array(
        'Bucket' => 'SOME_BUCKET',
        'Key'    => 'photos/photo02.jpg',
        'Body'   => fopen('/tmp/photo02.jpg', 'r'),
    ));

    // Execute an array of command objects to do them in parallel
    $s3Client->execute($commands);

    // Loop over the commands, which have now all been executed
    foreach ($commands as $command) {
        $result = $command->getResult();
        // Do something with result
    }

Error handling with parallel commands
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When executing commands in parallel, error handling becomes a bit trickier. If an exception is thrown, then the SDK (via
Guzzle) will aggregate the exceptions together and throw a single ``Guzzle\Service\Exception\CommandTransferException``
(`see the API docs
<http://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Guzzle.Service.Exception.CommandTransferException.html>`_) once all
of the commands have completed execution. This exception class keeps track of which commands succeeded and which failed
and also allows you to fetch the original exceptions thrown for failed commands.

.. code-block:: php

    use Guzzle\Service\Exception\CommandTransferException;

    try {
        $succeeded = $client->execute($commands);
    } catch (CommandTransferException $e) {
        $succeeded = $e->getSuccessfulCommands();
        echo "Failed Commands:\n";
        foreach ($e->getFailedCommands() as $failedCommand) {
            echo $e->getExceptionForFailedCommand($failedCommand)->getMessage() . "\n";
        }
    }


text:
describe Biodiversity do
  describe 'version' do
    it 'returns version of Biodiversity gem' do
      expect(subject.version).to match(/\d+\.\d+\.\d+/)
    end
  end
end


text:
<?php

namespace PhpSsrs\ReportingService2005;

class PauseScheduleResponse
{

  /**
   *
   * @access public
   */
  public function __construct()
  {

  }

}


text:
| [![Build Status](https://travis-ci.org/timblack1/rcl.svg?branch=master)](https://travis-ci.org/timblack1/rcl) | [![Coverage Status](https://coveralls.io/repos/timblack1/rcl/badge.svg?branch=master&service=github)](https://coveralls.io/github/timblack1/rcl?branch=master) | [![Dependency Status](https://david-dm.org/timblack1/rcl.svg)](https://david-dm.org/timblack1/rcl/master) | [![devDependency Status](https://david-dm.org/timblack1/rcl/master/dev-status.svg)](https://david-dm.org/timblack1/rcl/master#info=devDependencies) |
| --- | --- | --- | --- |
# Reformed Churches Locator

Want to find a reformed church in Timbuktu?  Reformed Churches Locator is a web application
that will provide a searchable, user-editable map and directory of all Reformed churches in
the world. It will aggregate congregations' contact info via data feeds from various
sources, and provide a JavaScript widget containing a map & directory that can be embedded
into your website using a simple code snippet (like embedding a YouTube video). It will
federate filtered sets of congregation data to other Reformed Churches Locator nodes via
CouchDB's filtered replications.  The intended result is that Reformed Churches Locator will
become the source of the most up-to-date contact info for Reformed churches, and will
simplify the job of creating a denominational church directory.

Reformed Churches Locator will recreate the map & congregations components of PresbyterySite
(http://sourceforge.net/projects/presbyterysite), but host & serve the congregation data in a
federated or peer-to-peer fashion in order to manage data from all Reformed churches rather
than from only one presbytery.

## Application Architecture

Please note that older Reformed Churches Locator issues which describe the overall application
architecture are hosted at https://blueprints.launchpad.net/reformedchurcheslocator.

Reformed Churches Locator is an "Offline first" application, meaning it will run well offline,
then sync its data to the server when it has an internet connection.  It uses Hoodie to store
the app's data locally using PouchDB, and syncs to CouchDB on the server through Hoodie's
server-side API.

## Installation

The following instructions are specific to installing this application on Ubuntu Linux.  Installation
on other operating systems is not documented.

### Install system-level dependencies

Install Node.js, CouchDB, & Git

```bash
$ sudo apt-get install couchdb nodejs git
```

Verify you're running Node 0.12.x or above:

```bash
$ node --version
```

The version should be at or above 0.12.x.

If you don't have Node.js installed, or you have a lower version, go to [nodejs.org](https://nodejs.org)
and click on the big green Install button.

### Install user- and app-level dependencies

```bash
$ npm install -g gulp bower && npm install && bower install
```

### Set Hoodie's admin password

```bash
$ hoodie start -n
```

Enter an admin password here.  If you don't, you'll need to remove the data directory with this command:
```bash
$ # rm -rf data
```
then run `hoodie start` again to enter the password.

After you set the password, type CTRL-C in the terminal to kill the Hoodie process.

### Run Reformed Churches Locator

Then run Reformed Churches Locator by running the following commands in your terminal:

```bash
$ git clone https://github.com/timblack1/rcl.git
$ npm start
```

This should open up a copy of the application in your web browser.

### Development workflow

#### Serve / watch

```bash
$ npm start
```

This outputs an IP address you can use to locally test and another that can be used on devices
connected to your network.

#### Run tests

```bash
$ npm test
```

This runs the unit tests defined in the `app/test` directory through
[web-component-tester](https://github.com/Polymer/web-component-tester).

To run tests Java 7 or higher is required. To update Java go to
http://www.oracle.com/technetwork/java/javase/downloads/index.html and download ***JDK*** and
install it.

## Deployment

Because the application is still in development, we have not yet documented how to deploy it to a server.

## Frequently Asked Questions

### Something has failed during installation. How do I fix this?

Our most commonly reported issue is around system permissions for installing Node.js dependencies.
We recommend following the
[fixing npm permissions](https://github.com/sindresorhus/guides/blob/master/npm-global-without-sudo.md)
guide to address any messages around administrator permissions being required. If you use `sudo`
to work around these issues, this guide may also be useful for avoiding that.

If you run into an exception that mentions five optional dependencies failing (or an `EEXIST` error), you
may have run into an npm [bug](https://github.com/npm/npm/issues/6309). We recommend updating to npm 2.11.0+
to work around this. You can do this by opening a Command Prompt/terminal and running
`npm install npm@2.11.0 -g`. If you are on Windows, Node.js (and npm) may have been installed into
`C:\Program Files\`. Updating npm by running `npm install npm@2.11.0 -g` will install npm into `%AppData%\npm`,
but your system will still use the npm version. You can avoid this by deleting your older npm from
`C:\Program Files\nodejs` as described [here](https://github.com/npm/npm/issues/6309#issuecomment-67549380).

If the issue is to do with a failure somewhere else, you might find that due to a network issue
a dependency failed to correctly install. We recommend running `npm cache clean` and deleting the
`node_modules` directory followed by `npm install` to see if this corrects the problem. If not, please check
the [issue tracker](https://github.com/PolymerElements/polymer-starter-kit/issues) in case there is a
workaround or fix already posted.

# Recipes for further development of this app

* [Add ES2015 (formally ES6) support using Babel](add-es2015-support-babel.md)
* [Polymer Performance Recipe](polymer-perf.md)
* [Deploy to Github Pages](deploy-to-github-pages.md)
* [Deploy to Firebase using Pretty URLs](deploy-to-firebase-pretty-urls.md)
* [Use PSK for Mobile Chrome Apps](mobile-chrome-apps.md)


text:
import React from 'react';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
import style from './style.css';

export default class <%= componentName %> extends React.Component{
	render(){
		return(
			<div>
			</div>
			);
	}
}


text:
FOUNDATION_EXPORT NSString *const FORCE_UPDATE_CELL_REUSE_IDENTIFIER;

@interface ForceUpdateCellViewModel : NSObject<PVGTableViewCellViewModel>

@property (readonly, nonatomic) NSString *ID;

- (instancetype)initWithID:(NSString *)ID;

- (UIColor *)randomColor;

@end


text:
require "spec_helper"

describe VIPS do
  it "has a library version" do
    a = VIPS::LIB_VERSION_ARRAY
    a.size.should == 3
    a[0].should >= 7
    a[1].should >= 20
    a[2].should >= 0
    VIPS::LIB_VERSION.should =~ /^\d+\.\d+\.\d+/
  end

  describe ".sequential_mode_supported?" do
    it "should return false for < 7.28 libvips versions" do
      original_version = VIPS::LIB_VERSION_ARRAY
      VIPS::LIB_VERSION_ARRAY = [7, 27, 7]
      Vips.sequential_mode_supported?.should == false
      VIPS::LIB_VERSION_ARRAY = original_version
    end

    it "should return true for >= 7.28 libvips versions" do
      original_version = VIPS::LIB_VERSION_ARRAY
      VIPS::LIB_VERSION_ARRAY = [7, 28, 0]
      Vips.sequential_mode_supported?.should == true
      VIPS::LIB_VERSION_ARRAY = original_version
    end

    it "should return true for >= 8 libvips versions" do
      original_version = VIPS::LIB_VERSION_ARRAY
      VIPS::LIB_VERSION_ARRAY = [8, 0, 0]
      Vips.sequential_mode_supported?.should == true
      VIPS::LIB_VERSION_ARRAY = original_version
    end
  end
end


text:
require "ar-find-in-batches-with-order/version"

module ActiveRecord
  module FindInBatchesWithOrder
    def find_in_batches_with_order(options = {})
      relation = self

      # we have to be explicit about the options to ensure proper ordering and retrieval

      direction = options.delete(:direction) || (arel.orders.first.try(:ascending?) ? :asc : nil) || (arel.orders.first.try(:descending?) ? :desc : nil) || raise("please pass :direction that matches sort order")
      start = options.delete(:start)
      collate = options[:collate] ? "COLLATE #{connection.quote_column_name(options[:collate])}" : ""
      batch_size = options.delete(:batch_size) || 1000
      with_start_ids = []

      # try to deduct the property_key, but safer to specificy directly
      property_key = options.delete(:property_key) || arel.orders.first.try(:value).try(:name) || arel.orders.first.try(:split,' ').try(:first)
      tbl = connection.quote_table_name(options.delete(:property_table_name) || table.name)
      sanitized_key = "#{tbl}.#{connection.quote_column_name(property_key)}"
      relation = relation.limit(batch_size)

      records = start ? (direction == :desc ? relation.where("#{sanitized_key} <= ?", start).to_a : relation.where("#{sanitized_key} >= ?", start).to_a)  : relation.to_a

      while records.any?
        records_size = records.size

        yield records

        break if records_size < batch_size

        next_start = records.last.send(property_key)
        with_start_ids.clear if start != next_start
        start = next_start

        records.each do |record|
          if record.send(property_key) == start
            with_start_ids << record.id
          end
        end

        without_dups = relation.where.not(relation.klass.primary_key => with_start_ids)
        records = (direction == :desc ? without_dups.where("#{sanitized_key} <= ? #{collate}", start).to_a : without_dups.where("#{sanitized_key} >= ? #{collate}", start).to_a)
      end
    end

    def find_each_with_order(options = {})
      find_in_batches_with_order(options) do |records|

        records.each do |record|
          yield record
        end
      end
    end

  end

  class Relation
    include FindInBatchesWithOrder
  end
end


text:
using System.Xml.Serialization;

namespace Amazon.CloudFront_2012_03_15.Model
{
    /// <summary>
    /// The CreateDistributionResponse contains any headers and the Distribution Config
    /// for the distribution created.
    /// </summary>
    [XmlRootAttribute(Namespace = "http://cloudfront.amazonaws.com/doc/2010-11-01/", IsNullable = false)]
    public class CreateDistributionResponse : CloudFrontResponse
    {
        #region Private Members

        private CloudFrontDistribution distribution;

        #endregion

        #region Distribution
        /// <summary>
        /// Gets and sets the Distribution property.
        /// </summary>
        [XmlElementAttribute(ElementName = "Distribution")]
        public CloudFrontDistribution Distribution
        {
            get { return this.distribution; }
            set { this.distribution = value; }
        }

        #endregion

        #region ETag

        /// <summary>
        /// Gets and sets the ETag property.
        /// The Distribution's ETag is also set if
        /// possible.
        /// </summary>
        [XmlElementAttribute(ElementName = "ETag")]
        public override string ETag
        {
            set
            {
                this.etagHeader = value;
                if (null != distribution)
                {
                    distribution.ETag = value;
                }
            }
        }

        #endregion
    }
}


text:
#include "V8Utils.h"

/**
  Get a field from an object as a persistent function handle. Empty handle if the key does not exist.
**/
Handle<Function> V8Utils::getFunctionFromObject(Handle<Object> callbacks, Handle<String> key) {
  Handle<Function> callback;
  if(callbacks->Has(key)) {
    callback = Persistent<Function>::New(Handle<Function>::Cast(callbacks->Get(key)));
  }
  return callback;
}

void V8Utils::callV8FunctionWithNoArgumentsIfHandleNotEmpty(v8::Handle<v8::Function> function) {
  if(!function.IsEmpty()) {
    unsigned int argc = 0;
    v8::Handle<v8::Value> argv[0];
    function->Call(v8::Context::GetCurrent()->Global(), argc, argv);
  }
}


text:
package org.apache.helix.ipc.benchmark;

public class RunBenchmark {
  public static void main(String[] args) throws Exception{
    TestServer.main(new String[]{"8011", "localhost", "8012"});
    TestServer.main(new String[]{"8012", "localhost", "8011"});
  }
}


text:
from django.shortcuts import get_object_or_404, render
from django.conf import settings
from django.http import HttpResponse
from django.views import generic
from django.core.cache import cache
from django.views.decorators.cache import cache_page

from common.diagrams_gpcr import DrawHelixBox, DrawSnakePlot

from protein.models import Protein, ProteinFamily, ProteinSegment, ProteinConformation
from residue.models import Residue,ResidueGenericNumber
from mutation.models import MutationExperiment
from structure.models import Structure
from interaction.models import ResidueFragmentInteraction
from mutational_landscape.models import NaturalMutations, PTMs

Alignment = getattr(__import__('common.alignment_' + settings.SITE_NAME, fromlist=['Alignment']), 'Alignment')

import json

def hex_to_RGB(hex):
  ''' "#FFFFFF" -> [255,255,255] '''
  # Pass 16 to the integer function for change of base
  return [int(hex[i:i+2], 16) for i in range(1,6,2)]

def RGB_to_hex(RGB):
  ''' [255,255,255] -> "#FFFFFF" '''
  # Components need to be integers for hex to make sense
  RGB = [int(x) for x in RGB]
  return "#"+"".join(["0{0:x}".format(v) if v < 16 else
            "{0:x}".format(v) for v in RGB])

def color_dict(gradient):
  ''' Takes in a list of RGB sub-lists and returns dictionary of
    colors in RGB and hex form for use in a graphing function
    defined later on '''
  return [RGB_to_hex(RGB) for RGB in gradient]

def linear_gradient(start_hex="#4682B4", finish_hex="#FFB347", n=10):
    # http://bsou.io/posts/color-gradients-with-python
  ''' returns a gradient list of (n) colors between
    two hex colors. start_hex and finish_hex
    should be the full six-digit color string,
    inlcuding the number sign ("#FFFFFF") '''
  # Starting and ending colors in RGB form
  s = hex_to_RGB(start_hex)
  f = hex_to_RGB(finish_hex)
  # Initilize a list of the output colors with the starting color
  RGB_list = [s]
  # Calcuate a color at each evenly spaced value of t from 1 to n
  for t in range(1, n):
    # Interpolate RGB vector for color at the current value of t
    curr_vector = [
      int(s[j] + (float(t)/(n-1))*(f[j]-s[j]))
      for j in range(3)
    ]
    # Add it to our list of output colors
    RGB_list.append(curr_vector)

  return color_dict(RGB_list)

@cache_page(60 * 60 * 24 * 7)
def detail(request, slug):
    # FULL class A is too big for consensus
    if slug == "001":
        return HttpResponse("Displaying a consensus of all class A receptors is currently not supported.")

    # get family
    pf = ProteinFamily.objects.get(slug=slug)

    # get family list
    ppf = pf
    families = [ppf.name]
    while ppf.parent.parent:
        families.append(ppf.parent.name)
        ppf = ppf.parent
    families.reverse()

    # number of proteins
    proteins = Protein.objects.filter(family__slug__startswith=pf.slug, sequence_type__slug='wt')
    no_of_proteins = proteins.count()
    no_of_human_proteins = Protein.objects.filter(family__slug__startswith=pf.slug, species__id=1,
        sequence_type__slug='wt').count()
    list_proteins = list(proteins.values_list('pk',flat=True))

    # get structures of this family
    structures = Structure.objects.filter(protein_conformation__protein__parent__family__slug__startswith=slug
        ).order_by('-representative', 'resolution').prefetch_related('pdb_code__web_resource')

    mutations = MutationExperiment.objects.filter(protein__in=proteins).prefetch_related('residue__generic_number',
                                'exp_qual', 'ligand')

    interactions = ResidueFragmentInteraction.objects.filter(
        structure_ligand_pair__structure__protein_conformation__protein__parent__in=proteins,
        structure_ligand_pair__annotated=True).exclude(interaction_type__type='hidden').prefetch_related(
            'rotamer__residue__generic_number', 'interaction_type'
            ).order_by('rotamer__residue__sequence_number')
    interaction_list = {}
    for interaction in interactions:
        if interaction.rotamer.residue.generic_number:
            gn = interaction.rotamer.residue.generic_number.label
            aa = interaction.rotamer.residue.amino_acid
            interactiontype = interaction.interaction_type.name
            if gn not in interaction_list:
                interaction_list[gn] = []
            interaction_list[gn].append([aa, interactiontype])

    ## Variants
    NMs = NaturalMutations.objects.filter(
        protein__in=proteins).prefetch_related('residue__generic_number')

    natural_mutation_list = {}
    max_snp_pos = 1
    for NM in NMs:
        if NM.residue.generic_number:
            if NM.residue.generic_number.label in natural_mutation_list:
                natural_mutation_list[NM.residue.generic_number.label]['val'] += 1
                if not str(NM.amino_acid) in natural_mutation_list[NM.residue.generic_number.label]['AA']:
                    natural_mutation_list[NM.residue.generic_number.label]['AA'] = natural_mutation_list[NM.residue.generic_number.label]['AA'] + str(NM.amino_acid) + ' '

                if natural_mutation_list[NM.residue.generic_number.label]['val'] > max_snp_pos:
                    max_snp_pos = natural_mutation_list[NM.residue.generic_number.label]['val']
            else:
                natural_mutation_list[NM.residue.generic_number.label] = {'val':1, 'AA': NM.amino_acid + ' '}

    ## PTMs
    ptms = PTMs.objects.filter(
        protein__in=proteins).prefetch_related('residue__generic_number')

    ptm_list = {}
    for ptm in ptms:
        if ptm.residue.generic_number:
            if ptm.residue.generic_number.label in ptm_list:
                ptm_list[ptm.residue.generic_number.label]['val'] += 1
                if not str(ptm.modification) in ptm_list[ptm.residue.generic_number.label]['mod']:
                    ptm_list[ptm.residue.generic_number.label]['mod'] = ptm_list[ptm.residue.generic_number.label]['mod'] + ', ' + str(ptm.modification)
            else:
                ptm_list[ptm.residue.generic_number.label] = {'val':1, 'mod': ptm.modification}

    # CMs = CancerMutations.objects.filter(
    #     protein__in=proteins).prefetch_related('residue__generic_number')
    #
    # cancer_mutation_list = {}
    # max_cancer_pos = 1
    # for CM in CMs:
    #     if CM.residue.generic_number:
    #         if CM.residue.generic_number.label in cancer_mutation_list:
    #             cancer_mutation_list[CM.residue.generic_number.label]['val'] += 1
    #             if not str(CM.amino_acid) in cancer_mutation_list[CM.residue.generic_number.label]['AA']:
    #                 cancer_mutation_list[CM.residue.generic_number.label]['AA'] = cancer_mutation_list[CM.residue.generic_number.label]['AA'] + str(CM.amino_acid)
    #
    #             if cancer_mutation_list[CM.residue.generic_number.label]['val'] > max_cancer_pos:
    #                 max_cancer_pos = cancer_mutation_list[CM.residue.generic_number.label]['val']
    #         else:
    #             cancer_mutation_list[CM.residue.generic_number.label] = {'val':1, 'AA': CM.amino_acid}
    #
    # DMs = DiseaseMutations.objects.filter(
    #     protein__in=proteins).prefetch_related('residue__generic_number')

    # disease_mutation_list = {}
    # max_disease_pos = 1
    # for DM in DMs:
    #     if DM.residue.generic_number:
    #         if DM.residue.generic_number.label in disease_mutation_list:
    #             disease_mutation_list[DM.residue.generic_number.label]['val'] += 1
    #             if not str(DM.amino_acid) in disease_mutation_list[DM.residue.generic_number.label]['AA']:
    #                 disease_mutation_list[DM.residue.generic_number.label]['AA'] = disease_mutation_list[DM.residue.generic_number.label]['AA'] + str(DM.amino_acid)
    #
    #             if disease_mutation_list[DM.residue.generic_number.label]['val'] > max_cancer_pos:
    #                 max_cancer_pos = disease_mutation_list[DM.residue.generic_number.label]['val']
    #         else:
    #             disease_mutation_list[DM.residue.generic_number.label] = {'val':1, 'AA': DM.amino_acid}

    mutations_list = {}
    for mutation in mutations:
        if not mutation.residue.generic_number: continue #cant map those without display numbers
        if mutation.residue.generic_number.label not in mutations_list: mutations_list[mutation.residue.generic_number.label] = []
        if mutation.ligand:
            ligand = mutation.ligand.name
        else:
            ligand = ''
        if mutation.exp_qual:
            qual = mutation.exp_qual.qual
        else:
            qual = ''
        mutations_list[mutation.residue.generic_number.label].append([mutation.foldchange,ligand.replace("'", "\\'"),qual])

    try:
        pc = ProteinConformation.objects.get(protein__family__slug=slug, protein__sequence_type__slug='consensus')
    except ProteinConformation.DoesNotExist:
        try:
            # In case of single members, not all families have a set consensus - grab the consensus of that single member
            pc = ProteinConformation.objects.get(protein__family__slug__startswith=slug, protein__sequence_type__slug='consensus')
        except ProteinConformation.DoesNotExist:
            try:
                pc = ProteinConformation.objects.get(protein__family__slug=slug, protein__species_id=1,
                    protein__sequence_type__slug='wt')
            except ProteinConformation.DoesNotExist:
                # In case of single members, not all families have a set consensus - grab the human representative of that single member
                pc = ProteinConformation.objects.get(protein__family__slug__startswith=slug, protein__species_id=1,
                    protein__sequence_type__slug='wt')

    residues = Residue.objects.filter(protein_conformation=pc).order_by('sequence_number').prefetch_related(
        'protein_segment', 'generic_number', 'display_generic_number')

    jsondata = {}
    jsondata_interaction = {}
    jsondata_natural_mutations = {}
    jsondata_ptms = {}
    # jsondata_cancer_mutations = {}
    # jsondata_disease_mutations = {}
    for r in residues:
        if r.generic_number:
            if r.generic_number.label in mutations_list:
                jsondata[r.sequence_number] = [mutations_list[r.generic_number.label]]
            if r.generic_number.label in interaction_list:
                jsondata_interaction[r.sequence_number] = interaction_list[r.generic_number.label]
            if r.generic_number.label in natural_mutation_list:
                jsondata_natural_mutations[r.sequence_number] = natural_mutation_list[r.generic_number.label]
            if r.generic_number.label in ptm_list:
                jsondata_ptms[r.sequence_number] = ptm_list[r.generic_number.label]
            # if r.generic_number.label in cancer_mutation_list:
                # jsondata_cancer_mutations[r.sequence_number] = cancer_mutation_list[r.generic_number.label]
            # if r.generic_number.label in disease_mutation_list:
                # jsondata_disease_mutations[r.sequence_number] = disease_mutation_list[r.generic_number.label]

    jsondata_natural_mutations['color'] = linear_gradient(start_hex="#c79494", finish_hex="#c40100", n=max_snp_pos)
    # jsondata_cancer_mutations['color'] = linear_gradient(start_hex="#d8baff", finish_hex="#422d65", n=max_cancer_pos)
    # jsondata_disease_mutations['color'] = linear_gradient(start_hex="#ffa1b1", finish_hex="#6e000b", n=max_disease_pos)

    HelixBox = DrawHelixBox(residues, 'Class A', 'family_diagram_preloaded_data')
    SnakePlot = DrawSnakePlot(residues, 'Class A', 'family_diagram_preloaded_data')

    # process residues and return them in chunks of 10
    # this is done for easier scaling on smaller screens
    chunk_size = 10
    r_chunks = []
    r_buffer = []
    last_segment = False
    border = False
    title_cell_skip = 0
    for i, r in enumerate(residues):
        # title of segment to be written out for the first residue in each segment
        segment_title = False

        # keep track of last residues segment (for marking borders)
        if r.protein_segment.slug != last_segment:
            last_segment = r.protein_segment.slug
            border = True

        # if on a border, is there room to write out the title? If not, write title in next chunk
        if i == 0 or (border and len(last_segment) <= (chunk_size - i % chunk_size)):
            segment_title = True
            border = False
            title_cell_skip += len(last_segment) # skip cells following title (which has colspan > 1)

        if i and i % chunk_size == 0:
            r_chunks.append(r_buffer)
            r_buffer = []

        r_buffer.append((r, segment_title, title_cell_skip))

        # update cell skip counter
        if title_cell_skip > 0:
            title_cell_skip -= 1
    if r_buffer:
        r_chunks.append(r_buffer)

    context = {'pf': pf, 'families': families, 'structures': structures, 'no_of_proteins': no_of_proteins,
        'no_of_human_proteins': no_of_human_proteins, 'HelixBox':HelixBox, 'SnakePlot':SnakePlot,
        'mutations':mutations, 'r_chunks': r_chunks, 'chunk_size': chunk_size, 'mutations_pos_list' : json.dumps(jsondata),'interaction_pos_list' : json.dumps(jsondata_interaction), 'natural_mutations_pos_list': json.dumps(jsondata_natural_mutations), 'ptms_pos_list': json.dumps(jsondata_ptms)} # ,'cancer_mutations_pos_list': json.dumps(jsondata_cancer_mutations), 'disease_mutations_pos_list': json.dumps(jsondata_disease_mutations)

    return render(request, 'family/family_detail.html', context)


text:
package works.cirno.mocha.resolver.prd;

import java.util.List;

/**
 *
 */
public interface PrefixDict<T> {
	void add(String prefix, T value);

	List<T> select(String string);

	List<T> select(String string, List<T> values);
}


text:
package com.tattood.tattood;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.shaishavgandhi.loginbuttons.GooglePlusButton;

import org.json.JSONObject;

import java.util.Objects;

import static com.android.volley.Response.ErrorListener;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends AppCompatActivity implements
        GoogleApiClient.OnConnectionFailedListener {

    private static final String PREFS_NAME = "LoginPreferences";
    private GoogleApiClient mGoogleApiClient;
    private static final int RC_SIGN_IN = 100;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initLogin();
        askForPermission();
        setContentView(R.layout.activity_login);
        GooglePlusButton login_button = (GooglePlusButton) findViewById(R.id.login_button);
//        SignInButton login_button = (SignInButton) findViewById(R.id.login_button);
//        login_button.setSize(SignInButton.SIZE_WIDE);
        login_button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("Signing", "clicked method signIn");
                signIn();
            }
        });
    }

    private void askForPermission() {
        String[] permission = {
                android.Manifest.permission.CAMERA,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                android.Manifest.permission.READ_EXTERNAL_STORAGE
        };
        ActivityCompat.requestPermissions(this, permission, 0x5);
    }

    private void initLogin() {
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
//                .requestIdToken("876997578175-3mvn4447hcvdpr4nr7vml1otj8ottad6.apps.googleusercontent.com")
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail().build();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                    @Override
                    public void onConnected(@Nullable Bundle bundle) {
                        Log.d("Login", "HERE");
                        if (getIntent().hasExtra("logout")) {
                            Log.d("Login", "HERE--Logout");
                            mAuth.signOut();
                            Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                                    new ResultCallback<Status>() {
                                        @Override
                                        public void onResult(@NonNull Status status) {
                                            Log.d("Login", "Finally log-out");
                                            SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, 0).edit();
                                            editor.putString("username", null);
                                            editor.apply();
                                        }
                                    });
                        }
                    }

                    @Override
                    public void onConnectionSuspended(int i) {}
                    })
                .build();
        mGoogleApiClient.connect();
        mAuth = FirebaseAuth.getInstance();
        if (mAuth == null)
            Log.d("Firebase", "NULL");
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                final FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user == null) {
                    Log.d("Signing", "signed out:");
                }
            }
        };
    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
        mGoogleApiClient.connect();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("Signing", "on activityResult");
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("Signing", "on activityResult");
        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
            } else {
                Log.d("Fail", "Google Sign-in Failed");
            }
        }
    }

    private void firebaseAuthWithGoogle(final GoogleSignInAccount acct) {
        Log.d("Firebase", "firebaseAuthWithGoogle:" + acct.getId());

        final AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d("Complete", "signInWithCredential:onComplete:" + task.isSuccessful());
                        if (!task.isSuccessful()) {
                            Log.w("Sign-in", "signInWithCredential", task.getException());
                            Toast.makeText(LoginActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            final SharedPreferences sharedPref = getSharedPreferences(PREFS_NAME, 0);
                            final SharedPreferences.Editor editor = sharedPref.edit();
                            editor.putString("email", acct.getEmail());
                            editor.putString("token", acct.getIdToken());
                            final String url = acct.getPhotoUrl() == null ? "" : acct.getPhotoUrl().toString();
                            editor.putString("photo-uri", url);
                            editor.apply();
                            Log.d("Login", acct.getIdToken());
                            Server.signIn(LoginActivity.this, acct.getIdToken(), acct.getEmail(),
                                    new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    String username = response.optString("username");
                                    editor.putString("username", username);
                                    editor.apply();
                                    Intent myIntent = new Intent(getBaseContext(), DiscoveryActivity.class);
                                    myIntent.putExtra("token", acct.getIdToken());
                                    myIntent.putExtra("username", username);
                                    myIntent.putExtra("photo-uri", url);
                                    startActivity(myIntent);
                                    finish();
                                }
                            }, new ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    if (error.networkResponse == null) {
                                        Toast.makeText(LoginActivity.this, "Network Error", Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                    int response = error.networkResponse.statusCode;
                                    if (response == 464) {
                                        Intent myIntent = new Intent(getBaseContext(), RegisterActivity.class);
                                        myIntent.putExtra("email", acct.getEmail());
                                        myIntent.putExtra("token", acct.getIdToken());
                                        myIntent.putExtra("photo-uri", Objects.toString(acct.getPhotoUrl(), ""));
                                        startActivity(myIntent);
                                        finish();
                                    } else {
                                        Log.d("Network-Error", "" + response);
                                        Toast.makeText(LoginActivity.this, "Network Error", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        }
                    }
                });
    }

    private void signIn() {
        if (Server.isOffline(this)) {
            Toast.makeText(this, "No Internet Connection!", Toast.LENGTH_LONG).show();
            return;
        }
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        Log.d("Signing", "method signIn 2:");
        if (signInIntent == null)
            Log.d("Signing", "method signIn null:");
        startActivityForResult(signInIntent, RC_SIGN_IN);
        Log.d("Signing", "method signIn 3:");
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        // An unresolvable error has occurred and Google APIs (including Sign-In) will not
        // be available.
        Log.d("Fail", "onConnectionFailed:" + connectionResult);
        Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
    }
}


text:
import Common, { Hardfork } from '@ethereumjs/common';

const commonGenerator = network => {
  return Common.custom({
    chainId: network.type.chainID,
    defaultHardfork: Hardfork.London
  });
};

export default commonGenerator;


text:
Analyze the viewshed for an object (GeoElement) in a scene.

![Image of viewshed for geoelement](ViewshedGeoElement.jpg)

## Use case

A viewshed analysis is a type of visual analysis you can perform on a scene. The viewshed aims to answer the question 'What can I see from a given location?'. The output is an overlay with two different colors - one representing the visible areas (green) and the other representing the obstructed areas (red).

## How to use the sample

Tap to set a destination for the vehicle (a GeoElement). The vehicle will 'drive' towards the tapped location. The viewshed analysis will update as the vehicle moves.

## How it works

1. Create and show the scene, with an elevation source and a buildings layer.
2. Add a model (the `GeoElement`) to represent the observer (in this case, a tank).
    * Use a `SimpleRenderer` which has a heading expression set in the `GraphicsOverlay`. This way you can relate the viewshed's heading to the `GeoElement` object's heading.
3. Create a `GeoElementViewshed` with configuration for the viewshed analysis.
4. Add the viewshed to an `AnalysisOverlay` and add the overlay to the scene.
5. Configure the SceneView `CameraController` to orbit the vehicle.

## Relevant API

* AnalysisOverlay
* GeodeticDistanceResult
* GeoElementViewshed
* GeometryEngine.DistanceGeodetic
* ModelSceneSymbol
* OrbitGeoElementCameraController

## Offline data

This sample downloads the following items from ArcGIS Online automatically:

* [bradley_low_3ds.zip](https://www.arcgis.com/home/item.html?id=07d62a792ab6496d9b772a24efea45d0) - Model Scene Symbol for use in ArcGIS Runtime Samples

## About the data

This sample shows a [Johannesburg, South Africa Scene](https://www.arcgis.com/home/item.html?id=eb4dab9e61b24fe2919a0e6f7905321e) from ArcGIS Online. The sample uses a [Tank model scene symbol](http://www.arcgis.com/home/item.html?id=07d62a792ab6496d9b772a24efea45d0) hosted as an item on ArcGIS Online.

## Tags

3D, analysis, buildings, model, scene, viewshed, visibility analysis


text:
import logging

from collections import OrderedDict

log = logging.getLogger(__name__)

FRONTEND_ASSET_CONFIG_KEYS = {
    'name', 'build_script', 'asset_path'
}

def cms_register_frontend_asset(config, asset_name, asset_config):
    registry = config.registry

    if not hasattr(registry, 'cms_frontend_assets'):
        registry.cms_frontend_assets = OrderedDict()

    def register():
        log.info('===>>> Registering frontend asset: %s', asset_name)
        if asset_name not in registry.cms_frontend_assets:
            to_reg_config = {}

            for key in FRONTEND_ASSET_CONFIG_KEYS:
                to_reg_config[key] = asset_config.get(key, None)

            registry.cms_frontend_assets[asset_name] = to_reg_config

    config.action('amnesiacms_frontend_asset={}'.format(asset_name), register)

def cms_add_entity_resource(config, entity, resource):
    registry = config.registry

    if not hasattr(registry, 'cms_entity_resources'):
        registry.cms_entity_resources = OrderedDict()

    def register():
        log.info('===>>> Mapping %s to resource %s', entity, resource)
        registry.cms_entity_resources[entity] = resource

    config.action('amnesiacms_entity_resource={}'.format(entity), register)

def cms_add_resource_path(config, resource_cls, path, target_cls):
    registry = config.registry

    if not hasattr(registry, 'cms_resource_paths'):
        registry.cms_resource_paths = OrderedDict()

    def register():
        log.info('===>>> Adding resource path "%s" from %s to %s', path,
                 resource_cls, target_cls)
        if resource_cls not in registry.cms_resource_paths:
            registry.cms_resource_paths[resource_cls] = OrderedDict()
        registry.cms_resource_paths[resource_cls][path] = target_cls

    config.action('amnesiacms_resource_path={}{}'.format(resource_cls, path),
                  register)

def cms_get_resource(request, entity):
    cfg = request.registry.cms_entity_resources
    return cfg[type(entity)]


text:
                <button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">

                Toggle navigation

                </button>

{{infoMsgRootScope}}

{{errMsgRootScope}}

{{showSuccessMsgRootScope}}

                    {{displayApp}}

                            No Apps are connected

 0">

                               {{app.name}}

                             Settings for {{app.name}}

                    Account

                                Settings

                                Docs

                                Logout

 Logout


text:
using System.Collections;
using System.Collections.Generic;
using Igloo.Clinic.Domain;

namespace Igloo.Clinic.Services.Interfaces
{
    public interface IPatientService
    {
        IList<Patient> RetrievePatients(Doctor doctor);
    }
}


text:
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

    QString project_directory = "";
    QString getRobogenPath();

    static QString stringFromType(PART_TYPE tp);
    static PART_TYPE typeFromString(const QString& str);
    QJsonObject getRobotJsonObject();
    //QJsonObject getPartJsonObject(RobotPart* part);

public slots:
    void onProjectTreeSelect(QListWidgetItem*);
    void onProjectTreeAdd();
    void onProjectTreeRemove();

    //void loadSimulation();
    //void loadEvolution();

    void onPushSimulate();
    void onPushWebGL();
    void onPushAnalyze(bool user_activated = true);
    void onPushStop();
    void onFileChanged(QString filename);
    void onNewFileList(QStringList files);

    void evolveReadReady();
    void onEvolveFinished(int);

    void onFileEvent(const QString &);

    void onNewProject();
    void onOpenProject();
    bool onSaveProject();

    void onEvolve();

    void saveSimulation();
    void loadSimulation();

    void saveEvolution();
    void loadEvolution();

    void saveRobot();
    void loadRobot();

private slots:

    void onAddPart();
    void onRemovePart();
    void onRobotPartChange(int index);
    void onRobotFaceChange(int index);
    void onRobotPartNameChange(QString name);
    void onRobotRotationChange(int index);
    void onRobotParamLengthChange(double value);
    void onRobotParamRotationChange(int value);
    void onItemChange(QTreeWidgetItem *, QTreeWidgetItem *);

    void onRunSelect(QListWidgetItem* current);
    void onRunDeletePressed();
    void onRunItemDoubleClicked(QListWidgetItem *item);

    void onProjectConfigDoubleClicked(QListWidgetItem* item);
    void onLoadRobot();
    void loadRobotJson(const QString& filename);

    void onCustomRobotBrowse();
    void onCustomSimulationBrowse();
    void onCustomEvolutionBrowse();

    void onObstaclesBrowse();
    void onPositionsBrowse();
    void onLightsBrowse();

private:
    Ui::MainWindow *ui;

    QFileSystemWatcher *fs_watcher = nullptr;

    int n_generation;

    bool first_dir_change = true;
    bool run_dir_added = false;

    QProcess *process_server;
    QProcess *process_evolve;
    QProcess *process_simulate;

    QList<QProcess*> process_list;
    DirWatcher dir_watcher;

    SettingsWindow* settings_window = nullptr;

    ProjectConfiguration* current_config = nullptr;
    ProjectConfiguration* current_running_config = nullptr;

    LogWindow* log_window = nullptr;

    QString current_run_name = "";
    QString current_run_path = "";

    void writeEvolution();
    void writeSimulation();
    void writeRobot();

    void closeEvent(QCloseEvent* ev);

    // plotting
    QCustomPlot* plot = nullptr;
    QCPGraph* graph_best = nullptr;
    QCPGraph* graph_avg = nullptr;
    QCPGraph* graph_std_up = nullptr;
    QCPGraph* graph_std_down = nullptr;
};

#endif // MAINWINDOW_H


text:
C    Copyright(C) 2014-2017 National Technology & Engineering Solutions of
C    Sandia, LLC (NTESS).  Under the terms of Contract DE-NA0003525 with
C    NTESS, the U.S. Government retains certain rights in this software.
C
C    Redistribution and use in source and binary forms, with or without
C    modification, are permitted provided that the following conditions are
C    met:
C
C    * Redistributions of source code must retain the above copyright
C       notice, this list of conditions and the following disclaimer.
C
C    * Redistributions in binary form must reproduce the above
C      copyright notice, this list of conditions and the following
C      disclaimer in the documentation and/or other materials provided
C      with the distribution.
C
C    * Neither the name of NTESS nor the names of its
C      contributors may be used to endorse or promote products derived
C      from this software without specific prior written permission.
C
C    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
C    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
C    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
C    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
C    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
C    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
C    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
C    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
C    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
C    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
C    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
C

C $Id: rdmesh.f,v 1.1 1990/11/30 11:14:30 gdsjaar Exp $
C $Log: rdmesh.f,v $
C Revision 1.1  1990/11/30 11:14:30  gdsjaar
C Initial revision
C
C
CC* FILE: [.RENUM]RDMESH.FOR
CC* MODIFIED BY: TED BLACKER
CC* MODIFICATION DATE: 7/6/90
CC* MODIFICATION: COMPLETED HEADER INFORMATION
C
      SUBROUTINE RDMESH (NPNODE, NPELEM, NPNBC, NPSBC, NPREGN, MS, MR,
     &   NNUID, NNXK, IUNIT, NNN, KKK, IPART, LSTNBC, LSTSBC, NUID, XN,
     &   YN, NXK, MAT, MATMAP, NUMMAT, ISIDE, NLPS, IFLINE, ILLIST,
     &   LINKS, LINKR, IMAT, LINKB, JMAT, NNNBC, NNSBC, ERR)
C***********************************************************************
C
C  SUBROUTINE RDMESH = THE CURRENT MESH STORED ON DISK
C
C***********************************************************************
C
      DIMENSION IPART(3, NPREGN), ISIDE(MS), NLPS(MS), IFLINE(MS)
      DIMENSION ILLIST(MS*3), LINKS(2, MS), LINKB(2, MS), LINKR(2, MR)
      DIMENSION IMAT(MR), JMAT(MS)
C
      DIMENSION NUID(NNUID), XN(NPNODE), YN(NPNODE)
      DIMENSION NXK(NNXK, NPELEM), MAT(NPELEM)
C
      DIMENSION LSTNBC(NPNBC), LSTSBC(NPSBC)
      DIMENSION MATMAP(3, NPREGN)
C
      LOGICAL ERR, BAR, ADDLNK
C
      ERR = .FALSE.
C
C  READ THE MESH TAPE
C
      REWIND IUNIT
      NNN = 0
      KKK = 0
      NNNBC = 0
      NNSBC = 0
      ADDLNK = .FALSE.
      DO 100 I = 1, NPREGN
         IPART(1, I) = 0
         IPART(2, I) = 0
         IPART(3, I) = 0
  100 CONTINUE
C
      NUMMAT = 0
      DO 220 IR = 1, NPREGN
         READ(IUNIT, END = 230) KKKREG, NNNREG, NNBCRG, NSBCRG, KREG,
     &      BAR, M1
C
C  READ THE NODES
C
         N1 = NNN + 1
         NNN = NNN + NNNREG
         IF (NNNREG .GE. 1)READ(IUNIT, END = 230) (NUID(I), XN(I),
     &      YN(I), I = N1, NNN)
C
C  READ THE ELEMENTS
C
         K1 = KKK + 1
         IPART(1, IR) = KREG
         IPART(2, IR) = K1
         KKK = KKK + KKKREG
         IPART(3, IR) = KKK
         READ(IUNIT, END = 230) ((NXK(I, K), I = 1, 4), K = K1, KKK)
C
C  ZERO THE MIDSIDE NODE LOCATIONS IN THE NXK ARRAY
C
         DO 120 I = 5, NNXK
            DO 110 K = K1, KKK
               NXK(I, K) = 0
  110       CONTINUE
  120    CONTINUE
C
C  SET UP THE MATERIAL ARRAY AND MAXIMUM NUMBER OF MATERIALS
C
         IF (BAR) THEN
            CALL LTSORT (MS, LINKB, KREG, IPNTR, ADDLNK)
            KMAT = ABS (JMAT(IPNTR))
         ELSE
            CALL LTSORT (MR, LINKR, KREG, IPNTR, ADDLNK)
            KMAT = IMAT(IPNTR)
         END IF
C
C  SEE IF ALTERNATING MATERIALS WITHIN A REGION ARE ENABLED
C
         IF (KMAT .LT. 0) THEN
            CALL LTSORT (MS, LINKS, IABS(KMAT), JPNTR, ADDLNK)
            IF ((JPNTR .GT. 0) .AND. (NLPS(JPNTR) .GE. 2)) THEN
C
C  ADD MATERIAL NUMBER BY ROW OF ELEMENTS
C
               MATPNT = IFLINE(JPNTR)
               DO 140 K = K1, KKK - M1 + 1, M1
                  DO 130 L = K, K + M1 - 1
                     MAT(L) = ILLIST(MATPNT)
  130             CONTINUE
C
C  UPDATE THE POINTER TO THE NEXT MATERIAL
C
                  MATPNT = MATPNT + 1
                  IF (MATPNT .GT. IFLINE(JPNTR) + NLPS(JPNTR) - 1)
     &               MATPNT = IFLINE(JPNTR)
  140          CONTINUE
            ELSE
               WRITE(*, 10000) IABS(KMAT), ISIDE(JPNTR)
            END IF
C
C  PUT THE NEW MATERIALS INTO THE MATERIAL ARRAYS
C
            DO 170 MATPNT = IFLINE(JPNTR),
     &         IFLINE(JPNTR) + NLPS(JPNTR) - 1
               DO 150 K = 1, NUMMAT
                  IF (MATMAP(1, K) .EQ. ILLIST(MATPNT)) GO TO 160
  150          CONTINUE
               NUMMAT = NUMMAT + 1
               MATMAP(1, NUMMAT) = ILLIST(MATPNT)
  160          CONTINUE
  170       CONTINUE
         ELSE
C
C  JUST INPUT THE ONE MATERIAL
C
            DO 180 K = K1, KKK
               MAT(K) = KMAT
  180       CONTINUE
            DO 190 K = 1, NUMMAT
               IF (MATMAP(1, K) .EQ. KMAT) GO TO 200
  190       CONTINUE
            NUMMAT = NUMMAT + 1
            MATMAP(1, NUMMAT) = KMAT
         END IF
  200    CONTINUE
C
C  READ THE NODAL BOUNDARY CONDITIONS
C
         NNNBC1 = NNNBC + 1
         NNNBC = NNNBC + NNBCRG
         IF (NNBCRG .GE. 1) READ(IUNIT)(LSTNBC(I), I = NNNBC1, NNNBC)
C
C  READ THE SIDE BOUNDARY CONDITIONS
C
         NNSBC1 = NNSBC + 1
         NNSBC = NNSBC + NSBCRG
         IF (NSBCRG .GE. 1) THEN
            READ(IUNIT)(LSTSBC(I), I = NNSBC1, NNSBC)
            DO 210 I = NNSBC1 + 1, NNSBC, 3
               LSTSBC(I) = LSTSBC(I) + K1 - 1
  210       CONTINUE
         END IF
  220 CONTINUE
C
      RETURN
C
  230 CONTINUE
      CALL MESAGE ('PREMATURE END OF FILE ON MESH READ')
      CALL MESAGE ('CHECK MESH PROCESSING OUTPUT TO DETERMINE')
      CALL MESAGE ('INCOMPLETE MESH DESCRIPTION')
      ERR = .TRUE.
      NNN = 0
      KKK = 0
      RETURN
C
10000 FORMAT(' THE ALTERNATING MATERIAL NUMBERS FOR REGION(S) WITH', /,
     &   ' NEGATIVE MATERIAL NUMBER:', I5, ' DO NOT CORRESPOND TO A',/,
     &   ' VALID SIDE NUMBER:', I5, ' WITH AT LEAST TWO LINES.')
C
      END


text:
package org.elasticsearch.client;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScheme;
import org.apache.http.impl.client.TargetAuthenticationStrategy;
import org.apache.http.protocol.HttpContext;

/**
 * An {@link org.apache.http.client.AuthenticationStrategy} implementation that does not perform
 * any special handling if authentication fails.
 * The default handler in Apache HTTP client mimics standard browser behaviour of clearing authentication
 * credentials if it receives a 401 response from the server. While this can be useful for browser, it is
 * rarely the desired behaviour with the Elasticsearch REST API.
 * If the code using the REST client has configured credentials for the REST API, then we can and should
 * assume that this is intentional, and those credentials represent the best possible authentication
 * mechanism to the Elasticsearch node.
 * If we receive a 401 status, a probably cause is that the authentication mechanism in place was unable
 * to perform the requisite password checks (the node has not yet recovered its state, or an external
 * authentication provider was unavailable).
 * If this occurs, then the desired behaviour is for the Rest client to retry with the same credentials
 * (rather than trying with no credentials, or expecting the calling code to provide alternate credentials).
 */
final class PersistentCredentialsAuthenticationStrategy extends TargetAuthenticationStrategy {

    private final Log logger = LogFactory.getLog(PersistentCredentialsAuthenticationStrategy.class);

    @Override
    public void authFailed(HttpHost host, AuthScheme authScheme, HttpContext context) {
        if (logger.isDebugEnabled()) {
            logger.debug("Authentication to " + host + " failed (scheme: " + authScheme.getSchemeName()
                + "). Preserving credentials for next request");
        }
        // Do nothing.
        // The superclass implementation of method will clear the credentials from the cache, but we don't
    }
}


text:
package cn.lxz.sweb.velocity;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;
import java.io.IOException;
import java.io.Writer;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
 *
 * 输出附加版本信息的 css 标记
 *
 * 示例:
 *      #css("/css/upload.css") => <link href="/css/upload.css?v=20151020180705" rel="stylesheet"/>
 */
public class CssDirective extends Directive {

	private static final DateTimeFormatter format=DateTimeFormatter.ofPattern("yyyyMMddHHmm");

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

    @Override
    public int getType() {
        return LINE;
    }

    @Override
    public boolean render(InternalContextAdapter internalContextAdapter, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
        String url = DirectiveHelper.getParameter(internalContextAdapter, node, 0);
        String tag = String.format("<link href=\"%s?v=%s\" rel=\"stylesheet\"/>", url, getVer());
        writer.write(tag);
        return true;
    }

    public static long getVer(){
    	LocalDateTime now=LocalDateTime.now();
    	return Long.valueOf(format.format(now));
    }
}


text:
package org.oscm.internal.types.exception.beans;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

import org.oscm.internal.types.exception.SAMLRedirectURLException.ReasonEnum;

/**
 * @author roderus
 *
 */
/**
 * Bean for JAX-WS exception serialization, specific for
 * {@link SAMLRedirectURLExceptionBean}.
 */
@XmlRootElement(name = "SAMLRedirectURLExceptionBean")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class SAMLRedirectURLExceptionBean extends ApplicationExceptionBean {

    private static final long serialVersionUID = -8340191524480039110L;

    private ReasonEnum reason;

    /**
     * Default constructor.
     */
    public SAMLRedirectURLExceptionBean() {
        super();
    }

    /**
     * Instantiates a SAMLRedirectURLExceptionBean based on the
     * specified ApplicationExceptionBean and sets the given
     * reason.
     *
     * @param sup
     *            the ApplicationExceptionBean to use as the base
     * @param reason
     *            the reason for the exception
     */
    public SAMLRedirectURLExceptionBean(ApplicationExceptionBean sup,
            ReasonEnum reason) {
        super(sup);
        setReason(reason);
    }

    /**
     * Returns the reason for the exception.
     *
     * @return the reason
     */
    public ReasonEnum getReason() {
        return reason;
    }

    /**
     * Sets the reason for the exception.
     *
     * @param reason
     *            the reason
     */
    public void setReason(ReasonEnum reason) {
        this.reason = reason;
    }

}


text:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:gravity="center"
    android:padding="@dimen/widget_margin"
    android:background="@drawable/widget_background">

    <LinearLayout
        android:layout_weight="1"
        android:orientation="vertical"
        android:layout_width="0dp"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical">

            <TextView
                android:id="@+id/dolar_today"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:contentDescription="@string/dolartoday"
                android:fontFamily="@font/titillium_web"
                android:text="@string/dolartoday"
                android:textColor="@color/font_primary"
                android:textSize="16sp"/>

            <TextView
                android:id="@+id/dolar_today_text"
                android:layout_weight="1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:contentDescription="@string/dolartoday"
                android:gravity="end"
                android:fontFamily="@font/titillium_web"
                android:textColor="@color/font_primary"
                android:textSize="16sp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical">

            <TextView
                android:id="@+id/localbitcoin"
                android:layout_weight="1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/localbitcoins"
                android:contentDescription="@string/localbitcoins"
                android:fontFamily="@font/titillium_web"
                android:textColor="@color/font_primary"
                android:textSize="16sp"/>

            <TextView
                android:id="@+id/localbitcoin_text"
                android:layout_weight="1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:contentDescription="@string/localbitcoins"
                android:gravity="end"
                android:fontFamily="@font/titillium_web"
                android:textColor="@color/font_primary"
                android:textSize="16sp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical">

            <TextView
                android:id="@+id/airtm"
                android:layout_weight="1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/airtm"
                android:contentDescription="@string/airtm"
                android:fontFamily="@font/titillium_web"
                android:textColor="@color/font_primary"
                android:textSize="16sp"/>

            <TextView
                android:id="@+id/airtm_text"
                android:layout_weight="1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:contentDescription="@string/usd"
                android:gravity="end"
                android:fontFamily="@font/titillium_web"
                android:textColor="@color/font_primary"
                android:textSize="16sp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical">

            <TextView
                android:id="@+id/usd"
                android:layout_weight="1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/usd"
                android:contentDescription="@string/usd"
                android:fontFamily="@font/titillium_web"
                android:textColor="@color/font_primary"
                android:textSize="16sp"/>

            <TextView
                android:id="@+id/usd_text"
                android:layout_weight="1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:contentDescription="@string/usd"
                android:gravity="end"
                android:fontFamily="@font/titillium_web"
                android:textColor="@color/font_primary"
                android:textSize="16sp" />
        </LinearLayout>

    </LinearLayout>

    <ImageView
        android:layout_weight=".1"
        android:id="@+id/refresh"
        android:clickable="true"
        android:focusable="true"
        android:src="@drawable/ic_refresh_white_24dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>


text:
namespace rx
{
enum class GlslangError
{
    InvalidShader,
    InvalidSpirv,
};

constexpr gl::ShaderMap<const char *> kDefaultUniformNames = {
    {gl::ShaderType::Vertex, sh::vk::kDefaultUniformsNameVS},
    {gl::ShaderType::TessControl, sh::vk::kDefaultUniformsNameTCS},
    {gl::ShaderType::TessEvaluation, sh::vk::kDefaultUniformsNameTES},
    {gl::ShaderType::Geometry, sh::vk::kDefaultUniformsNameGS},
    {gl::ShaderType::Fragment, sh::vk::kDefaultUniformsNameFS},
    {gl::ShaderType::Compute, sh::vk::kDefaultUniformsNameCS},
};

struct GlslangProgramInterfaceInfo
{
    // Uniforms set index:
    uint32_t uniformsAndXfbDescriptorSetIndex;
    uint32_t currentUniformBindingIndex;
    // Textures set index:
    uint32_t textureDescriptorSetIndex;
    uint32_t currentTextureBindingIndex;
    // Other shader resources set index:
    uint32_t shaderResourceDescriptorSetIndex;
    uint32_t currentShaderResourceBindingIndex;
    // ANGLE driver uniforms set index:
    uint32_t driverUniformsDescriptorSetIndex;

    uint32_t locationsUsedForXfbExtension;
};

struct GlslangSourceOptions
{
    bool supportsTransformFeedbackExtension = false;
    bool supportsTransformFeedbackEmulation = false;
    bool enableTransformFeedbackEmulation   = false;
    bool emulateBresenhamLines              = false;
};

struct GlslangSpirvOptions
{
    gl::ShaderType shaderType                 = gl::ShaderType::InvalidEnum;
    SurfaceRotation preRotation               = SurfaceRotation::Identity;
    bool negativeViewportSupported            = false;
    bool transformPositionToVulkanClipSpace   = false;
    bool removeEarlyFragmentTestsOptimization = false;
    bool removeDebugInfo                      = false;
    bool isTransformFeedbackStage             = false;
    bool isTransformFeedbackEmulated          = false;
};

using GlslangErrorCallback = std::function<angle::Result(GlslangError)>;

struct ShaderInterfaceVariableXfbInfo
{
    static constexpr uint32_t kInvalid = std::numeric_limits<uint32_t>::max();

    // Used by both extension and emulation
    uint32_t buffer = kInvalid;
    uint32_t offset = kInvalid;
    uint32_t stride = kInvalid;

    // Used only by emulation (array index support is missing from VK_EXT_transform_feedback)
    uint32_t arraySize   = kInvalid;
    uint32_t columnCount = kInvalid;
    uint32_t rowCount    = kInvalid;
    uint32_t arrayIndex  = kInvalid;
    GLenum componentType = GL_FLOAT;
    // If empty, the whole array is captured.  Otherwise only the specified members are captured.
    std::vector<ShaderInterfaceVariableXfbInfo> arrayElements;
};

// Information for each shader interface variable.  Not all fields are relevant to each shader
// interface variable.  For example opaque uniforms require a set and binding index, while vertex
// attributes require a location.
struct ShaderInterfaceVariableInfo
{
    ShaderInterfaceVariableInfo();

    static constexpr uint32_t kInvalid = std::numeric_limits<uint32_t>::max();

    // Used for interface blocks and opaque uniforms.
    uint32_t descriptorSet = kInvalid;
    uint32_t binding       = kInvalid;
    // Used for vertex attributes, fragment shader outputs and varyings.  There could be different
    // variables that share the same name, such as a vertex attribute and a fragment output.  They
    // will share this object since they have the same name, but will find possibly different
    // locations in their respective slots.
    uint32_t location  = kInvalid;
    uint32_t component = kInvalid;
    uint32_t index     = kInvalid;
    // The stages this shader interface variable is active.
    gl::ShaderBitSet activeStages;
    // Used for transform feedback extension to decorate vertex shader output.
    ShaderInterfaceVariableXfbInfo xfb;
    std::vector<ShaderInterfaceVariableXfbInfo> fieldXfb;
    // Indicates that the precision needs to be modified in the generated SPIR-V
    // to support only transferring medium precision data when there's a precision
    // mismatch between the shaders. For example, either the VS casts highp->mediump
    // or the FS casts mediump->highp.
    bool useRelaxedPrecision = false;
    // Indicate if varying is input or output, or both (in case of for example gl_Position in a
    // geometry shader)
    bool varyingIsInput  = false;
    bool varyingIsOutput = false;
    // For vertex attributes, this is the number of components / locations.  These are used by the
    // vertex attribute aliasing transformation only.
    uint8_t attributeComponentCount = 0;
    uint8_t attributeLocationCount  = 0;
};

// TODO: http://anglebug.com/4524: Need a different hash key than a string, since that's slow to
// calculate.
class ShaderInterfaceVariableInfoMap final : angle::NonCopyable
{
  public:
    ShaderInterfaceVariableInfoMap();
    ~ShaderInterfaceVariableInfoMap();

    void clear();
    bool contains(gl::ShaderType shaderType, const std::string &variableName) const;
    const ShaderInterfaceVariableInfo &get(gl::ShaderType shaderType,
                                           const std::string &variableName) const;
    ShaderInterfaceVariableInfo &get(gl::ShaderType shaderType, const std::string &variableName);
    ShaderInterfaceVariableInfo &add(gl::ShaderType shaderType, const std::string &variableName);
    ShaderInterfaceVariableInfo &addOrGet(gl::ShaderType shaderType,
                                          const std::string &variableName);
    size_t variableCount(gl::ShaderType shaderType) const { return mData[shaderType].size(); }

    using VariableNameToInfoMap = angle::HashMap<std::string, ShaderInterfaceVariableInfo>;

    class Iterator final
    {
      public:
        Iterator(VariableNameToInfoMap::const_iterator beginIt,
                 VariableNameToInfoMap::const_iterator endIt)
            : mBeginIt(beginIt), mEndIt(endIt)
        {}
        VariableNameToInfoMap::const_iterator begin() { return mBeginIt; }
        VariableNameToInfoMap::const_iterator end() { return mEndIt; }

      private:
        VariableNameToInfoMap::const_iterator mBeginIt;
        VariableNameToInfoMap::const_iterator mEndIt;
    };

    Iterator getIterator(gl::ShaderType shaderType) const;

  private:
    gl::ShaderMap<VariableNameToInfoMap> mData;
};

void GlslangInitialize();
void GlslangRelease();

bool GetImageNameWithoutIndices(std::string *name);

// Get the mapped sampler name after the source is transformed by GlslangGetShaderSource()
std::string GlslangGetMappedSamplerName(const std::string &originalName);
std::string GetXfbBufferName(const uint32_t bufferIndex);

void GlslangAssignLocations(const GlslangSourceOptions &options,
                            const gl::ProgramState &programState,
                            const gl::ProgramVaryingPacking &varyingPacking,
                            const gl::ShaderType shaderType,
                            const gl::ShaderType frontShaderType,
                            bool isTransformFeedbackStage,
                            GlslangProgramInterfaceInfo *programInterfaceInfo,
                            ShaderInterfaceVariableInfoMap *variableInfoMapOut);

// Transform the source to include actual binding points for various shader resources (textures,
// buffers, xfb, etc).  For some variables, these values are instead output to the variableInfoMap
// to be set during a SPIR-V transformation.  This is a transitory step towards moving all variables
// to this map, at which point GlslangGetShaderSpirvCode will also be called by this function.
void GlslangGetShaderSource(const GlslangSourceOptions &options,
                            const gl::ProgramState &programState,
                            const gl::ProgramLinkedResources &resources,
                            GlslangProgramInterfaceInfo *programInterfaceInfo,
                            gl::ShaderMap<std::string> *shaderSourcesOut,
                            ShaderInterfaceVariableInfoMap *variableInfoMapOut);

angle::Result GlslangTransformSpirvCode(const GlslangErrorCallback &callback,
                                        const GlslangSpirvOptions &options,
                                        const ShaderInterfaceVariableInfoMap &variableInfoMap,
                                        const angle::spirv::Blob &initialSpirvBlob,
                                        angle::spirv::Blob *spirvBlobOut);

angle::Result GlslangGetShaderSpirvCode(const GlslangErrorCallback &callback,
                                        const gl::ShaderBitSet &linkedShaderStages,
                                        const gl::Caps &glCaps,
                                        const gl::ShaderMap<std::string> &shaderSources,
                                        gl::ShaderMap<angle::spirv::Blob> *spirvBlobsOut);

}  // namespace rx

#endif  // LIBANGLE_RENDERER_GLSLANG_WRAPPER_UTILS_H_


text:
using System;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using Android.Animation;
using Android.Content.Res;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Views;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using XamEffects;
using XamEffects.Droid;
using XamEffects.Droid.GestureCollectors;
using Color = Android.Graphics.Color;
using ListView = Android.Widget.ListView;
using ScrollView = Android.Widget.ScrollView;
using View = Android.Views.View;

[assembly: ExportEffect(typeof(TouchEffectPlatform), nameof(TouchEffect))]

namespace XamEffects.Droid {
    public class TouchEffectPlatform : PlatformEffect {
        public bool EnableRipple => Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop;
        public bool IsDisposed => (Container as IVisualElementRenderer)?.Element == null;
        public View View => Control ?? Container;

        Color _color;
        byte _alpha;
        RippleDrawable _ripple;
        FrameLayout _viewOverlay;
        ObjectAnimator _animator;

        public static void Init() {
        }

        protected override void OnAttached() {
            if (Control is ListView || Control is ScrollView) {
                return;
            }

            View.Clickable = true;
            View.LongClickable = true;
            _viewOverlay = new FrameLayout(Container.Context) {
                LayoutParameters = new ViewGroup.LayoutParams(-1, -1),
                Clickable = false,
                Focusable = false,
            };
            Container.LayoutChange += ViewOnLayoutChange;

            if (EnableRipple)
                _viewOverlay.Background = CreateRipple(_color);

            SetEffectColor();
            TouchCollector.Add(View, OnTouch);

            Container.AddView(_viewOverlay);
            _viewOverlay.BringToFront();
        }

        protected override void OnDetached() {
            if (IsDisposed) return;

            Container.RemoveView(_viewOverlay);
            _viewOverlay.Pressed = false;
            _viewOverlay.Foreground = null;
            _viewOverlay.Dispose();
            Container.LayoutChange -= ViewOnLayoutChange;

            if (EnableRipple)
                _ripple?.Dispose();

            TouchCollector.Delete(View, OnTouch);
        }

        protected override void OnElementPropertyChanged(PropertyChangedEventArgs e) {
            base.OnElementPropertyChanged(e);

            if (e.PropertyName == TouchEffect.ColorProperty.PropertyName) {
                SetEffectColor();
            }
        }

        void SetEffectColor() {
            var color = TouchEffect.GetColor(Element);
            if (color == Xamarin.Forms.Color.Default) {
                return;
            }

            _color = color.ToAndroid();
            _alpha = _color.A == 255 ? (byte)80 : _color.A;

            if (EnableRipple) {
                _ripple.SetColor(GetPressedColorSelector(_color));
            }
        }

        void OnTouch(View.TouchEventArgs args) {
            switch (args.Event.Action) {
                case MotionEventActions.Down:
                    if (EnableRipple)
                        ForceStartRipple(args.Event.GetX(), args.Event.GetY());
                    else
                        BringLayer();

                    break;

                case MotionEventActions.Up:
                case MotionEventActions.Cancel:
                    if (IsDisposed) return;

                    if (EnableRipple)
                        ForceEndRipple();
                    else
                        TapAnimation(250, _alpha, 0);

                    break;
            }
        }

        void ViewOnLayoutChange(object sender, View.LayoutChangeEventArgs layoutChangeEventArgs) {
            var group = (ViewGroup)sender;
            if (group == null || IsDisposed) return;
            _viewOverlay.Right = group.Width;
            _viewOverlay.Bottom = group.Height;
        }

        #region Ripple

        RippleDrawable CreateRipple(Color color) {
            if (Element is Layout) {
                var mask = new ColorDrawable(Color.White);
                return _ripple = new RippleDrawable(GetPressedColorSelector(color), null, mask);
            }

            var back = View.Background;
            if (back == null) {
                var mask = new ColorDrawable(Color.White);
                return _ripple = new RippleDrawable(GetPressedColorSelector(color), null, mask);
            }

            if (back is RippleDrawable) {
                _ripple = (RippleDrawable)back.GetConstantState().NewDrawable();
                _ripple.SetColor(GetPressedColorSelector(color));

                return _ripple;
            }

            return _ripple = new RippleDrawable(GetPressedColorSelector(color), back, null);
        }

        static ColorStateList GetPressedColorSelector(int pressedColor) {
            return new ColorStateList(
                new[] { new int[] { } },
                new[] { pressedColor, });
        }

        void ForceStartRipple(float x, float y) {
            if (IsDisposed || !(_viewOverlay.Background is RippleDrawable bc)) return;

            _viewOverlay.BringToFront();
            bc.SetHotspot(x, y);
            _viewOverlay.Pressed = true;
        }

        void ForceEndRipple() {
            if (IsDisposed) return;

            _viewOverlay.Pressed = false;
        }

        #endregion

        #region Overlay

        void BringLayer() {
            if (IsDisposed)
                return;

            ClearAnimation();

            _viewOverlay.BringToFront();
            var color = _color;
            color.A = _alpha;
            _viewOverlay.SetBackgroundColor(color);
        }

        void TapAnimation(long duration, byte startAlpha, byte endAlpha) {
            if (IsDisposed)
                return;

            _viewOverlay.BringToFront();

            var start = _color;
            var end = _color;
            start.A = startAlpha;
            end.A = endAlpha;

            ClearAnimation();
            _animator = ObjectAnimator.OfObject(_viewOverlay,
                "BackgroundColor",
                new ArgbEvaluator(),
                start.ToArgb(),
                end.ToArgb());
            _animator.SetDuration(duration);
            _animator.RepeatCount = 0;
            _animator.RepeatMode = ValueAnimatorRepeatMode.Restart;
            _animator.Start();
            _animator.AnimationEnd += AnimationOnAnimationEnd;
        }

        void AnimationOnAnimationEnd(object sender, EventArgs eventArgs) {
            if (IsDisposed) return;

            ClearAnimation();
        }

        void ClearAnimation() {
            if (_animator == null) return;
            _animator.AnimationEnd -= AnimationOnAnimationEnd;
            _animator.Cancel();
            _animator.Dispose();
            _animator = null;
        }

        #endregion
    }
}


text:
using System;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Microsoft.Win32.SafeHandles;
using MS.Win32;

namespace MS.Internal.AutomationProxies
{
    class ThemePart: IDisposable
    {
        // ------------------------------------------------------
        //
        //  Constructors
        //
        //------------------------------------------------------

        #region Constructors

        internal ThemePart (IntPtr hwnd, string sClass)
        {
            if (Environment.OSVersion.Version.Major >= 5)
            {
                _hTheme = new SafeThemeHandle(OpenThemeData(hwnd, sClass), false);
            }
            else
            {
                _hTheme = new SafeThemeHandle(IntPtr.Zero, false);
            }
        }

        public void Dispose ()
        {
            _hTheme.Dispose();
        }

        #endregion

        //------------------------------------------------------
        //
        //  Internal Methods
        //
        //------------------------------------------------------

        #region Internal Methods

        // Retreive the dimension of of UI element
        internal NativeMethods.SIZE Size (int iPartId, int iStateId)
        {
            bool fSuccess = false;
            // Default is (0, 0)
            NativeMethods.SIZE size = new NativeMethods.SIZE(0, 0);

            if (!_hTheme.IsInvalid)
            {
                unsafe
                {
                    fSuccess = GetThemePartSize(_hTheme, IntPtr.Zero, iPartId, iStateId, IntPtr.Zero, (int)THEMESIZE.TS_TRUE, &size) == IntPtr.Zero;
                }

            }

            // Falls back uses GetSystemMetrics
            if (!fSuccess)
            {
                // dangerous construct, the iPartId might collide.
                // When entering an entry, make sure that the ID is not previously used.
                // If it is the case, then an extra parameter needs to be added to this method
                switch (iPartId)
                {
                    case (int) STATUSPARTS.SP_GRIPPER:
                        size.cx = UnsafeNativeMethods.GetSystemMetrics (NativeMethods.SM_CXSIZE);
                        size.cy = UnsafeNativeMethods.GetSystemMetrics (NativeMethods.SM_CXSIZE);
                        break;

                    case (int)SCROLLBARPARTS.SBP_SIZEBOX:
                        size.cx = UnsafeNativeMethods.GetSystemMetrics(NativeMethods.SM_CXVSCROLL);
                        size.cy = UnsafeNativeMethods.GetSystemMetrics(NativeMethods.SM_CYHSCROLL);
                        break;

                    case (int)SCROLLBARPARTS.SBP_ARROWBTN:
                        size.cx = UnsafeNativeMethods.GetSystemMetrics(NativeMethods.SM_CXHSCROLL);
                        size.cy = UnsafeNativeMethods.GetSystemMetrics(NativeMethods.SM_CYVSCROLL);
                        break;

                    case (int) WINDOWPARTS.WP_MINBUTTON :
                    case (int) WINDOWPARTS.WP_MAXBUTTON :
                    case (int) WINDOWPARTS.WP_CLOSEBUTTON :
                    case (int) WINDOWPARTS.WP_HELPBUTTON :
                        size.cx = UnsafeNativeMethods.GetSystemMetrics (NativeMethods.SM_CXSIZE);
                        size.cy = UnsafeNativeMethods.GetSystemMetrics (NativeMethods.SM_CXSIZE);
                        break;

                    default:
                        System.Diagnostics.Debug.Assert (false, "Unsupport Type");
                        break;
                }
            }

            return size;
        }

        #endregion

        //------------------------------------------------------
        //
        //  Internal Fields
        //
        //------------------------------------------------------

        #region Internal Fields

        internal enum WINDOWPARTS
        {
            WP_CAPTION = 1,
            WP_SMALLCAPTION = 2,
            WP_MINCAPTION = 3,
            WP_SMALLMINCAPTION = 4,
            WP_MAXCAPTION = 5,
            WP_SMALLMAXCAPTION = 6,
            WP_FRAMELEFT = 7,
            WP_FRAMERIGHT = 8,
            WP_FRAMEBOTTOM = 9,
            WP_SMALLFRAMELEFT = 10,
            WP_SMALLFRAMERIGHT = 11,
            WP_SMALLFRAMEBOTTOM = 12,
            WP_SYSBUTTON = 13,
            WP_MDISYSBUTTON = 14,
            WP_MINBUTTON = 15,
            WP_MDIMINBUTTON = 16,
            WP_MAXBUTTON = 17,
            WP_CLOSEBUTTON = 18,
            WP_SMALLCLOSEBUTTON = 19,
            WP_MDICLOSEBUTTON = 20,
            WP_RESTOREBUTTON = 21,
            WP_MDIRESTOREBUTTON = 22,
            WP_HELPBUTTON = 23,
            WP_MDIHELPBUTTON = 24,
            WP_HORZSCROLL = 25,
            WP_HORZTHUMB = 26,
            WP_VERTSCROLL = 27,
            WP_VERTTHUMB = 28,
            WP_DIALOG = 29,
            WP_CAPTIONSIZINGTEMPLATE = 30,
            WP_SMALLCAPTIONSIZINGTEMPLATE = 31,
            WP_FRAMELEFTSIZINGTEMPLATE = 32,
            WP_SMALLFRAMELEFTSIZINGTEMPLATE = 33,
            WP_FRAMERIGHTSIZINGTEMPLATE = 34,
            WP_SMALLFRAMERIGHTSIZINGTEMPLATE = 35,
            WP_FRAMEBOTTOMSIZINGTEMPLATE = 36,
            WP_SMALLFRAMEBOTTOMSIZINGTEMPLATE = 37,
        };
        //
        internal enum MINBUTTONSTATES
        {
            MINBS_NORMAL = 1,
            MINBS_HOT = 2,
            MINBS_PUSHED = 3,
            MINBS_DISABLED = 4,
        };

        internal enum SCROLLBARPARTS
        {
            SBP_ARROWBTN = 1,
            SBP_THUMBBTNHORZ = 2,
            SBP_THUMBBTNVERT = 3,
            SBP_LOWERTRACKHORZ = 4,
            SBP_UPPERTRACKHORZ = 5,
            SBP_LOWERTRACKVERT = 6,
            SBP_UPPERTRACKVERT = 7,
            SBP_GRIPPERHORZ = 8,
            SBP_GRIPPERVERT = 9,
            SBP_SIZEBOX = 10,
        };

        internal enum STATUSPARTS
        {
            SP_PANE = 1,
            SP_GRIPPERPANE = 2,
            SP_GRIPPER = 3,
        };

        enum THEMESIZE
        {
            TS_MIN,             // minimum size
            TS_TRUE,            // size without stretching
            TS_DRAW,            // size that theme mgr will use to draw part
        };

        #endregion

        //------------------------------------------------------
        //
        //  Private Methods
        //
        //------------------------------------------------------

        #region Private Methods

        [DllImport ("UxTheme.dll", CharSet = CharSet.Auto)]
        private static unsafe extern IntPtr GetThemePartSize(SafeThemeHandle hTheme, IntPtr hdc, int iPartId, int iStateId, IntPtr prc, int eSize, NativeMethods.SIZE* psz);

        [DllImport ("UxTheme.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr OpenThemeData(IntPtr hwnd, [MarshalAs(UnmanagedType.LPWStr)]string s);

        #endregion

        //------------------------------------------------------
        //
        //  Private Fields
        //
        //------------------------------------------------------

        #region Private Fields

        // cached Value. Will never be initialize elsewhere if OS == Win98
        private SafeThemeHandle _hTheme;

        #endregion

    }
}


text:
INSTALL
========

1. Read over my [Mac Bootstrap Instructions](https://github.com/frankcarey/dotfiles/blob/master/bootstrap.md) to make sure that you have everything installed. I use this when setting up or reinstalling a new mac.
2. Clone this repo to ~/.dotfiles (don't forget to grab the submodules)
    git clone --recursive git@github.com:frankcarey/dotfiles.git
3. ln -s .dotfiles/.zshrc . (repeat for each dotfile you want to use.. @TODO Script this)

install jshint
------------
npm install jshint -g