text:
.class Landroid/widget/Toolbar$1;
.super Ljava/lang/Object;
.source "Toolbar.java"

# interfaces
.implements Landroid/widget/ActionMenuView$OnMenuItemClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/widget/Toolbar;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/widget/Toolbar;

# direct methods
.method constructor <init>(Landroid/widget/Toolbar;)V
    .locals 0
    .param p1, "this$0"    # Landroid/widget/Toolbar;

    .prologue
    .line 158
    iput-object p1, p0, Landroid/widget/Toolbar$1;->this$0:Landroid/widget/Toolbar;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onMenuItemClick(Landroid/view/MenuItem;)Z
    .locals 1
    .param p1, "item"    # Landroid/view/MenuItem;

    .prologue
    .line 161
    iget-object v0, p0, Landroid/widget/Toolbar$1;->this$0:Landroid/widget/Toolbar;

    invoke-static {v0}, Landroid/widget/Toolbar;->-get2(Landroid/widget/Toolbar;)Landroid/widget/Toolbar$OnMenuItemClickListener;

    move-result-object v0

    if-eqz v0, :cond_0

    .line 162
    iget-object v0, p0, Landroid/widget/Toolbar$1;->this$0:Landroid/widget/Toolbar;

    invoke-static {v0}, Landroid/widget/Toolbar;->-get2(Landroid/widget/Toolbar;)Landroid/widget/Toolbar$OnMenuItemClickListener;

    move-result-object v0

    invoke-interface {v0, p1}, Landroid/widget/Toolbar$OnMenuItemClickListener;->onMenuItemClick(Landroid/view/MenuItem;)Z

    move-result v0

    return v0

    .line 164
    :cond_0
    const/4 v0, 0x0

    return v0
.end method


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Languages.Core.Text;

namespace Microsoft.Languages.Core.Tokens {
    [DebuggerDisplay("Count={Count}")]
    public sealed class TokenBraceCounter<T> where T : ITextRange {
        T _openBrace1;
        T _closeBrace1;
        T _openBrace2;
        T _closeBrace2;

        private Stack<T> _braces1 = new Stack<T>();
        private Stack<T> _braces2;
        private IComparer<T> _comparer;

        public TokenBraceCounter(T openCurlyBrace, T closeCurlyBrace, IComparer<T> comparer) :
            this(openCurlyBrace, closeCurlyBrace, default(T), default(T), comparer) {
        }

        public TokenBraceCounter(T openBrace1, T closeBrace1, T openBrace2, T closeBrace2, IComparer<T> comparer) {
            _openBrace1 = openBrace1;
            _closeBrace1 = closeBrace1;
            _comparer = comparer;

            if (openBrace2 != null) {
                _braces2 = new Stack<T>();
                _openBrace2 = openBrace2;
                _closeBrace2 = closeBrace2;
            }
        }

        public int Count {
            get { return _braces1.Count; }
        }

        public bool CountBrace(T brace) {
            if (0 == _comparer.Compare(brace, _openBrace1)) {
                _braces1.Push(brace);
            } else if (_braces2 != null && 0 == _comparer.Compare(brace, _openBrace2)) {
                _braces2.Push(brace);
            } else if (0 == _comparer.Compare(brace, _closeBrace1)) {
                if (_braces1.Count > 0) {
                    _braces1.Pop();
                }
            } else if (_braces2 != null && 0 == _comparer.Compare(brace, _closeBrace2)) {
                if (_braces2.Count > 0) {
                    _braces2.Pop();
                }
            } else {
                return false;
            }

            return true;
        }

        /// <summary>
        /// Given token stream and token representing opening brace
        /// finds index of the closing brace token.
        /// </summary>
        public static int GetMatchingBrace(TokenStream<T> tokens, T openBraceToken, T closeBraceToken, IComparer<T> comparer) {
            TokenBraceCounter<T> braceCounter = new TokenBraceCounter<T>(openBraceToken, closeBraceToken, comparer);

            int start = tokens.Position;
            int position = -1;

            while (!tokens.IsEndOfStream()) {
                braceCounter.CountBrace(tokens.CurrentToken);
                if (braceCounter.Count == 0) {
                    position = tokens.Position;
                    break;
                }

                tokens.MoveToNextToken();
            }

            tokens.Position = start;
            return position;
        }

        /// <summary>
        /// Given token stream and token representing opening brace
        /// finds index of the closing brace token.
        /// </summary>
        public int GetMatchingBrace(TokenStream<T> tokens) {
            return GetMatchingBrace(tokens, _openBrace1, _closeBrace1, _comparer);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using namespace std;
using namespace Tizen::ArtikCloud;

GithubScm::GithubScm()
{
	//__init();
}

GithubScm::~GithubScm()
{
	//__cleanup();
}

void
GithubScm::__init()
{
	//_class = std::string();
	//_links = new GithubScmlinks();
	//credentialId = std::string();
	//id = std::string();
	//uri = std::string();
}

void
GithubScm::__cleanup()
{
	//if(_class != NULL) {
	//
	//delete _class;
	//_class = NULL;
	//}
	//if(_links != NULL) {
	//
	//delete _links;
	//_links = NULL;
	//}
	//if(credentialId != NULL) {
	//
	//delete credentialId;
	//credentialId = NULL;
	//}
	//if(id != NULL) {
	//
	//delete id;
	//id = NULL;
	//}
	//if(uri != NULL) {
	//
	//delete uri;
	//uri = NULL;
	//}
	//
}

void
GithubScm::fromJson(char* jsonStr)
{
	JsonObject *pJsonObject = json_node_get_object(json_from_string(jsonStr,NULL));
	JsonNode *node;
	const gchar *_classKey = "_class";
	node = json_object_get_member(pJsonObject, _classKey);
	if (node !=NULL) {

		if (isprimitive("std::string")) {
			jsonToValue(&_class, node, "std::string", "");
		} else {

		}
	}
	const gchar *_linksKey = "_links";
	node = json_object_get_member(pJsonObject, _linksKey);
	if (node !=NULL) {

		if (isprimitive("GithubScmlinks")) {
			jsonToValue(&_links, node, "GithubScmlinks", "GithubScmlinks");
		} else {

			GithubScmlinks* obj = static_cast<GithubScmlinks*> (&_links);
			obj->fromJson(json_to_string(node, false));

		}
	}
	const gchar *credentialIdKey = "credentialId";
	node = json_object_get_member(pJsonObject, credentialIdKey);
	if (node !=NULL) {

		if (isprimitive("std::string")) {
			jsonToValue(&credentialId, node, "std::string", "");
		} else {

		}
	}
	const gchar *idKey = "id";
	node = json_object_get_member(pJsonObject, idKey);
	if (node !=NULL) {

		if (isprimitive("std::string")) {
			jsonToValue(&id, node, "std::string", "");
		} else {

		}
	}
	const gchar *uriKey = "uri";
	node = json_object_get_member(pJsonObject, uriKey);
	if (node !=NULL) {

		if (isprimitive("std::string")) {
			jsonToValue(&uri, node, "std::string", "");
		} else {

		}
	}
}

GithubScm::GithubScm(char* json)
{
	this->fromJson(json);
}

char*
GithubScm::toJson()
{
	JsonObject *pJsonObject = json_object_new();
	JsonNode *node;
	if (isprimitive("std::string")) {
		std::string obj = getClass();
		node = converttoJson(&obj, "std::string", "");
	}
	else {

	}
	const gchar *_classKey = "_class";
	json_object_set_member(pJsonObject, _classKey, node);
	if (isprimitive("GithubScmlinks")) {
		GithubScmlinks obj = getLinks();
		node = converttoJson(&obj, "GithubScmlinks", "");
	}
	else {

		GithubScmlinks obj = static_cast<GithubScmlinks> (getLinks());
		GError *mygerror;
		mygerror = NULL;
		node = json_from_string(obj.toJson(), &mygerror);

	}
	const gchar *_linksKey = "_links";
	json_object_set_member(pJsonObject, _linksKey, node);
	if (isprimitive("std::string")) {
		std::string obj = getCredentialId();
		node = converttoJson(&obj, "std::string", "");
	}
	else {

	}
	const gchar *credentialIdKey = "credentialId";
	json_object_set_member(pJsonObject, credentialIdKey, node);
	if (isprimitive("std::string")) {
		std::string obj = getId();
		node = converttoJson(&obj, "std::string", "");
	}
	else {

	}
	const gchar *idKey = "id";
	json_object_set_member(pJsonObject, idKey, node);
	if (isprimitive("std::string")) {
		std::string obj = getUri();
		node = converttoJson(&obj, "std::string", "");
	}
	else {

	}
	const gchar *uriKey = "uri";
	json_object_set_member(pJsonObject, uriKey, node);
	node = json_node_alloc();
	json_node_init(node, JSON_NODE_OBJECT);
	json_node_take_object(node, pJsonObject);
	char * ret = json_to_string(node, false);
	json_node_free(node);
	return ret;
}

std::string
GithubScm::getClass()
{
	return _class;
}

void
GithubScm::setClass(std::string  _class)
{
	this->_class = _class;
}

GithubScmlinks
GithubScm::getLinks()
{
	return _links;
}

void
GithubScm::setLinks(GithubScmlinks  _links)
{
	this->_links = _links;
}

std::string
GithubScm::getCredentialId()
{
	return credentialId;
}

void
GithubScm::setCredentialId(std::string  credentialId)
{
	this->credentialId = credentialId;
}

std::string
GithubScm::getId()
{
	return id;
}

void
GithubScm::setId(std::string  id)
{
	this->id = id;
}

std::string
GithubScm::getUri()
{
	return uri;
}

void
GithubScm::setUri(std::string  uri)
{
	this->uri = uri;
}


text:
This document defines the structured data layer that Cockroach exposes on top of
its distributed key:value datastore.

##Overview##

The structured data layer is an abstraction over the internal key:value store
that provides familiar data organization tools. The structured data layer
implements a tabular model of data storage which somewhat resembles a relational
database at a high level. The terms namespace, table, column, and index/key
collectively define the structured data abstraction, each roughly akin to
database, table, column, and index/key in a relational database. The structured
data layer introduces concepts of data storage that many
database users are familiar with, and greatly increases the range of use-cases
that Cockroach is able to ergonomically service.

##Goals##

Add support for the following entities: *namespaces, tables, columns, and
indexes*. These notions are chosen for their similarity to *databases, tables,
columns, and indexes* in relational databases, but they are not intended to be
implementations thereof. Each entity will support:

- Creation: of a namespace, table, column in O(1).

- Renaming: in O(1)

-  Most configuration changes in O(1): with some exceptions like creating a
   new index will take O(n) time, where n is the number of rows in the table.

- Deletion: in O(n) where n is the number of subordinate entities (tables for a
  namespace, rows for a table).

The client API will be changed to use tabular based addressing instead of
global-key addressing. Non-primary-keyed queries will be supported through the use of secondary indexes.

##Non-Goals##

For now we don't intend on developing the following:

- Add support for triggers, stored-procedures, and integrity constraints.

- Add the notion of column types beyond *a sequence of bytes*. Add support for
  unbounded sub-collections of columns.

- Add support for non-tabular storage. This might be supported in the future.

- Add support for column locality-groups to improve data layout for performance.

- Add support for interleaved tables.

##Design##

We support high level entities like Namespace, Table, Index, and Column.
{Namespace,Table}Descriptor stores the entity metadata for {Namespace,Table}.

```proto
NamespaceDescriptor {
  NamespaceID = ...;
  Permissions = ...;
  ...
}
```

```proto
TableDescriptor {
  TableID = ...;
  Columns = [{ ColumnID = ..., Name = ... }, ...];
  Indexes = [{ IndexID = ..., Name = ..., ColumnIDs = [ ... ]}, ...];
  Permissions = ...;
  NextFreeColumnId = ...;
  NextFreeIndexID = ...;
  ...
}
```

In order to support fast renaming, we indirect entity access through a
hierarchical name-to-identifier mapping. NamespaceID and TableID are
allocated from the same global ID space. ColumnID and IndexID are local
to each Table.

To simplify our implementation, our Tables will require the presence of a
primary key. Follow-up work may relax this requirement. An investigation of use
cases not requiring a primary key is required to specify this work.

Initially, all the Table metadata in a cluster will be distributed by gossip and
cached by each Cockroach node. To reduce contention on the Table metadata, a
database transaction on the data within a Table will only contain the data being
addressed, and will not include a database read of the Table metadata. Care will
be taken to not expose these implementation details to the user.

##Addressing: Anatomy of a key##

The "/" separator is used below to disambiguate the components forming
each key, and to stress an order to the way the components line up to
form the key. The actual code does not use a "/" to separate key
components, but instead uses the encodings founding in
[util/encoding](https://github.com/cockroachdb/cockroach/tree/master/util/encoding).

###Global metadata key###

The metadata addressing will use the following key:Descriptor mappings:

`\x00name-<Parent-DescriptorID><Name>` : `<DescriptorID>`

`\x00desc-<DescriptorID>` : `{Namespace,Table}Descriptor`

The root namespace has the fixed ID of `1`. The initial implementation will
support only a single level of namespaces, though the key design allows for
arbitrarily many levels. The namespace table, mapping name to descriptor ID,
allows lookup of a descriptor proto from a `<namespace>/<table>` path. The
descriptor table allows for the reverse lookup of a descriptor proto from a
descriptor ID.

As an example, lookup of the `<TableID>` for the table path `"foo/bar"`
(`<namespace>/<table>`) is performed by first looking up the `<NamespaceID>`
using the key:

  `\x00name-<1>"foo"` : `<NamespaceID>`

The resulting `<NamespaceID>` is used to lookup the `<TableID>`:

  `\x00name-<NamespaceID>"bar"` : `<TableID>`

Creating/Renaming/Deleting: Creating a new Namespace or Table involves
allocating a new ID, initializing the {Namespace,Table}Descriptor, and storing
the descriptor at its key defined above. Renaming involves deleting the old key
and creating a new one. A namespace can only be deleted if it does not contain
any children. A table is deleted by marking it deleted in its table
descriptor. This will allow folks to recover their data for a few days/weeks
before we garbage collect the table in the background.

###Data addressing###

The Index data used to find data in the database is stored in the database
itself at keys with the following prefix: `/TableID/IndexID/Key>`, where TableID
represents the Table being addressed and IndexID the index in use. The encoding
used ensures that the data and metadata are well-separated.

**Primary key addressing**

This schema is made possible by the uniqueness constraint inherent to primary
keys. The primary key prefix `/TableID/PrimaryIndexID/Key` keys into a
unique row in the database. A cell within a row under a particular column is
addressed by adding the desired ColumnID to the key prefix:
`/TableID/PrimaryIndexID/Key/ColumnID`. PrimaryIndexID is variable to allow
changing the primary key.

**Secondary key addressing**

Secondary keys will be implemented as a layer of indirection to the primary
keys. Unlike primary keys, secondary keys are not required to be unique. So we
will employ the following key anatomy:
`/TableID/SecondaryIndexID/SecondaryKey/PrimaryKey`. Thus, multiple PrimaryKeys
can be enumerated under a single SecondaryKey. A lookup will involve looking up
the secondary index using the secondary key to pick up all the primary keys, and
further using the primary keys to get to all the data rows. A row insertion
involves computing the primary and secondary keys for the row, adding the data
under the primary key, and adding the primary key to all the secondary indexes
under the secondary keys. A row deletion behaves analogously.

**Interleaved table layout**

We will not be implementing interleaved tables as discussed in the
[Spanner](http://static.googleusercontent.com/media/research.google.com/en/us/archive/spanner-osdi2012.pdf)
paper initially but it's worth discussing how we might arrange their data.
Imagine you have two tables A and B with B configured to be interleaved within
A. The `/TableID-A/PrimaryIndexID/Key` prefix determines the key prefix where
the data from table B will be stored along with an entire row from table A at
primary key Key. All the rows from table B will bear the prefix
`/TableID-A/PrimaryIndexID/Key/TableID-B`, with
`/TableID-A/PrimaryIndexID/Key/TableID-B/KeyB` being a prefix for a particular
row in the table.

##Examples##

**Employee DB**

To represent an employee table for employees at microsoft, an admin might define
a namespace="microsoft" with a table="employees". The employee table might have
columns (id, first-name, last-name, address, state, zip, telephone, etc), where
id is specified as the primary key. Under the covers the "microsoft" namespace
might be given a NamespaceID=101, and the employee table given a TableID=9876.
The primary index has a default IndexID=0 and there could be a secondary index
on lastname with IndexID=1. Column telephone might have a columnID=6. For an
employee with employee-id=3456, the employee's telephone can be queried/modified
through the API using the query:

```?
  { table: "/microsoft/employees",
    key: "3456",
    columns : ["telephone" }
```

The query is converted internally by Cockroach into a global key: /9876/0/3456/6
(`/TableID/PrimaryIndexID/Key/ColumnID`).

Assume a secondary index is built for the last-name column. Telephone numbers of
employees with lastname="kimball" can be queried using the query:

```?
  { table: "/microsoft/employees",
    index: "last-name",
    key: "kimball",
    columns: ["telephone"] }
```

and this might produce two records for Spencer and Andy. Internally Cockroach
looks up the secondary index using key prefix:
`/TableID/SecondaryIndexID/Key`=/9876/1/kimball to get to the two employee ids for
Spencer and Andy, viz.: 1234 and 2345. The two telephone numbers are looked up
using keys: /9876/0/1234/6 and /9876/0/2345/6.

**Key:Value DB**

It is important to note that a key:value store is simply a degenerate case of
the more fully-featured namespace & table based schema defined here. A user
interested in using Cockroach as a key:value store to store all their documents
keyed by a document-id might define a table="documents" under
namespace="published", with a column "document". The user can lookup/modify the
database documents using the tuple ("/published/documents", document-id,
"document").

**Accounting/Permissions/Zones**

Cockroach currently allows a user to configure accounting, read/write
permissions, and zones by a key prefix. We will allow the user to configure
these permissions, etc, per namespace and per table.

**API**

The Cockroach API will be a protobuf service API. The read API will support a
Get() on a key filtered on a group of columns. It will also support a Scan() of
multiple rows in a table into a stream of ResultSets. The client API written in
a particular language can export iterators over a ResultSet. The write API will
support Put() on a group of cells in a group of rows.


text:
package io.motown.utils.rest.response;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Navigation item to be returned in the Operator API response.
 */
public final class NavigationItem {
    private final String href;

    /**
     * Construct a navigation item containing a link.
     * @param href  the link for this navigation item.
     */
    public NavigationItem(String href) {
        this.href = checkNotNull(href);
    }

    public String getHref() {
        return href;
    }
}


text:
Vizir is a web UI for displaying time series from different data sources.

It is written in Ruby, using the Ruby on Rails framework.

It is designed in a modular way, to be easily extended by writing providers for multiple data sources.

collect is the only provider currently implemented, but more to come.

It's still under development.

## Features

 * renders graphs in the browser
 * supports your own time series source with a few lines of code
 * provides a DSL to describe metrics and graphs, to create custom dashboards,
   and to apply operations to data (sums, ratios, etc.)

## Setup

#### Dependencies

Vizir depends on Ruby >= 1.9 (tested only with MRI 1.9) and bundle.

The collectd backend depends on librrd (`apt-get install librrd4` on Debian and related).

#### Install

 * `git clone https://github.com/Fotolia/vizir`
 * `cd vizir; bundle install`
 * Copy config/database.yml.example to config/database.yml and edit to match your environment
 * Copy config/providers.yml.example to config/providers.yml and edit to match your environment
 * `rake db:migrate`
 * `rake vizir:init`
 * `rake vizir:load`

#### Rails secret token

The secret token used to sign cookies is generated at the application's first start.
It is stored in `config/secret_token.yml` file which is not tracked.
To create a new one, juste delete it and restart the application.

## Metrics, graphs and dashboards definition

Vizir provides a comprehensive Ruby DSL to define metrics, graphs and dashboards (each one being a set of one or more of the previous).

It comes with a set of definitions, stored in `lib/definitions/<provider>`, the only provider being "collectd" at the moment.

Example of definition for a load average graph:

```ruby
graph "load" do
  { :shortterm => 1, :midterm => 5, :longterm => 15 }.each do |term,time|
    metric "load_#{time.to_s}" do
      rrd "load/load.rrd"
      ds term.to_s
      title "Load average #{time.to_s}min"
    end
  end

  layout :line
  title "Load average"
  scope :entity
end
```
will define 3 metrics (load_1, load_5, load_15), gathered in a graph.
The `scope :entity` line means the graph is defined for each entity (e.g host) which provides load data.

Graphs can be grouped in dashboards to simplify the display.
Currently, graphs must be part of a dashboard to be displayed.

Definition of a "System" dashboard :

```ruby
dashboard "system" do
  title "System metrics"
  graphs ["load", "cpu", "memory"]
end
```

Each component can be defined independently in different files, or nested (e.g dashboard containing graphs containing metrics).

At the moment, definition modifications need a reload of application data with the rake task, but we're working to avoid this step.


text:
import csv
import itertools
import os

import loom.cleanse
import loom.tasks
import pandas as pd

from distributions.io.stream import json_load
from distributions.io.stream import open_compressed
from loom.cFormat import assignment_stream_load

from cgpm.mixtures.view import View
from cgpm.utils import config as cu
from cgpm.utils.parallel_map import parallel_map

DEFAULT_LOOM_STORE = os.path.join(os.sep, 'tmp', 'cgpm', 'loomstore')

DEFAULT_CLEANSED_DIR = 'cleansed'
DEFAULT_RAW_DIR = 'raw'
DEFAULT_RESULTS_DIR = 'results'

def _generate_column_names(state):
    """Returns list of dummy names for the outputs of `state`."""
    return [unicode('c%05d') % (i,) for i in state.outputs]

def _generate_loom_stattypes(state):
    """Returns list of loom stattypes from the cgpm stattypes of `state`."""
    cctypes = state.cctypes()
    distargs = state.distargs()
    return [cu.loom_stattype(s, d) for s, d in zip(cctypes, distargs)]

def _generate_project_paths(name=None):
    """Creates a new project in the loom store."""
    if name is None:
        name = cu.timestamp()
    store = _retrieve_loom_store()
    project_root = os.path.join(store, name)
    # Create necessary subdirectories.
    paths = {
        'root'      : project_root,
        'raw'       : os.path.join(project_root, DEFAULT_RAW_DIR),
        'cleansed'  : os.path.join(project_root, DEFAULT_CLEANSED_DIR),
        'results'   : os.path.join(project_root, DEFAULT_RESULTS_DIR)

    }
    for path in paths.values():
        if not os.path.exists(path):
            os.makedirs(path)
    return paths

def _loom_cross_cat(path, sample):
    """Return the loom CrossCat structure at `path`, whose id is `sample`."""
    model_in = os.path.join(
        path, 'samples', 'sample.%d' % (sample,), 'model.pb.gz')
    cross_cat = loom.schema_pb2.CrossCat()
    with open_compressed(model_in, 'rb') as f:
        cross_cat.ParseFromString(f.read())
    return cross_cat

def _retrieve_loom_store():
    """Retrieves absolute path of the loom store."""
    if os.environ.get('CGPM_LOOM_STORE'):
        return os.environ['CGPM_LOOM_STORE']
    if not os.path.exists(DEFAULT_LOOM_STORE):
        os.makedirs(DEFAULT_LOOM_STORE)
    return DEFAULT_LOOM_STORE

def _retrieve_column_partition(path, sample):
    """Return column partition from CrossCat `sample` at `path`.

    The returned structure is of the form `cgpm.crosscat.state.State.Zv`.
    """
    cross_cat = _loom_cross_cat(path, sample)
    return dict(itertools.chain.from_iterable([
        [(featureid, k) for featureid in kind.featureids]
        for k, kind in enumerate(cross_cat.kinds)
    ]))

def _retrieve_featureid_to_cgpm(path):
    """Returns a dict mapping loom's 0-based featureid to cgpm.outputs."""
    # Loom orders features alphabetically based on statistical types:
    # i.e. 'bb' < 'dd' < 'nich'. The ordering is stored in
    # `ingest/encoding.json.gz`.
    encoding_in = os.path.join(path, 'ingest', 'encoding.json.gz')
    features = json_load(encoding_in)
    def colname_to_output(cname):
        # Convert dummy column name from 'c00012' to the integer 12.
        return int(cname.replace('c', ''))
    return {
        i: colname_to_output(f['name']) for i, f in enumerate(features)
    }

def _retrieve_row_partitions(path, sample):
    """Return row partition from CrossCat `sample` at `path`.

    The returned structure is of the form `cgpm.crosscat.state.State.Zrv`.
    """
    cross_cat = _loom_cross_cat(path, sample)
    num_kinds = len(cross_cat.kinds)
    assign_in = os.path.join(
        path, 'samples', 'sample.%d' % (sample,), 'assign.pbs.gz')
    assignments = {
        a.rowid: [a.groupids(k) for k in xrange(num_kinds)]
        for a in assignment_stream_load(assign_in)
    }
    rowids = sorted(assignments)
    return {
        k: [assignments[rowid][k] for rowid in rowids]
        for k in xrange(num_kinds)
    }

def _update_state(state, path, sample):
    """Updates `state` to match the CrossCat `sample` at `path`.

    Only the row and column partitions are updated; parameter inference
    (state alpha, view alphas, hyperparameters, etc) should be transitioned
    separately.

    Wild errors will occur if the Loom object is incompatible with `state`.
    """

    # Retrieve the new column partition from loom.
    Zv_new_raw = _retrieve_column_partition(path, sample)
    assert sorted(Zv_new_raw.keys()) == range(len(state.outputs))

    # The keys of Zv are contiguous
    # from [0..len(outputs)], while state.outputs are arbitrary integers, so we
    # need to map the loom feature ids correctly.
    output_mapping = _retrieve_featureid_to_cgpm(path)
    assert sorted(output_mapping.values()) == sorted(state.outputs)
    Zv_new = {output_mapping[f]: Zv_new_raw[f] for f in Zv_new_raw}

    # Retrieve the new row partitions from loom. The view ids are contiguous
    # from [0..n_views].
    Zvr_new = _retrieve_row_partitions(path, sample)
    assert set(Zv_new.values()) == set(Zvr_new.keys())

    # Create new views in cgpm, with the corresponding loom row partitions.
    offset = max(state.views) + 1
    new_views = []
    for v in sorted(set(Zvr_new.keys())):
        index = v + offset
        assert index not in state.views
        view = View(
            state.X,
            outputs=[state.crp_id_view + index],
            Zr=Zvr_new[v],
            rng=state.rng
        )
        new_views.append(view)
        state._append_view(view, index)

    # Migrate each dim to its new view.
    for c in state.outputs:
        v_current = state.Zv(c)
        v_new = Zv_new[c] + offset
        state._migrate_dim(v_current, v_new, state.dim_for(c), reassign=True)

    assert len(state.views) == len(new_views)
    state._check_partitions()

    return state

def _update_state_mp(args):
    return _update_state(*args)

def _validate_transition(
        N=None, S=None, kernels=None, seed=None,
        checkpoint=None, progress=None):
    # These features will be implemented in stages; raise errors for now.
    if S is not None:
        raise ValueError('Loom does not support transitions by seconds.')
    if kernels is not None:
        raise ValueError('Loom does not support kernels.')
    if progress is not None:
        raise ValueError('Loom does not support progress bar.')
    if checkpoint is not None:
        raise ValueError('Loom does not support checkpoint.')

def _write_dataset(state, path):
    """Write a csv file of `state.X` to the file at `path`."""
    frame = pd.DataFrame([state.X[i] for i in state.outputs]).T
    assert frame.shape == (state.n_rows(), state.n_cols())
    frame.columns = _generate_column_names(state)
    # Update columns which can be safely converted to int.
    for col in frame.columns:
        if all(frame[col] == frame[col]//1):
            frame[col] = frame[col].astype(int)
    frame.to_csv(path, na_rep='', index=False)

def _write_schema(state, path):
    """Writes a csv file of the loom schema of `state` to the file at `path`."""
    column_names = _generate_column_names(state)
    loom_stattypes = _generate_loom_stattypes(state)
    with open(path, 'wb') as schema_file:
        writer = csv.writer(
            schema_file, delimiter=',', quoting=csv.QUOTE_MINIMAL)
        writer.writerow(['Feature Name', 'Type'])
        writer.writerows(zip(column_names, loom_stattypes))

# --- End of helper methods ----------------------------------------------------

def initialize(state):
    """Run the preprocessing pipeline.
    |- write dataset and schema to csv
    |- cleanse
    |- transform
    |- ingest
    |- ready for: infer
    """
    paths = _generate_project_paths()

    # Write dataset and schema csv files.
    dataset_file = os.path.join(paths['raw'], 'data.csv')
    schema_file = os.path.join(paths['raw'], 'schema.csv')

    _write_dataset(state, dataset_file)
    _write_schema(state, schema_file)

    # Cleanse and compress the dataset for Loom.
    cleansed_file = os.path.join(paths['cleansed'], 'data.csv.gz')
    loom.cleanse.force_ascii(dataset_file, cleansed_file)

    # Transform the cleansed dataset into Loom.
    loom.tasks.transform(paths['results'], schema_file, paths['cleansed'])

    # Ingest the transformed data.
    loom.tasks.ingest(paths['results'])

    return paths

def transition(
        state, N=None, S=None, kernels=None, seed=None, checkpoint=None,
        progress=None):
    """Runs full Gibbs sweeps of all kernels on the cgpm.state.State object."""

    # Check compatible transition parameters.
    _validate_transition(
        N=N, S=S, kernels=kernels, seed=seed, checkpoint=checkpoint,
        progress=progress)

    # Create Loom project if necessary.
    if state._loom_path is None:
        state._loom_path = initialize(state)

    if N is None:
        N = 1

    # The seed is used to determine which directory under results/samples
    # to use. Default to 0, since infer_one has no default mode.
    if seed is None:
        seed = 0

    loom.tasks.infer_one(
        state._loom_path['results'],
        seed=seed,
        config={"schedule": {"extra_passes": N}}
    )

    _update_state(state, state._loom_path['results'], seed)

def transition_engine(
        engine, N=None, S=None, kernels=None, seed=None, checkpoint=None,
        progress=None):
    """Run full Gibbs (all kernels) on all states in cgpm.engine.Engine object.

    Implemented separately to use Loom multiprocessing, and share a single
    Loom project among several cgpm states (Loom samples).
    """

    # Check compatible transition parameters.
    _validate_transition(
        N=N, S=S, kernels=kernels, seed=seed, checkpoint=checkpoint,
        progress=progress)

    # All the states must have the same loom project path.
    for state in engine.states:
        assert state._loom_path == engine.states[0]._loom_path

    # Create Loom project if necessary.
    if engine.states[0]._loom_path is None:
        loom_path = initialize(engine.states[0])
        for state in engine.states:
            state._loom_path = loom_path

    # Run transitions using Loom multiprocessing.
    loom.tasks.infer(
        engine.states[0]._loom_path['results'],
        sample_count=engine.num_states(),
        config={"schedule": {"extra_passes": N}}
    )

    # Update the engine and save the engine.
    args = [
        (engine.states[i], engine.states[i]._loom_path['results'], i)
        for i in xrange(engine.num_states())
    ]
    engine.states = parallel_map(_update_state_mp, args)

    # Transition the non-structural parameters.
    num_transitions = int(len(engine.states[0].outputs)**.5)
    engine.transition(
        N=num_transitions,
        kernels=['column_hypers', 'column_params', 'alpha', 'view_alphas']
    )


text:
<?php

namespace AppBundle\Controller\Callback\CloudSearch\Resource;

use AppBundle\Controller\Callback\CloudSearch\BaseProvider;
use Symfony\Component\HttpFoundation\Request;

class OpenCourseLessons extends BaseProvider
{
    public function get(Request $request)
    {
        $conditions = $request->query->all();
        $start = $request->query->get('start', 0);
        $limit = $request->query->get('limit', 20);

        $conditions['status'] = 'published';
        $conditions['updatedTime_GE'] = $conditions['cursor'];
        $lessons = $this->getOpenCourseService()->searchLessons($conditions, array('createdTime' => 'ASC'), $start, $limit);
        $next = $this->nextCursorPaging($conditions['cursor'], $start, $limit, $lessons);

        return $this->wrap($this->filter($lessons), $next);
    }

    public function filter($res)
    {
        return $this->multicallFilter('open_course_lesson', $res);
    }

    protected function multicallFilter($name, array $res)
    {
        foreach ($res as $key => $one) {
            $res[$key] = $this->callFilter($name, $one);
            $res[$key]['body'] = '';
            $res[$key]['content'] = '';
        }

        return $res;
    }

    /**
     * @return Biz\OpenCourse\Service\OpenCourseService
     */
    protected function getOpenCourseService()
    {
        return $this->getBiz()->service('OpenCourse:OpenCourseService');
    }
}


text:
<?php
	/**
	 * Display image form database
	 *
	 * Retrive an image from mysql database if image id is provided.
	 *
	 * @example to display a image with image id 1, place <img src="image.php?id=1" > in your html file.
	 *
	 */

	// verify request id.
	if (empty($_GET['id']) || !is_numeric($_GET['id'])) {
		echo 'A valid image file id is required to display the image file.';
		exit;
	}

	$imageId = $_GET['id'];
	//echo "id is : $imageId";
	//connect to mysql database
	if ($conn = mysqli_connect('localhost', 'root', 'nandan', 'forImg')) {
		$data = mysqli_real_escape_string($conn, $data);
		$sql = "SELECT  data FROM person where Person_id = {$imageId}";
		//echo "SELECT  data FROM person where Person_id = {$imageId}";
		if ($rs = mysqli_query($conn, $sql)) {
			$imageData = mysqli_fetch_array($rs, MYSQLI_ASSOC);
			mysqli_free_result($rs);
		} else {
			echo "Error: Could not get data from mysql database. Please try again.";
		}
		//close mysqli connection
		mysqli_close($conn);

	} else {
		echo "Error: Could not connect to mysql database. Please try again.";
	}

	if (!empty($imageData)) {
		//echo "got data displaying below";
		// show the image.
		//header("Content-type: {$imageData['type']}");
		echo $imageData['data'];
	}
	?>


text:
#ifndef HTMLInputElementFileSystem_h
#define HTMLInputElementFileSystem_h

#include "modules/filesystem/EntriesCallback.h"

namespace blink {

class Entry;
class HTMLInputElement;
class ExecutionContext;

class HTMLInputElementFileSystem {
public:
    static EntryHeapVector webkitEntries(ExecutionContext*, HTMLInputElement&);

private:
    HTMLInputElementFileSystem();
    ~HTMLInputElementFileSystem();
};

} // namespace blink

#endif // HTMLInputElementFileSystem_h


text:
CREATE TABLE `user_types` (
  `id`	INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  `user_type`	VARCHAR DEFAULT 'user',
  `type_desc`	VARCHAR DEFAULT 'Default User'
);

INSERT INTO user_types (id, user_type, type_desc) VALUES (1, 'user', 'Common User');
INSERT INTO user_types (id, user_type, type_desc) VALUES (2, 'admin', 'Administrator');

CREATE TABLE `users` (
  `user_id`	INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  `user_name`	VARCHAR NOT NULL,
  `user_password`	VARCHAR NOT NULL,
  `user_email`	VARCHAR NOT NULL,
  `first_name`	VARCHAR NOT NULL,
  `middle_name`	VARCHAR NOT NULL,
  `last_name`	VARCHAR NOT NULL,
  `user_account_type`	TEXT,
  `created`	TEXT,
  `modified`	TEXT
);

-- RESET CODES
CREATE TABLE `reset_codes` (
  `id`	INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  `code`	VARCHAR NOT NULL,
  `email`	VARCHAR NOT NULL,
  `created` TEXT
);


text:
"""Condition table-based trigger fsm."""

from typing import Optional, Tuple
from hdltools.vcd.trigger import VCDTriggerFSM, VCDTriggerDescriptor

class ConditionTableTrigger(VCDTriggerFSM):
    """Condition table trigger fsm.

    Unordered event-based trigger
    """

    def __init__(
        self,
        conditions: Optional[Tuple[VCDTriggerDescriptor]] = None,
        debug=False,
        oneshot=True,
        **kwargs,
    ):
        """Initialize."""
        super().__init__(**kwargs)
        self._condtable = {}
        self._oneshot = oneshot

        if conditions is not None:
            for condition in conditions:
                self.add_condition(condition)

    @property
    def conditions_met(self):
        """Get number of conditions met."""
        met = 0
        for cond, state in self._condtable.items():
            if state:
                met += 1

        return met

    @property
    def unmet_conditions(self):
        """Get number of unmet conditions."""
        return len(self._condtable) - self.conditions_met

    @property
    def conditions(self):
        """Get conditions."""
        return self._condtable.keys()

    @VCDTriggerFSM.sensitivity_list.getter
    def sensitivity_list(self):
        """Get current sensitivity list."""
        return self.conditions

    @VCDTriggerFSM.global_sensitivity_list.getter
    def global_sensitivity_list(self):
        """Get global sensitivity list."""
        return self.conditions

    @property
    def oneshot(self):
        """Get oneshot."""
        return self._oneshot

    @oneshot.setter
    def oneshot(self, value):
        """Set oneshotness."""
        if not isinstance(value, bool):
            raise TypeError("value must be bool")
        if self.trigger_armed:
            raise RuntimeError("cannot change oneshot property while armed")

        self._oneshot = value

    def arm_trigger(self, reset_conds=False):
        """Arm trigger."""
        super().arm_trigger()
        # reset states
        if not self._condtable:
            raise RuntimeError("table empty; cannot arm")
        if reset_conds:
            self._condtable = {evt: False for evt in self._condtable}

    def trigger_reset(self):
        """Reset trigger configuration."""
        super().trigger_reset()
        self._condtable = {}

    def add_condition(self, cond: VCDTriggerDescriptor):
        """Add condition."""
        if self.trigger_armed:
            raise RuntimeError("cannot add condition while trigger is armed")
        if cond in self._condtable:
            raise ValueError("condition is already in condition table")
        if not isinstance(cond, VCDTriggerDescriptor):
            raise TypeError("cond must be a VCDTriggerDescriptor object")
        self._condtable[cond] = False

    def remove_condition(self, cond: VCDTriggerDescriptor):
        """Remove condition."""
        if self.trigger_armed:
            raise RuntimeError(
                "cannot remove condition while trigger is armed"
            )
        del self._condtable[cond]

    def __len__(self):
        """Get table length."""
        return len(self._condtable)

    def __getitem__(self, key: VCDTriggerDescriptor) -> bool:
        """Get condition state."""
        return self._condtable[key]

    def advance(self, cond, value, time):
        """Advance value directly without variable name matching."""
        if self.trigger_armed is False:
            return (False, None, False)
        if cond.match_value(value):
            if self._condtable[cond] is False:
                changed = True
                self._condtable[cond] = True
            else:
                changed = False
            return (changed, True, False)
        else:
            if self._condtable[cond]:
                changed = True
                self._condtable[cond] = False
            else:
                changed = False
            return (changed, False, False)

    def check_and_fire(self, time=None):
        """Check current state and fire."""
        if self.unmet_conditions == 0 and self.triggered is False:
            # done (event start)
            self._fire_trigger(self.oneshot)

        if (
            not self.oneshot
            and self.unmet_conditions != 0
            and self.triggered is True
        ):
            # event ends
            self._event_ends()

    def match_and_advance(self, var, value, time=None):
        """Update condition states."""
        if self.trigger_armed is False:
            return
        updated_values = {}
        for cond, state in self._condtable.items():
            if cond.match_var(var.scope, var.name, var.identifiers[0]):
                # condition in table
                if cond.match_value(value):
                    updated_values[cond] = True
                    print(f"DEBUG: cond {cond} -> TRUE")
                else:
                    updated_values[cond] = False
                    print(f"DEBUG: cond {cond} -> FALSE")

        # save updated values
        self._condtable.update(updated_values)

        # check current state and fire
        if self.unmet_conditions == 0:
            # done
            self._fire_trigger()


text:
package chatty.gui;

import chatty.Helper;
import chatty.Helper.IntegerPair;
import chatty.util.settings.Settings;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Window;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;

/**
 * Allows you to add windows that you can then save the position and size for
 * (usually at the end of the program session), which can be reloaded later,
 * based on the restore settings. Also attaches the added windows to the
 * default parent, moving them along if the parent is moved (if enabled).
 *
 * The window attributes are saved to the settings.
 *
 * The position/size of the window is restored just once at the start (even if
 * it isn't shown yet) and then just not changed if it's set to restore. If it's
 * set to not restore, then the position is set everytime it's opened.
 *
 * @author tduva
 */
public class WindowStateManager {

    private static final Logger LOGGER = Logger.getLogger(WindowStateManager.class.getName());

    private static final String SETTING = "windows";
    private static final String MODE_SETTING = "restoreMode";
    private static final String CHECK_ON_SCREEN_SETTING = "restoreOnlyIfOnScreen";

    public static final int DONT_RESTORE = 0;
    public static final int RESTORE_MAIN = 1;
    public static final int RESTORE_ALL = 2;
    public static final int RESTORE_ON_START = 3;
    public static final int REOPEN_ON_START = 4;

    private final HashMap<Window, StateItem> windows = new HashMap<>();

    /**
     * Saves which windows have had their position set already in this session.
     */
    private final Set<Window> locationSet = new HashSet<>();
    private final Settings settings;

    /**
     * The default parent is the one that the windows are centered on, if they
     * are opened and their position hasn't been set yet or their position
     * should not be restored.
     */
    private final Window defaultParent;

    /**
     * The primary window is special, because it can be set to be restored even
     * if the others aren't ({@code RESTORE_MAIN}).
     */
    private Window primaryWindow;

    private final AttachedWindowManager attachedWindowManager;

    public WindowStateManager(Window defaultParent, Settings settings) {
        this.settings = settings;
        this.defaultParent = defaultParent;
        attachedWindowManager = new AttachedWindowManager(defaultParent);
    }

    /**
     * Adds a window to be managed.
     *
     * @param window The {@code Window} object
     * @param id The id of the window, which is used when saving
     * @param saveSize Whether to save (or rather restore) the size
     * @param reopen Whether to reopen the window on start
     */
    public void addWindow(Window window, String id, boolean saveSize, boolean reopen) {
        windows.put(window, new StateItem(id, saveSize, reopen));
        attachedWindowManager.attach(window);
    }

    /**
     * Sets the primary window, which can be restored even if the other windows
     * are set to not restore.
     *
     * @param window
     */
    public void setPrimaryWindow(Window window) {
        this.primaryWindow = window;
    }

    public void setAttachedWindowsEnabled(boolean enabled) {
        attachedWindowManager.setEnabled(enabled);
    }

    /**
     * Saves the attributes for all managed windows.
     */
    public void saveWindowStates() {
        for (Window window : windows.keySet()) {
            saveWindowState(window);
        }
    }

    /**
     * Loads the window attributes for all managed windows.
     */
    public void loadWindowStates() {
        for (Window window : windows.keySet()) {
            loadWindowState(window);
        }
    }

    /**
     * Save the window attributes for a single window.
     *
     * @param window The window to save the attributes for
     */
    private void saveWindowState(Window window) {
        // Only save state when window state was actually set during this
        // this session at least once
        if (!locationSet.contains(window) && window != primaryWindow) {
            return;
        }
        // Should still save whether it was open
        StateItem item = windows.get(window);
        Point location = window.getLocation();
        String state = location.x+","+location.y;
        Dimension size = window.getSize();
        state += ";"+size.width+","+size.height;
        state += ";"+(window.isVisible() ? "1" : "0");
        settings.mapPut(SETTING, item.id, state);
    }

    /**
     * Try to load the window attributes for the given {@literal Window} and sets
     * the location and size for the window (if it's set to restore).
     *
     * The attributes are loaded from a map in the settings, with the window id
     * as the key. The item has to be a {@literal String} in the format:
     * x,y;width,height;wasOpen
     *
     * @param window
     */
    private void loadWindowState(Window window) {
        StateItem item = windows.get(window);
        String state = (String)settings.mapGet(SETTING, item.id);
        if (state == null) {
            return;
        }

        String[] states = state.split(";");
        if (states.length < 3) {
            return;
        }

        if (mode() >= RESTORE_ON_START
                || (mode() >= RESTORE_MAIN && window == primaryWindow)) {
            // Set position and size

            // Set size first, so width is set already for checking position
            IntegerPair sizeTemp = Helper.getNumbersFromString(states[1]);
            if (sizeTemp != null && item.saveSize) {
                Dimension size = new Dimension(sizeTemp.a, sizeTemp.b);
                window.setSize(size);
            }

            // Set position
            IntegerPair locationTemp = Helper.getNumbersFromString(states[0]);
            if (locationTemp != null) {
                Point location = new Point(locationTemp.a, locationTemp.b);
                if (!settings.getBoolean(CHECK_ON_SCREEN_SETTING)
                        || isOnScreen(location, window.getWidth())) {
                    // If this is the window the others are attached to, ignore
                    // this movement.
                    if (window == defaultParent) {
                        attachedWindowManager.ignoreLocationOnce(location);
                    }
                    window.setLocation(location);
                    locationSet.add(window);
                } else {
                    LOGGER.info("Location for "+item.id+" ["+location+"] not restored (not on screen)");
                }
            }
        }

        item.wasOpen = states[2].equals("1");
    }

    private boolean isOnScreen(Point location, int width) {
        return GuiUtil.isPointOnScreen(location, 100)
            || GuiUtil.isPointOnScreen(location, width - 100);
    }

    /**
     * Sets the location to the default one (centered on the default parent),
     * unless the mode is set to restore and the position was set before, in
     * which case nothing is done, so the window just keeps the location it
     * already has.
     *
     * @param window The window to set the position for
     * @param parent The window to center the window on, can be null in which
     * case it centers on the default parent
     */
    public void setWindowPosition(Window window, Window parent) {
        boolean setLocationBefore = locationSet.contains(window);
        if (mode() < RESTORE_ALL || !setLocationBefore) {
            if (parent == null) {
                parent = defaultParent;
            }
            window.setLocationRelativeTo(parent);
            locationSet.add(window);
        }
    }

    public void setWindowPosition(Window window) {
        setWindowPosition(window, null);
    }

    /**
     * Returns whether the window was open in the last session.
     *
     * @param window The window to check.
     * @return {@code true} if the window was open last session, {@code false}
     * if it wasn't or there is no data saved
     */
    public boolean wasOpen(Window window) {
        StateItem item = windows.get(window);
        return item != null && item.wasOpen;
    }

    /**
     * Returns whether the window should be reopened on start.
     *
     * @param window
     * @return {@code true} if it should be reopened, {@code false} otherwise
     */
    public boolean shouldReopen(Window window) {
        return mode() >= REOPEN_ON_START && wasOpen(window);
    }

    /**
     * Gets the current restore mode setting.
     *
     * @return The mode as an integer
     */
    private int mode() {
        return (int)settings.getLong(MODE_SETTING);
    }

    /**
     * Saves some stuff for a single window.
     */
    private static class StateItem {

        /**
         * Whether to save (or rather restore) the size.
         */
        public final boolean saveSize;

        /**
         * The id of this window, which is used when saving the settings.
         */
        public final String id;

        /**
         * Whether this window should be reopened (if the restore setting allows
         * it).
         */
        public final boolean reopen;

        /**
         * Saves whether the window was open when the program was closed last
         * session.
         */
        public boolean wasOpen;

        StateItem(String id, boolean saveSize, boolean reopen) {
            this.saveSize = saveSize;
            this.reopen = reopen;
            this.id = id;
        }
    }

}


text:
#ifndef TENSORFLOW_STREAM_EXECUTOR_TPU_TPU_NODE_CONTEXT_H_
#define TENSORFLOW_STREAM_EXECUTOR_TPU_TPU_NODE_CONTEXT_H_

#include <string>

#include "absl/memory/memory.h"
#include "tensorflow/compiler/xla/service/backend.h"
#include "tensorflow/compiler/xla/service/stream_pool.h"
#include "tensorflow/compiler/xla/service/transfer_manager.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/stream_executor/device_memory_allocator.h"
#include "tensorflow/stream_executor/lib/status.h"
#include "tensorflow/stream_executor/lib/statusor.h"
#include "tensorflow/stream_executor/tpu/status_helper.h"
#include "tensorflow/stream_executor/tpu/tpu_platform_interface.h"

namespace tensorflow {
namespace tpu {

// A TpuNodeContext object represents a specific TPU node (core). The static
// class methods represent host-wide actions.
//
// First call Initialize in a freshly reset system. Then call Create to talk to
// individual nodes.
class TpuNodeContext final {
 public:
  using Status = stream_executor::port::Status;
  template <typename T>
  using StatusOr = stream_executor::port::StatusOr<T>;

  static StatusOr<std::unique_ptr<TpuNodeContext>> Create(int device_ordinal);

  explicit TpuNodeContext(int device_ordinal, XLA_TpuNodeContext* node_context)
      : device_ordinal_(device_ordinal), node_context_(node_context) {
    CHECK_NE(node_context, nullptr);
  }
  ~TpuNodeContext();

  static Status StopChipHeartbeats();

  static Status CloseTpuHost();

  static Status Initialize(int device_ordinal);

  static TpuPlatformInterface* platform();

  int device_ordinal() const;

  xla::Backend* backend() const;

  stream_executor::StreamExecutor* stream_executor() const;

  bool CompactionSupported(int device_ordinal) const;

 private:
  const int device_ordinal_;
  XLA_TpuNodeContext* const node_context_;

  TF_DISALLOW_COPY_AND_ASSIGN(TpuNodeContext);
};

}  // namespace tpu
}  // namespace tensorflow

#endif  // TENSORFLOW_STREAM_EXECUTOR_TPU_TPU_NODE_CONTEXT_H_


text:
package ui

import "time"

// ResetPasswordToken describes a reset password token UI object.
type ResetPasswordToken struct {
	// TokenID is token ID
	TokenID string `json:"tokenId"`
	// User is user name associated with this token
	User string `json:"user"`
	// QRCode is a QR code value
	QRCode []byte `json:"qrCode,omitempty"`
	// Expiry is token expiration time
	Expiry time.Time `json:"expiry,omitempty"`
}

// RecoveryCodes describes RecoveryCodes UI object.
type RecoveryCodes struct {
	// Codes are user's new recovery codes.
	Codes []string `json:"codes,omitempty"`
	// Created is when the codes were created.
	Created *time.Time `json:"created,omitempty"`
}

// ChangedUserAuthn describes response after successfully changing authn.
type ChangedUserAuthn struct {
	Recovery                RecoveryCodes `json:"recovery"`
	PrivateKeyPolicyEnabled bool          `json:"privateKeyPolicyEnabled,omitempty"`
}


text:
'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
	errorHandler = require('../errors.server.controller'),
	mongoose = require('mongoose'),
	passport = require('passport'),
	User = mongoose.model('User');

/**
 * Signin after passport authentication
 */
exports.signin = function(req, res, next) {
	passport.authenticate('local', function(err, user, info) {
		if (err || ! user) {
			res.status(400).send(info);
		} else {
			// Remove sensitive data before login
			user.password = undefined;
			user.salt = undefined;
			req.login(user, function(err) {
				if (err) {
					res.status(400).send(err);
				} else {
					res.json(user);
				}
			});
		}
	})(req, res, next);
};

/**
 * Signout
 */
exports.signout = function(req, res) {
	req.logout();
	res.redirect('/');
};

exports.createUser = function(req, res) {
	// Init Variables
	var user = new User(req.body);
	// Add missing user fields
	var roles = ['user'];
	if (req.body.rights.teacher) {
		roles.push('teacher');
	}
	if (req.body.rights.manager) {
		roles.push('manager');
	}
	if (req.body.rights.admin) {
		roles.push('admin');
	}
	if (req.body.rights.printer) {
		roles.push('printer');
	}
	user.username = user.serial;
	user.roles = roles;
	user.provider = 'local';
	user.displayname = user.firstname + ' ' + user.lastname;
	// Then save the user
	user.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		return res.status(200).send({
			message: 'User created'
		});
	});
};

exports.read = function(req, res) {
	res.jsonp(req.profile);
};


text:
<ion-content class="">

Latest News

Latest news and updates

  <ion-card>
  <ion-card-content>
    <ion-card-title>
      Klinik Koding
      </ion-card-title>

     Selamat malam Filkom.
Klinik koding sekarang hadir setiap minggu loh! Pada minggu ini kita akan membahas mata kuliah Pemrograman Lanjut dengan materi dasar pemahaman OOP

  </ion-card-content>
</ion-card>
<ion-card>
  <ion-card-content>
    <ion-card-title>
      Pengumuman Lolos Tahap III Recruitment BCC 2017/2018
      </ion-card-title>

    Berikut ini adalah daftar nama peserta recruitment BCC 2017 yang lolos untuk mengikuti tahap selanjutnya yaitu Tahap III.

  </ion-card-content>
</ion-card>

</ion-content>


text:
namespace dom_distiller {

class DomDistillerService;

// Handler class for DOM Distiller list operations.
class DomDistillerHandler : public content::WebUIMessageHandler {
 public:
  // The lifetime of |service| has to outlive this handler.
  DomDistillerHandler(DomDistillerService* service, const std::string& scheme);
  ~DomDistillerHandler() override;

  // content::WebUIMessageHandler implementation.
  void RegisterMessages() override;

  // Callback from JavaScript for the "requestEntries" message. This
  // requests the list of entries and returns it to the front end by calling
  // "onReceivedEntries". There are no JavaScript arguments to this method.
  void HandleRequestEntries(const base::ListValue* args);

  // Callback from JavaScript for when an article should be added. The first
  // element in |args| should be a string representing the URL to be added.
  void HandleAddArticle(const base::ListValue* args);

  // Callback from JavaScript for when an article is selected. The first element
  // in |args| should be a string representing the ID of the entry to be
  // selected.
  void HandleSelectArticle(const base::ListValue* args);

  // Callback from JavaScript for when viewing a URL is requested. The first
  // element in |args| should be a string representing the URL to be viewed.
  void HandleViewUrl(const base::ListValue* args);

 private:
  // Callback from DomDistillerService when an article is available.
  void OnArticleAdded(bool article_available);

  // The DomDistillerService.
  DomDistillerService* service_;

  // The scheme for DOM distiller articles.
  std::string article_scheme_;

  // Factory for the creating refs in callbacks.
  base::WeakPtrFactory<DomDistillerHandler> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(DomDistillerHandler);
};

}  // namespace dom_distiller

#endif  // COMPONENTS_DOM_DISTILLER_WEBUI_DOM_DISTILLER_HANDLER_H_


text:
@ECHO OFF
if "%1" == "goto" shift && goto continue

REM If they enter nothing, do all the benchmarks
set def=imaginary,spectral,real
if not "%1" == "" set def=%1
for %%i in (%def%) do for %%j in (yca\%%i\*.yca) do call %0 goto %%j
goto end

:continue
echo Processing %1
firstify %1 -himlv > %1.txt 2>&1

:end


text:
var searchData=
[
  ['logger',['logger',['../classnetflex_1_1logger.html',1,'netflex']]],
  ['logger_5fiface',['logger_iface',['../classnetflex_1_1logger__iface.html',1,'netflex']]]
];


text:
package org.apache.sshd.server.subsystem.sftp;

import java.nio.file.attribute.FileTime;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * @author Apache MINA SSHD Project
 */
public final class UnixDateFormat {

    /**
     * A {@link List} of short months names where Jan=0, Feb=1, etc.
     */
    public static final List<String> MONTHS =
        Collections.unmodifiableList(
            Arrays.asList(
                "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
            ));

    /**
     * Six months duration in msec.
     */
    public static final long SIX_MONTHS = 183L * 24L * 60L * 60L * 1000L;

    private UnixDateFormat() {
        throw new UnsupportedOperationException("No instance allowed");
    }

    /**
     * Get unix style date string.
     *
     * @param time The {@link FileTime} to format - ignored if {@code null}
     * @return The formatted date string
     * @see #getUnixDate(long)
     */
    public static String getUnixDate(FileTime time) {
        return getUnixDate((time != null) ? time.toMillis() : -1L);
    }

    public static String getUnixDate(long millis) {
        if (millis < 0L) {
            return "------------";
        }

        StringBuilder sb = new StringBuilder(16);
        Calendar cal = new GregorianCalendar();
        cal.setTimeInMillis(millis);

        // month
        sb.append(MONTHS.get(cal.get(Calendar.MONTH)));
        sb.append(' ');

        // day
        int day = cal.get(Calendar.DATE);
        if (day < 10) {
            sb.append(' ');
        }
        sb.append(day);
        sb.append(' ');

        long nowTime = System.currentTimeMillis();
        if (Math.abs(nowTime - millis) > SIX_MONTHS) {

            // year
            int year = cal.get(Calendar.YEAR);
            sb.append(' ');
            sb.append(year);
        } else {
            // hour
            int hh = cal.get(Calendar.HOUR_OF_DAY);
            if (hh < 10) {
                sb.append('0');
            }
            sb.append(hh);
            sb.append(':');

            // minute
            int mm = cal.get(Calendar.MINUTE);
            if (mm < 10) {
                sb.append('0');
            }
            sb.append(mm);
        }

        return sb.toString();
    }
}


text:
package org.scalawag.timber.slf4j.receiver

import org.scalawag.timber.api.Entry
import org.scalawag.timber.backend.receiver.formatter.EntryFormatter
import ch.qos.logback.core.{FileAppender, Context}
import ch.qos.logback.core.rolling._

package object logback {

  def file(
      filename: String,
      name: Option[String] = None,
      append: Option[Boolean] = None,
      prudent: Option[Boolean] = None
  )(implicit formatter: EntryFormatter, context: LogbackContext) = {
    val encoder = new EncoderAdapter(formatter)
    encoder.setContext(context)
    context.add(encoder)

    val appender = new FileAppender[Entry]
    appender.setContext(context)
    appender.setFile(filename)
    appender.setEncoder(encoder)
    name.foreach(appender.setName)
    prudent.foreach(appender.setPrudent)
    append.foreach(appender.setAppend)
    context.add(appender)
    appender
  }

  def rollingFile(
      filename: String,
      rollingPolicy: RollingPolicy,
      triggeringPolicy: Option[TriggeringPolicy[Entry]] = None,
      name: Option[String] = None,
      append: Option[Boolean] = None,
      prudent: Option[Boolean] = None
  )(implicit formatter: EntryFormatter, context: LogbackContext) = {
    val encoder = new EncoderAdapter(formatter)
    encoder.setContext(context)
    context.add(encoder)

    val appender = new RollingFileAppender[Entry]
    appender.setContext(context)
    appender.setFile(filename)
    appender.setEncoder(encoder)
    rollingPolicy.setParent(appender)
    appender.setRollingPolicy(rollingPolicy)
    triggeringPolicy.foreach(appender.setTriggeringPolicy)
    name.foreach(appender.setName)
    prudent.foreach(appender.setPrudent)
    append.foreach(appender.setAppend)
    context.add(appender)
    appender
  }

  def timeBasedRollingPolicy(
      fileNamePattern: String,
      maxHistory: Option[Int] = None,
      cleanHistoryOnStart: Option[Boolean] = None
  )(implicit context: LogbackContext) = {
    val policy = new TimeBasedRollingPolicy[Entry]
    policy.setContext(context)
    policy.setFileNamePattern(fileNamePattern)
    maxHistory.foreach(policy.setMaxHistory)
    cleanHistoryOnStart.foreach(policy.setCleanHistoryOnStart)
    context.add(policy)
    policy
  }

  def fixedWindowRollingPolicy(fileNamePattern: String, minIndex: Option[Int] = None, maxIndex: Option[Int] = None)(
      implicit context: LogbackContext
  ) = {
    val policy = new FixedWindowRollingPolicy
    policy.setContext(context)
    policy.setFileNamePattern(fileNamePattern)
    minIndex.foreach(policy.setMinIndex)
    maxIndex.foreach(policy.setMaxIndex)
    context.add(policy)
    policy
  }

  def sizeBasedTriggeringPolicy(maxFileSize: Option[String] = None)(implicit context: LogbackContext) = {
    val policy = new SizeBasedTriggeringPolicy[Entry]
    policy.setContext(context)
    maxFileSize.foreach(policy.setMaxFileSize)
    context.add(policy)
    policy
  }
}


text:
#ifndef WEBRTC_MODULES_DESKTOP_CAPTURE_CROPPED_DESKTOP_FRAME_H_
#define WEBRTC_MODULES_DESKTOP_CAPTURE_CROPPED_DESKTOP_FRAME_H_

#include "webrtc/modules/desktop_capture/desktop_frame.h"

namespace webrtc {

// Returns nullptr frame if |rect| is not contained by the bounds of |frame|.
std::unique_ptr<DesktopFrame> CreateCroppedDesktopFrame(
    std::unique_ptr<DesktopFrame> frame,
    const DesktopRect& rect);

}  // namespace webrtc

#endif  // WEBRTC_MODULES_DESKTOP_CAPTURE_CROPPED_DESKTOP_FRAME_H_


text:
package edu.gemini.spModel.gemini.calunit;

import edu.gemini.shared.util.StringUtil;
import edu.gemini.spModel.type.DisplayableSpType;
import edu.gemini.spModel.type.ObsoletableSpType;
import edu.gemini.spModel.type.SequenceableSpType;
import edu.gemini.spModel.type.SpTypeUtil;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public final class CalUnitParams {
    public enum LampType {
        arc,
        flat
    }

    /**
     * Lamps
     */
    public enum Lamp implements DisplayableSpType, SequenceableSpType {
        IR_GREY_BODY_HIGH("IR grey body - high", "GCALflat", LampType.flat),
        IR_GREY_BODY_LOW("IR grey body - low", "GCALflat", LampType.flat),
        QUARTZ("Quartz Halogen", "GCALflat", LampType.flat),
        AR_ARC("Ar arc", "Ar", LampType.arc),
        THAR_ARC("ThAr arc", "ThAr", LampType.arc),
        CUAR_ARC("CuAr arc", "CuAr", LampType.arc),
        XE_ARC("Xe arc", "Xe", LampType.arc),
        ;

//        KR_ARC =
//                new Lamp("Kr arc", "Kr", true);

        /** The default Lamp value **/
        public static Lamp DEFAULT = IR_GREY_BODY_HIGH;

        private String _displayValue;

        // Name expected by the TCC software
        private String _tccName;

        // Set to true for arcs
        private LampType _type;

        Lamp(String displayValue, String tccName, LampType lampType) {
            _displayValue = displayValue;
            _tccName      = tccName;
            _type         = lampType;
        }

        public String displayValue() {
            return _displayValue;
        }

        public String sequenceValue() {
            return _displayValue;
        }

        public LampType type() {
            return _type;
        }

        public String toString() {
            return _displayValue;
        }

        /** Return a Lamp by name or the default if not found. **/
        public static Lamp getLamp(String name) {
            return getLamp(name, Lamp.DEFAULT);
        }

        /** Return a Lamp by name, or the given default value if not found. **/
        public static Lamp getLamp(String name, Lamp def) {
            return SpTypeUtil.oldValueOf(Lamp.class, name, def);
        }

        /** Return a Lamp by index **/
        public static Lamp getLampByIndex(int index) {
            return SpTypeUtil.valueOf(Lamp.class, index, DEFAULT);
        }

        /** Return the name expected by the TCC software for this lamp */
        public String getTccName() {
            return _tccName;
        }

        /** Return true if the lamp is an arc */
        public boolean isArc() { return _type == LampType.arc; }

        private static List<Lamp> _flatLamps;
        private static List<Lamp> _arcLamps;

        private static List<Lamp> _getLamps(LampType lampType) {
            return Arrays.stream(values()).filter(l -> l.type() == lampType)
                    .collect(Collectors.toList());
        }

        public synchronized static List<Lamp> flatLamps() {
            if (_flatLamps == null) _flatLamps = _getLamps(LampType.flat);
            return _flatLamps;
        }

        public synchronized static List<Lamp> arcLamps() {
            if (_arcLamps == null) _arcLamps = _getLamps(LampType.arc);
            return _arcLamps;
        }

        public static String show(Collection<Lamp> lamps, StringUtil.MapToString<Lamp> mapper) {
            return StringUtil.mkString(lamps, "", ",", "", mapper);
        }

        public static boolean contains(Collection<Lamp> lamps, LampType type) {
            for (Lamp l : lamps) if (l.type() == type) return true;
            return false;
        }

        public static boolean containsArc(Collection<Lamp> lamps) {
            return contains(lamps, LampType.arc);
        }

        public static List<Lamp> read(String formattedList) {
            String[] ar = formattedList.split(",");
            return Arrays.stream(ar).map(Lamp::getLamp).collect(Collectors.toList());
        }
    }

    /**
     * Filters
     */
    public enum Filter implements DisplayableSpType, ObsoletableSpType, SequenceableSpType {

        NONE("none"),
        ND_10("ND1.0"),
        ND_16("ND1.6") {
            @Override public boolean isObsolete() { return true; }
        },
        ND_20("ND2.0"),
        ND_30("ND3.0"),
        ND_40("ND4.0"),
        ND_45("ND4-5"),
        ND_50("ND5.0") {
            @Override public boolean isObsolete() { return true; }
        },
        GMOS("GMOS balance"),
        HROS("HROS balance") {
            @Override public boolean isObsolete() { return true; }
        },
        NIR("NIR balance"),

        ;

        /** The default Filter value **/
        public static Filter DEFAULT = NONE;

        private String _displayValue;

        Filter(String displayVal) {
            _displayValue = displayVal;
        }

        public String displayValue() {
            return _displayValue;
        }

        public String sequenceValue() {
            return _displayValue;
        }

        public String toString() {
            return _displayValue;
        }

        /** Return a Filter by name or the default if not found. **/
        static public Filter getFilter(String name) {
            return getFilter(name, DEFAULT);
        }

        /** Return a Filter by name or the given default if not found. **/
        static public Filter getFilter(String name, Filter def) {
            return SpTypeUtil.oldValueOf(Filter.class, name, def);
        }

        /** Return a Filter by index **/
        static public Filter getFilterByIndex(int index) {
            return SpTypeUtil.valueOf(Filter.class, index, DEFAULT);
        }
    }

    /**
     * Diffusers
     */
    public enum Diffuser implements DisplayableSpType, SequenceableSpType {
        IR("IR"),
        VISIBLE("visible"),
        ;

        /** The default Diffuser value **/
        public static Diffuser DEFAULT = IR;

        private String _displayValue;

        Diffuser(String displayValue) {
            _displayValue = displayValue;
        }

        public String displayValue() {
            return _displayValue;
        }

        public String sequenceValue() {
            return _displayValue;
        }

        public String toString() {
            return _displayValue;
        }

        /** Return a Diffuser by name or the default if not found. **/
        public static Diffuser getDiffuser(String name) {
            return getDiffuser(name, DEFAULT);
        }

        /** Return a Diffuser by name or the given default if not found **/
        public static Diffuser getDiffuser(String name, Diffuser def) {
            return SpTypeUtil.oldValueOf(Diffuser.class, name, def);
        }

        /** Return a Diffuser by index **/
        public static Diffuser getDiffuserByIndex(int index) {
            return SpTypeUtil.valueOf(Diffuser.class, index, DEFAULT);
        }
    }

    /**
     * IR grey body shutter
     */
    public enum Shutter implements DisplayableSpType, SequenceableSpType {

        OPEN("Open"),
        CLOSED("Closed"),
        ;

        /** The default Shutter value **/
        public static Shutter DEFAULT = OPEN;

        private String _displayValue;

        Shutter(String displayValue) {
            _displayValue = displayValue;
        }

        public String displayValue() {
            return _displayValue;
        }

        public String sequenceValue() {
            return _displayValue;
        }

        public String toString() {
            return _displayValue;
        }

        /** Return a Shutter by name or the default if not found. **/
        public static Shutter getShutter(String name) {
            return getShutter(name, DEFAULT);
        }

        /** Return a Shutter by name or the given default if not found **/
        public static Shutter getShutter(String name, Shutter def) {
            return SpTypeUtil.oldValueOf(Shutter.class, name, def);
        }

        /** Return a Shutter by index **/
        public static Shutter getShutterByIndex(int index) {
            return SpTypeUtil.valueOf(Shutter.class, index, DEFAULT);
        }
    }
}


text:
package grader

import (
	"github.com/omegaup/quark/common"
	"math/big"
	"os"
	"testing"
)

func addRun(
	t *testing.T,
	ctx *Context,
	queue *Queue,
	priority QueuePriority,
) *RunContext {
	AplusB, err := common.NewLiteralInputFactory(
		&common.LiteralInput{
			Cases: map[string]*common.LiteralCaseSettings{
				"0": {Input: "1 2", ExpectedOutput: "3", Weight: big.NewRat(1, 1)},
				"1": {Input: "2 3", ExpectedOutput: "5", Weight: big.NewRat(1, 1)},
			},
			Validator: &common.LiteralValidatorSettings{
				Name: "token-numeric",
			},
		},
		ctx.Config.Grader.RuntimePath,
		common.LiteralPersistGrader,
	)
	if err != nil {
		t.Fatalf("Failed to create Input: %q", err)
	}
	inputRef, err := ctx.InputManager.Add(AplusB.Hash(), AplusB)
	if err != nil {
		t.Fatalf("Failed to get input back: %q", err)
	}
	runCtx := NewEmptyRunContext(ctx)
	runCtx.Priority = priority
	runCtx.Run.InputHash = inputRef.Input.Hash()
	runCtx.Run.Source = "print 3"
	if err := AddRunContext(ctx, runCtx, inputRef); err != nil {
		t.Fatalf("AddRunContext failed with %q", err)
	}
	originalLength := len(queue.runs[priority])
	queue.AddRun(runCtx)
	if len(queue.runs[priority]) != originalLength+1 {
		t.Fatalf(
			"expected len(queue.runs[%d]) == %d, got %d",
			priority,
			originalLength+1,
			len(queue.runs[priority]),
		)
	}
	return runCtx
}

func TestMonitorSerializability(t *testing.T) {
	ctx, err := newGraderContext(t)
	if err != nil {
		t.Fatalf("GraderContext creation failed with %q", err)
	}
	defer ctx.Close()
	if !ctx.Config.Runner.PreserveFiles {
		defer os.RemoveAll(ctx.Config.Grader.RuntimePath)
	}
	ctx.InputManager.MarshalJSON()
	ctx.InflightMonitor.MarshalJSON()
	ctx.QueueManager.MarshalJSON()
}

func TestQueue(t *testing.T) {
	ctx, err := newGraderContext(t)
	if err != nil {
		t.Fatalf("GraderContext creation failed with %q", err)
	}
	defer ctx.Close()
	if !ctx.Config.Runner.PreserveFiles {
		defer os.RemoveAll(ctx.Config.Grader.RuntimePath)
	}

	queue, err := ctx.QueueManager.Get(DefaultQueueName)
	if err != nil {
		t.Fatalf("default queue not found")
	}

	addRun(t, ctx, queue, QueuePriorityNormal)

	closeNotifier := make(chan bool, 1)

	// Test timeout.
	originalConnectTimeout := ctx.InflightMonitor.connectTimeout
	ctx.InflightMonitor.connectTimeout = 0
	runCtx, timeout, _ := queue.GetRun("test", ctx.InflightMonitor, closeNotifier)
	if len(queue.runs[QueuePriorityNormal]) != 0 {
		t.Fatalf(
			"expected len(queue.runs[1]) == %d, got %d",
			0,
			len(queue.runs[QueuePriorityNormal]),
		)
	}
	if _, didTimeout := <-timeout; !didTimeout {
		t.Fatalf("expected timeout but did not happen")
	}
	ctx.InflightMonitor.connectTimeout = originalConnectTimeout

	// The run has already been requeued. This time it will be successful.
	if len(queue.runs[QueuePriorityHigh]) != 1 {
		t.Fatalf(
			"expected len(queue.runs[0]) == %d, got %d",
			1,
			len(queue.runs[QueuePriorityHigh]),
		)
	}
	runCtx, timeout, _ = queue.GetRun("test", ctx.InflightMonitor, closeNotifier)
	if len(queue.runs[QueuePriorityHigh]) != 0 {
		t.Fatalf(
			"expected len(queue.runs[0]) == %d, got %d",
			0,
			len(queue.runs[QueuePriorityHigh]),
		)
	}
	if _, _, ok := ctx.InflightMonitor.Get(runCtx.Run.AttemptID); !ok {
		t.Fatalf("Run %d not found in the inflight run monitor", runCtx.Run.AttemptID)
	}
	ctx.InflightMonitor.Remove(runCtx.Run.AttemptID)
	if _, didTimeout := <-timeout; didTimeout {
		t.Fatalf("expected run completion, but did not happen")
	}

	// Test the closeNotifier.
	closeNotifier <- true
	if _, _, ok := queue.GetRun(
		"test",
		ctx.InflightMonitor,
		closeNotifier,
	); ok {
		t.Fatalf("Expected closeNotifier to cause no run to be available")
	}
}

func TestQueuePriorities(t *testing.T) {
	ctx, err := newGraderContext(t)
	if err != nil {
		t.Fatalf("GraderContext creation failed with %q", err)
	}
	defer ctx.Close()
	if !ctx.Config.Runner.PreserveFiles {
		defer os.RemoveAll(ctx.Config.Grader.RuntimePath)
	}

	queue, err := ctx.QueueManager.Get(DefaultQueueName)
	if err != nil {
		t.Fatalf("default queue not found")
	}

	closeNotifier := make(chan bool, 1)

	ephemeralPriority := addRun(t, ctx, queue, QueuePriorityEphemeral)
	lowPriority := addRun(t, ctx, queue, QueuePriorityLow)
	normalPriority := addRun(t, ctx, queue, QueuePriorityNormal)
	highPriority := addRun(t, ctx, queue, QueuePriorityHigh)

	var runCtx *RunContext
	runCtx, _, _ = queue.GetRun("test", ctx.InflightMonitor, closeNotifier)
	if runCtx != highPriority {
		t.Fatalf("expected runCtx == %v, got %v", highPriority, runCtx)
	}
	runCtx, _, _ = queue.GetRun("test", ctx.InflightMonitor, closeNotifier)
	if runCtx != normalPriority {
		t.Fatalf("expected runCtx == %v, got %v", normalPriority, runCtx)
	}
	runCtx, _, _ = queue.GetRun("test", ctx.InflightMonitor, closeNotifier)
	if runCtx != lowPriority {
		t.Fatalf("expected runCtx == %v, got %v", lowPriority, runCtx)
	}
	runCtx, _, _ = queue.GetRun("test", ctx.InflightMonitor, closeNotifier)
	if runCtx != ephemeralPriority {
		t.Fatalf("expected runCtx == %v, got %v", ephemeralPriority, runCtx)
	}

	queueInfo := ctx.QueueManager.GetQueueInfo()[DefaultQueueName]
	if queueInfo.Lengths[QueuePriorityEphemeral] != 0 {
		t.Errorf(
			"expected queueInfo.Lengths[%d] == %d, got %d",
			QueuePriorityEphemeral,
			0,
			queueInfo.Lengths[QueuePriorityEphemeral],
		)
	}
	if queueInfo.Lengths[QueuePriorityLow] != 0 {
		t.Errorf(
			"expected queueInfo.Lengths[%d] == %d, got %d",
			QueuePriorityLow,
			0,
			queueInfo.Lengths[QueuePriorityLow],
		)
	}
	if queueInfo.Lengths[QueuePriorityNormal] != 0 {
		t.Errorf(
			"expected queueInfo.Lengths[%d] == %d, got %d",
			QueuePriorityNormal,
			0,
			queueInfo.Lengths[QueuePriorityNormal],
		)
	}
	if queueInfo.Lengths[QueuePriorityHigh] != 0 {
		t.Errorf(
			"expected queueInfo.Lengths[%d] == %d, got %d",
			QueuePriorityHigh,
			0,
			queueInfo.Lengths[QueuePriorityHigh],
		)
	}
}

type listener struct {
	c         chan *RunInfo
	done      chan struct{}
	processed int
}

func newListener() *listener {
	l := &listener{
		c:         make(chan *RunInfo, 0),
		done:      make(chan struct{}, 0),
		processed: 0,
	}
	go func() {
		for range l.c {
			l.processed++
		}
		close(l.done)
	}()
	return l
}

func TestPostProcessor(t *testing.T) {
	ctx, err := newGraderContext(t)
	if err != nil {
		t.Fatalf("GraderContext creation failed with %q", err)
	}
	defer ctx.Close()
	if !ctx.Config.Runner.PreserveFiles {
		defer os.RemoveAll(ctx.Config.Grader.RuntimePath)
	}

	pp := NewRunPostProcessor()
	go pp.run()
	listeners := make([]*listener, 10)

	for i := range listeners {
		listeners[i] = newListener()
		pp.AddListener(listeners[i].c)
	}

	numProcessed := 10
	for i := 0; i < numProcessed; i++ {
		pp.PostProcess(&RunInfo{})
	}

	pp.Close()

	for i := range listeners {
		select {
		case <-listeners[i].done:
		}
		if listeners[i].processed != numProcessed {
			t.Fatalf("listeners[%d].processed == %d, want %d", i, listeners[i].processed, numProcessed)
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.lazarusid.tenoncalculator" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/tenon_calculator"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".TenonActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text: set SSL_CERT_FILE=cacert.pem


text:
@extends('layout.dashboard')

@section('content')

             {{ trans('dashboard.metrics.metrics') }}

        > {{ trans('dashboard.metrics.edit.title') }}

                @include('dashboard.partials.errors')
                <form class='form-vertical' name='MetricsForm' role='form' method='POST'>
                    <input type="hidden" name="_token" value="{{ csrf_token() }}">
                    <fieldset>

                            {{ trans('forms.metrics.name') }}
                            <input type="text" class="form-control" name="metric[name]" id="metric-name" required value="{{ $metric->name }}">

                            {{ trans('forms.metrics.suffix') }}
                            <input type="text" class="form-control" name="metric[suffix]" id="metric-suffix" required value="{{ $metric->suffix }}">

                            {{ trans('forms.metrics.description') }}

                                <textarea name="metric[description]" class="form-control" rows="5">{{ $metric->description }}</textarea>

                            {{ trans('forms.metrics.calc_type') }}
                            <select name="metric[calc_type]" class="form-control" required>
                                <option value="0" {{ $metric->calc_type === 0 ? "selected" : null }}>{{ trans('forms.metrics.type_sum') }}</option>
                                <option value="1" {{ $metric->calc_type === 1 ? "selected" : null }}>{{ trans('forms.metrics.type_avg') }}</option>
                            </select>

                            {{ trans('forms.metrics.default-value') }}
                            <input type="number" class="form-control" name="metric[default_value]" id="metric-default_value" value="{{ $metric->default_value }}">

                            {{ trans('forms.metrics.places') }}
                            <input type="number" min="0" max="4" class="form-control" name="metric[places]" id="metric-places" required value="{{ $metric->places }}">

                                <input type="hidden" value="0" name="metric[display_chart]">
                                <input type="checkbox" value="1" name="metric[display_chart]" {{ $metric->display_chart ? 'checked' : null }}>
                                {{ trans('forms.metrics.display-chart') }}

                    </fieldset>

                    <input type="hidden" name="metric[id]" value={{$metric->id}}>

                            <button type="submit" class="btn btn-success">{{ trans('forms.update') }}</button>
                            {{ trans('forms.cancel') }}

                </form>

@stop


text:
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */

#ifndef NATIVE_EXTENSION_VTK_VTKXOPENGLRENDERWINDOWWRAP_H
#define NATIVE_EXTENSION_VTK_VTKXOPENGLRENDERWINDOWWRAP_H

#include <nan.h>

#include <vtkSmartPointer.h>
#include <vtkXOpenGLRenderWindow.h>

#include "vtkOpenGLRenderWindowWrap.h"
#include "../../plus/plus.h"

class VtkXOpenGLRenderWindowWrap : public VtkOpenGLRenderWindowWrap
{
	public:
		using Nan::ObjectWrap::Wrap;
		static void Init(v8::Local<v8::Object> exports);
		static void InitPtpl();
		static void ConstructorGetter(
			v8::Local<v8::String> property,
			const Nan::PropertyCallbackInfo<v8::Value>& info);

		VtkXOpenGLRenderWindowWrap(vtkSmartPointer<vtkXOpenGLRenderWindow>);
		VtkXOpenGLRenderWindowWrap();
		~VtkXOpenGLRenderWindowWrap( );
		static Nan::Persistent<v8::FunctionTemplate> ptpl;

	private:
		static void New(const Nan::FunctionCallbackInfo<v8::Value>& info);

		static void Finalize(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void Frame(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetDesiredDepth(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetEventPending(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetPosition(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetScreenSize(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void HideCursor(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void Initialize(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void InitializeFromCurrentContext(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void IsCurrent(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void IsDirect(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void MakeCurrent(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void PopContext(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void PrefFullScreen(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void PushContext(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void Render(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void ReportCapabilities(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetCurrentCursor(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetForceMakeCurrent(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetFullScreen(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetNextWindowInfo(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetOffScreenRendering(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetParentInfo(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetPosition(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetSize(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetStereoCapableWindow(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetSwapControl(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetWindowInfo(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetWindowName(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void ShowCursor(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void Start(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void WindowInitialize(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void WindowRemap(const Nan::FunctionCallbackInfo<v8::Value>& info);

#ifdef VTK_NODE_PLUS_VTKXOPENGLRENDERWINDOWWRAP_CLASSDEF
		VTK_NODE_PLUS_VTKXOPENGLRENDERWINDOWWRAP_CLASSDEF
#endif
};

#endif


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace FirstTestSolution
{
    [TestClass]
    public class DiscounTests
    {
        [TestMethod]
        public void TestDiscountMethod()
        {
            double total = 100;
            bool vipclient = true;

            if (total > 1000 || vipclient)
            {
                total = total * 0.9;
                System.Console.Out.Write("Скидка 10%, общая сумма " + total);
            }
            /*else
            {
                System.Console.Out.Write("Скидка не предоставляется. Общая сумма " + total);
            }*/
        }
    }
}


text:
<ion-modal-view class="add-habit-modal">
  <ion-header-bar class="bar bar-header bar-positive" ng-click="addModal.hide()">

Add Habit

    <button class="button button-clear button-primary" ng-click="showAddModal.hide()">Close</button>
  </ion-header-bar>
  <ion-content class="padding" scroll="false">

        Name
        <input type="text" placeholder="Work Out" ng-model="habit.name">

        Abbreviation
        <input type="text" placeholder="WO" ng-model="habit.abbreviation">

        Color

      <button class="button button-full button-positive" ng-click="date.addHabit(habit); habit = null;" type="submit">Add</button>

  </ion-content>
</ion-modal-view>


text:
<?xml version="1.0" encoding="utf-8"?>
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2012/deployment" AppPlatformVersion="8.0">
  <DefaultLanguage xmlns="" code="en-US" />
  <App xmlns="" ProductID="{7f6f7687-356e-4ab7-9859-144d74491e88}" Title="Frame" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal" Author="Frame_for_WP author" Description="Sample description" Publisher="Frame_for_WP" PublisherID="{8a838a46-2998-4457-bbdf-9abbcb3d6649}">
    <IconPath IsRelative="true" IsResource="false">Assets\ApplicationIcon.png</IconPath>
    <Capabilities>
      <Capability Name="ID_CAP_NETWORKING" />
      <Capability Name="ID_CAP_MEDIALIB_AUDIO" />
      <Capability Name="ID_CAP_MEDIALIB_PLAYBACK" />
      <Capability Name="ID_CAP_SENSORS" />
      <Capability Name="ID_CAP_WEBBROWSERCOMPONENT" />
      <Capability Name="ID_CAP_ISV_CAMERA" />
    </Capabilities>
    <Tasks>
      <DefaultTask Name="_default" NavigationPage="View/MainPage.xaml" />
    </Tasks>
    <Tokens>
      <PrimaryToken TokenID="Frame_for_WPToken" TaskName="_default">
        <TemplateFlip>
          <SmallImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileSmall.png</SmallImageURI>
          <Count>0</Count>
          <BackgroundImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileMedium.png</BackgroundImageURI>
          <Title>Frame_for_WP</Title>
          <BackContent>
          </BackContent>
          <BackBackgroundImageURI>
          </BackBackgroundImageURI>
          <BackTitle>
          </BackTitle>
          <DeviceLockImageURI>
          </DeviceLockImageURI>
          <HasLarge>
          </HasLarge>
        </TemplateFlip>
      </PrimaryToken>
    </Tokens>
    <ScreenResolutions>
      <ScreenResolution Name="ID_RESOLUTION_WVGA" />
      <ScreenResolution Name="ID_RESOLUTION_WXGA" />
      <ScreenResolution Name="ID_RESOLUTION_HD720P" />
    </ScreenResolutions>
    <Requirements>
      <Requirement Name="ID_REQ_REARCAMERA" />
    </Requirements>
  </App>
</Deployment>


text:
package com.facebook.buck.rules;

import static org.junit.Assert.assertTrue;

import com.facebook.buck.artifact_cache.ArtifactCache;
import com.facebook.buck.artifact_cache.DirArtifactCacheTestUtil;
import com.facebook.buck.artifact_cache.TestArtifactCaches;
import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildId;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.facebook.buck.timing.DefaultClock;
import com.facebook.buck.util.ObjectMappers;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;

import org.junit.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Optional;

public class BuildInfoRecorderIntegrationTest {
  private static final String RULE_KEY = Strings.repeat("a", 40);

  private static final BuildTarget BUILD_TARGET = BuildTargetFactory.newInstance("//foo:bar");

  @Test
  public void testPerformUploadToArtifactCache() throws IOException, InterruptedException {
    BuildInfoRecorder buildInfoRecorder = createBuildInfoRecorder(
        new FakeProjectFilesystem() {
            @Override
            public void createZip(
                Collection<Path> pathsToIncludeInZip,
                Path out,
                ImmutableMap<Path, String> additionalFileContents) throws IOException {
              // For this test, nothing really cares about the content, so just write out the name.
              writeBytesToPath(out.toString().getBytes(), out);
            }
        });
    Path cacheDir = Files.createTempDirectory("root");
    ArtifactCache artifactCache = TestArtifactCaches
        .createDirCacheForTest(cacheDir, Paths.get("cache"));
    buildInfoRecorder.performUploadToArtifactCache(
        ImmutableSet.of(new RuleKey(RULE_KEY)),
        artifactCache,
        new BuckEventBus(new DefaultClock(), new BuildId()));
    assertTrue(
        cacheDir.resolve(
            DirArtifactCacheTestUtil
                .getPathForRuleKey(
                    artifactCache,
                    new RuleKey(RULE_KEY),
                    Optional.empty()))
        .toFile()
        .exists());
  }

  private static BuildInfoRecorder createBuildInfoRecorder(ProjectFilesystem filesystem) {
    return new BuildInfoRecorder(
        BUILD_TARGET,
        filesystem,
        new DefaultClock(),
        new BuildId(),
        ObjectMappers.newDefaultInstance(),
        ImmutableMap.of());
  }
}


text:
#ifndef ARM_COMPUTE_NEBOUNDINGBOXTRANSFORMKERNEL_H
#define ARM_COMPUTE_NEBOUNDINGBOXTRANSFORMKERNEL_H

#include "src/core/NEON/INEKernel.h"

namespace arm_compute
{
class ITensor;

/** Interface for the bounding box kernel */
class NEBoundingBoxTransformKernel : public INEKernel
{
public:
    const char *name() const override
    {
        return "NEBoundingBoxTransformKernel";
    }

    /** Default constructor */
    NEBoundingBoxTransformKernel();
    /** Prevent instances of this class from being copied (As this class contains pointers) */
    NEBoundingBoxTransformKernel(const NEBoundingBoxTransformKernel &) = delete;
    /** Prevent instances of this class from being copied (As this class contains pointers) */
    NEBoundingBoxTransformKernel &operator=(const NEBoundingBoxTransformKernel &) = delete;
    /** Allow instances of this class to be moved */
    NEBoundingBoxTransformKernel(NEBoundingBoxTransformKernel &&) = default;
    /** Allow instances of this class to be moved */
    NEBoundingBoxTransformKernel &operator=(NEBoundingBoxTransformKernel &&) = default;
    /** Default destructor */
    ~NEBoundingBoxTransformKernel() = default;

    /** Set the input and output tensors.
     *
     * @param[in]  boxes      Source tensor. Bounding box proposals in pixel coordinates. Size(M, 4), format [x1, y1, x2, y2]. Data types supported: QASYMM16/F16/F32.
     * @param[out] pred_boxes Destination tensor. Pixel coordinates of the transformed bounding boxes. Size (M, 4*K), format [x1, y1, x2, y2]. Data types supported: Same as @p input
     * @param[in]  deltas     Bounding box translations and scales. Size (M, 4*K), format [dx, dy, dw, dh], K  is the number of classes.
     *                        Data types supported: QASYMM8 if @p input is QASYMM16, otherwise same as @p input.
     * @param[in]  info       Contains BoundingBox operation information described in @ref BoundingBoxTransformInfo.
     *
     * @note Only single image prediction is supported. Height and Width (and scale) of the image will be contained in the BoundingBoxTransformInfo struct.
     *
     */
    void configure(const ITensor *boxes, ITensor *pred_boxes, const ITensor *deltas, const BoundingBoxTransformInfo &info);

    /** Static function to check if given info will lead to a valid configuration of @ref CLBoundingBoxTransform
     *
     * @param[in] boxes      Source tensor info. Bounding box proposals in pixel coordinates. Size(M, 4), format [x1, y1, x2, y2]. Data types supported: QASYMM16/F16/F32.
     * @param[in] pred_boxes Destination tensor info. Pixel coordinates of the transformed bounding boxes. Size (M, 4*K), format [x1, y1, x2, y2]. Data types supported: Same as @p input
     * @param[in] deltas     Bounding box translations and scales. Size (M, 4*K), format [dx, dy, dw, dh], K  is the number of classes.
     *                       Data types supported: QASYMM8 if @p input is QASYMM16, otherwise same as @p input.
     * @param[in] info       Contains BoundingBox operation information described in @ref BoundingBoxTransformInfo.
     *
     * @note Only single image prediction is supported. Height and Width (and scale) of the image will be contained in the BoundingBoxTransformInfo struct.
     *
     * @return a Status
     */
    static Status validate(const ITensorInfo *boxes, const ITensorInfo *pred_boxes, const ITensorInfo *deltas, const BoundingBoxTransformInfo &info);

    // Inherited methods overridden:
    void run(const Window &window, const ThreadInfo &info) override;

private:
    const ITensor           *_boxes;
    ITensor                 *_pred_boxes;
    const ITensor           *_deltas;
    BoundingBoxTransformInfo _bbinfo;
};
} // namespace arm_compute
#endif /*ARM_COMPUTE_NEBOUNDINGBOXTRANSFORMKERNEL_H */