text:
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/cli/README.md.mako'
DO NOT EDIT !
-->
The `adsense1d4` command-line interface *(CLI)* allows to use most features of the *Google AdSense* service from the comfort of your terminal.

By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's
capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero.

If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools.

Everything else about the *AdSense* API can be found at the
[official documentation site](https://developers.google.com/adsense/management/).

# Downloads

You can download the pre-compiled 64bit binaries for the following platforms:

* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.1/ubuntu/adsense1d4.tar.gz)
* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.1/osx/adsense1d4.tar.gz)

Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/adsense1d4-cli).

# Usage

This documentation was generated from the *AdSense* API at revision *20150617*. The CLI is at version *0.3.1*.

```bash
adsense1d4 [options]
        accounts
                adclients-list <account-id> [-p <v>]... [-o <out>]
                adunits-customchannels-list <account-id> <ad-client-id> <ad-unit-id> [-p <v>]... [-o <out>]
                adunits-get <account-id> <ad-client-id> <ad-unit-id> [-p <v>]... [-o <out>]
                adunits-get-ad-code <account-id> <ad-client-id> <ad-unit-id> [-p <v>]... [-o <out>]
                adunits-list <account-id> <ad-client-id> [-p <v>]... [-o <out>]
                alerts-delete <account-id> <alert-id> [-p <v>]...
                alerts-list <account-id> [-p <v>]... [-o <out>]
                customchannels-adunits-list <account-id> <ad-client-id> <custom-channel-id> [-p <v>]... [-o <out>]
                customchannels-get <account-id> <ad-client-id> <custom-channel-id> [-p <v>]... [-o <out>]
                customchannels-list <account-id> <ad-client-id> [-p <v>]... [-o <out>]
                get <account-id> [-p <v>]... [-o <out>]
                list [-p <v>]... [-o <out>]
                payments-list <account-id> [-p <v>]... [-o <out>]
                reports-generate <account-id> <start-date> <end-date> [-p <v>]... [-o <out>]
                reports-saved-generate <account-id> <saved-report-id> [-p <v>]... [-o <out>]
                reports-saved-list <account-id> [-p <v>]... [-o <out>]
                savedadstyles-get <account-id> <saved-ad-style-id> [-p <v>]... [-o <out>]
                savedadstyles-list <account-id> [-p <v>]... [-o <out>]
                urlchannels-list <account-id> <ad-client-id> [-p <v>]... [-o <out>]
        adclients
                list [-p <v>]... [-o <out>]
        adunits
                customchannels-list <ad-client-id> <ad-unit-id> [-p <v>]... [-o <out>]
                get <ad-client-id> <ad-unit-id> [-p <v>]... [-o <out>]
                get-ad-code <ad-client-id> <ad-unit-id> [-p <v>]... [-o <out>]
                list <ad-client-id> [-p <v>]... [-o <out>]
        alerts
                delete <alert-id> [-p <v>]...
                list [-p <v>]... [-o <out>]
        customchannels
                adunits-list <ad-client-id> <custom-channel-id> [-p <v>]... [-o <out>]
                get <ad-client-id> <custom-channel-id> [-p <v>]... [-o <out>]
                list <ad-client-id> [-p <v>]... [-o <out>]
        metadata
                dimensions-list [-p <v>]... [-o <out>]
                metrics-list [-p <v>]... [-o <out>]
        payments
                list [-p <v>]... [-o <out>]
        reports
                generate <start-date> <end-date> [-p <v>]... [-o <out>]
                saved-generate <saved-report-id> [-p <v>]... [-o <out>]
                saved-list [-p <v>]... [-o <out>]
        savedadstyles
                get <saved-ad-style-id> [-p <v>]... [-o <out>]
                list [-p <v>]... [-o <out>]
        urlchannels
                list <ad-client-id> [-p <v>]... [-o <out>]
  adsense1d4 --help

Configuration:
  [--scope <url>]...
            Specify the authentication a method should be executed in. Each scope
            requires the user to grant this application permission to use it.
            If unset, it defaults to the shortest scope url for a particular method.
  --config-dir <folder>
            A directory into which we will store our persistent data. Defaults to
            a user-writable directory that we will create during the first invocation.
            [default: ~/.google-service-cli]
  --debug
            Output all server communication to standard error. `tx` and `rx` are placed
            into the same stream.
  --debug-auth
            Output all communication related to authentication to standard error. `tx`
            and `rx` are placed into the same stream.

```

# Configuration

The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `adsense1d4-`.  You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis.

More information about the various kinds of persistent data are given in the following paragraphs.

# Authentication

Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the
set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*.

If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a
method that is read-only, it will ask only for a read-only scope.
You may use the `--scope` flag to specify a scope directly.
All applicable scopes are documented in the respective method's CLI documentation.

The first time a scope is used, the user is asked for permission. Follow the instructions given
by the CLI to grant permissions, or to decline.

If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration
directory, e.g. `~/.google-service-cli/adsense1d4-token-<scope-hash>.json`. No manual management of these tokens
is necessary.

To revoke granted authentication, please refer to the [official documentation][revoke-access].

# Application Secrets

In order to allow any application to use Google services, it will need to be registered using the
[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it
one by one. Most APIs can be used for free and have a daily quota.

To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI
comes with a default application secret that is configured accordingly. This also means that heavy usage
all around the world may deplete the daily quota.

You can workaround this limitation by putting your own secrets file at this location:
`~/.google-service-cli/adsense1d4-secret.json`, assuming that the required *adsense* API
was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at
*APIs & auth -> Credentials -> Download JSON* and used as is.

Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new].

# Debugging

Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know
what exactly led to a particular issue. This is done by allowing all client-server communication to be
output to standard error *as-is*.

The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag
will cause all communication related to authentication to standard error.
If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the
issue at hand.

You may consider redirecting standard error into a file for ease of use, e.g. `adsense1d4 --debug <resource> <method> [options] 2>debug.txt`.

[scopes]: https://developers.google.com/+/api/oauth#scopes
[revoke-access]: http://webapps.stackexchange.com/a/30849
[google-dev-console]: https://console.developers.google.com/
[google-project-new]: https://developers.google.com/console/help/new/


text:
#nullable enable

using System;
using System.Collections.Generic;

namespace OmniSharp.Models.v1.Completion
{
    public class CompletionItem
    {
        /// <summary>
        /// The label of this completion item. By default
        /// also the text that is inserted when selecting
        /// this completion.
        /// </summary>
        public string Label { get; set; } = null!;

        /// <summary>
        /// The kind of this completion item. Based of the kind
        /// an icon is chosen by the editor.The standardized set
        /// of available values is defined in <see cref="CompletionItemKind"/>
        /// </summary>
        public CompletionItemKind Kind { get; set; }

        /// <summary>
        /// Tags for this completion item
        /// </summary>
        public IReadOnlyList<CompletionItemTag>? Tags { get; set; }

        /// <summary>
        /// A human-readable string with additional information
        /// about this item, like type or symbol information
        /// </summary>
        public string? Detail { get; set; }

        /// <summary>
        /// A human-readable string that represents a doc-comment. This is
        /// formatted as markdown.
        /// </summary>
        public string? Documentation { get; set; }

        /// <summary>
        /// Select this item when showing.
        /// </summary>
        public bool Preselect { get; set; }

        /// <summary>
        /// A string that should be used when comparing this item
        /// with other items. When null or empty the label is used.
        /// </summary>
        public string? SortText { get; set; }

        /// <summary>
        /// A string that should be used when filtering a set of
        /// completion items. When null or empty the label is used.
        /// </summary>
        public string? FilterText { get; set; }

        /// <summary>
        /// The format of <see cref="InsertText"/>. This applies to both <see cref="InsertText"/> and
        /// <see cref="TextEdit"/>.<see cref="LinePositionSpanTextChange.NewText"/>.
        /// </summary>
        public InsertTextFormat InsertTextFormat { get; set; }

        /// <summary>
        /// An edit which is applied to a document when selecting this completion. When an edit is provided the value of
        /// <see cref="InsertText"/> is ignored.
        /// </summary>
        public LinePositionSpanTextChange? TextEdit { get; set; }

        /// <summary>
        /// An optional set of characters that when pressed while this completion is active will accept it first and
        /// then type that character.
        /// </summary>
        public IReadOnlyList<char>? CommitCharacters { get; set; }

        /// <summary>
        /// An optional array of additional text edits that are applied when
        /// selecting this completion.Edits must not overlap (including the same insert position)
        /// with the main edit nor with themselves.
        ///
        /// Additional text edits should be used to change text unrelated to the current cursor position
        /// (for example adding an import statement at the top of the file if the completion item will
        /// insert an unqualified type).
        /// </summary>
        public IReadOnlyList<LinePositionSpanTextChange>? AdditionalTextEdits { get; set; }

        /// <summary>
        /// Index in the completions list that this completion occurred.
        /// </summary>
        public (long CacheId, int Index) Data { get; set; }

        /// <summary>
        /// True if there is a post-insert step for this completion item for asynchronous completion support.
        /// </summary>
        public bool HasAfterInsertStep { get; set; }

        public override string ToString()
        {
            return $"{{ {nameof(Label)} = {Label}, {nameof(CompletionItemKind)} = {Kind} }}";
        }
    }

    public enum CompletionItemKind
    {
        Text = 1,
        Method = 2,
        Function = 3,
        Constructor = 4,
        Field = 5,
        Variable = 6,
        Class = 7,
        Interface = 8,
        Module = 9,
        Property = 10,
        Unit = 11,
        Value = 12,
        Enum = 13,
        Keyword = 14,
        Snippet = 15,
        Color = 16,
        File = 17,
        Reference = 18,
        Folder = 19,
        EnumMember = 20,
        Constant = 21,
        Struct = 22,
        Event = 23,
        Operator = 24,
        TypeParameter = 25,
    }

    public enum CompletionItemTag
    {
        Deprecated = 1,
    }

    public enum InsertTextFormat
    {
        PlainText = 1,
        // TODO: Support snippets
        Snippet = 2,
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* row */
.budget-table-row.toolkit-row-availablenegative .budget-table-cell-available .cautious {
	background: #d33c2d !important;
}
.budget-table-row.toolkit-row-availablenegative .budget-table-cell-available .cautious:hover {
	background: #b43326 !important;
}

/* pacing column */
li.budget-table-cell-pacing span.cautious {
    background: #d33c2d !important;
}
li.budget-table-cell-pacing .budget-table-cell-pacing-display.cautious:hover {
	background: #b43326 !important;
}
li.budget-table-cell-pacing span.deemphasized.cautious,
li.budget-table-cell-pacing span.deemphasized.cautious:hover {
    background: none !important;
}

/* inspector */
.budget-inspector-category-overview .toolkit-row-availablenegative dt.cautious {
	color: #d33c2d;
}
.budget-inspector-category-overview .toolkit-row-availablenegative dd .cautious {
	background: #d33c2d;
}


text:
This is a small extension to Caliburn Micro (until it's in Caliburn.Micro proper? :))
that adds a bindable appbar, with full support for Pivot- and Panorama-conducted views.

Licensed under the [MIT license](LICENSE.md).

## Changelog

* 2.0.0
    - **REMOVED** support for Windows Phone 7 (use 1.x versions instead)
    - Update to support Caliburn.Micro 2.0 (thanks @jagui)
    - Changed `BackgroundColor`, `ForegroundColor`, `BarOpacity`, and `IsMenuEnabled` to DependencyProperties (thanks @belyansky)
    - Allow syncing appbar in hardcoded Panorama (thanks @matopeto)

* 1.0.5
	- Fix issue with background/foreground color (#13)
	- Fix sample WP80 issue with pivot and navigation (#9)
	- Update to Caliburn.Micro 1.5.2
	- Fix exceptions being thrown in design-time

* 1.0.4
	- Support PhoneApplicationPage as Pivot items (#8)
	- Add `Invalidated` event to make handling theming easier

* 1.0.3
	- Check if parent is null before invalidating appbar (#3)

* 1.0.2
	- Fix issue with WP8 when using swappable bars + Pivot

* 1.0.1
	- Fix issue with swappable bars

* 1.0.0
	- Initial release

## Features

* `BindableAppBar`, `BindableAppBarButton`, and `BindableAppBarMenuItem`
  are all full `DependencyObjects` so they can support full binding capabilities
* Full Caliburn message functionality (`cal:Message.Attach`)
* Bind icons
* Bind text
* Bind bar, button, and menu item visibility
* Support for automatic `Click` convention
* "Hot Swappable" app bars (multiple appbars per view with visibility bindings)
* `AppBarConductor` fully syncs with Panorama and Pivot controls, so you can have multiple appbar configurations

## Known Issues

* The Panorama control aborts transitions when you change the ApplicationBar's visibility (`null`, `Opacity = 0`, etc.)
  so to workaround it, there's a small background sleep of a configurable wait time (`PanoramaWaitThreshold`)

* Panorama is weird on Windows Phone 8 and the BAB doesn't play nice with it.

## Installation

Install via Nuget (also will install Caliburn.Micro):

	PM> Install-Package Caliburn.Micro.BindableAppBar

Once installed, you can wireup the default `Click` convention in your bootstrapper:

	static void AddCustomConventions()
    {

        // App Bar Conventions
        ConventionManager.AddElementConvention<BindableAppBarButton>(
            Control.IsEnabledProperty, "DataContext", "Click");
        ConventionManager.AddElementConvention<BindableAppBarMenuItem>(
            Control.IsEnabledProperty, "DataContext", "Click");

		// ... the rest of your conventions
	}

## Usage

### Single View

If you only need to bind an appbar on one page, it's very straightforward:

    <bab:BindableAppBar x:Name="AppBar">
        <bab:BindableAppBarButton
            x:Name="Add"
            Text="{Binding AddButtonText}"
            Visibility="{Binding ShowAddButton, Converter={StaticResource BooleanToVisibilityConverter}}"
            IconUri="{Binding ButtonIconUri}"/>

        <bab:BindableAppBarMenuItem
            x:Name="Pin"
            Text="{Binding PinItemText}" />
    </bab:BindableAppBar>

### Conducted Page

This is where things get interesting. Often times, you have a conductor with multiple pages.
It's simple to wireup your conductor to the appbar:

    public class SampleConductorBase : Conductor<Screen>.Collection.OneActive {

        public SampleConductorBase() {

        }

        protected override void OnInitialize() {
            base.OnInitialize();

            Items.Add(new Item1ViewModel());
            Items.Add(new Item2ViewModel() { ShowAppBar = true });
            Items.Add(new Item2ViewModel());

            ActivateItem(Items[0]);

            // Initialize appbar, the views have been attached by this point
            AppBarConductor.Mixin(this);
        }
    }

There are a few requirements:

1. Your conducted page must contain a `Pivot` or `Panorama` control
2. When you attach the `AppBarConductor`, it is after you have initialized the default items

You can adjust the `Panorama` animation wait threshold easily:

	AppBarConductor.Mixin(this, panoramaWaitThreshold: 1000);

## More Information

Please see the Sample project in the source for some examples of usage.


text:
/*

demo3.c

Author: Sandro Furieri a-furieri@lqt.it

This software is provided 'as-is', without any express or implied
warranty.  In no event will the author be held liable for any
damages arising from the use of this software.

Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely

*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

/*
these headers are required in order to support
SQLite/SpatiaLite
*/
#include <sqlite3.h>
#include <spatialite/gaiageo.h>
#include <spatialite.h>

int
main (int argc, char *argv[])
{
    int ret;
    sqlite3 *handle;
    sqlite3_stmt *stmt;
    char sql[256];
    char *err_msg = NULL;
    double x;
    double y;
    int pk;
    int ix;
    int iy;
    gaiaGeomCollPtr geo = NULL;
    unsigned char *blob;
    int blob_size;
    int i;
    char **results;
    int n_rows;
    int n_columns;
    char *count;
    clock_t t0;
    clock_t t1;

    if (argc != 2)
      {
	  fprintf (stderr, "usage: %s test_db_path\n", argv[0]);
	  return -1;
      }

/*
VERY IMPORTANT:
you must initialize the SpatiaLite extension [and related]
BEFORE attempting to perform any other SQLite call
*/
    spatialite_init (0);

/* showing the SQLite version */
    printf ("SQLite version: %s\n", sqlite3_libversion ());
/* showing the SpatiaLite version */
    printf ("SpatiaLite version: %s\n", spatialite_version ());
    printf ("\n\n");

/*
trying to connect the test DB:
- this demo is intended to create a new, empty database
*/
    ret = sqlite3_open_v2 (argv[1], &handle,
			   SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
    if (ret != SQLITE_OK)
      {
	  printf ("cannot open '%s': %s\n", argv[1], sqlite3_errmsg (handle));
	  sqlite3_close (handle);
	  return -1;
      }

/*
we are supposing this one is an empty database,
so we have to create the Spatial Metadata
*/
    strcpy (sql, "SELECT InitSpatialMetadata()");
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
/* an error occurred */
	  printf ("InitSpatialMetadata() error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  goto abort;
      }

/*
now we can create the test table
for simplicity we'll define only one column, the primary key
*/
    strcpy (sql, "CREATE TABLE test (");
    strcat (sql, "PK INTEGER NOT NULL PRIMARY KEY)");
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
/* an error occurred */
	  printf ("CREATE TABLE 'test' error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  goto abort;
      }

/*
... we'll add a Geometry column of POINT type to the test table
*/
    strcpy (sql, "SELECT AddGeometryColumn('test', 'geom', 3003, 'POINT', 2)");
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
/* an error occurred */
	  printf ("AddGeometryColumn() error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  goto abort;
      }

/*
and finally we'll enable this geo-column to have a Spatial Index based on R*Tree
*/
    strcpy (sql, "SELECT CreateSpatialIndex('test', 'geom')");
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
/* an error occurred */
	  printf ("CreateSpatialIndex() error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  goto abort;
      }

    printf
	("\nnow we are going to insert 1 million POINTs; wait, please ...\n\n");

    t0 = clock ();
/*
beginning a transaction

*** this step is absolutely critical ***

the SQLite engine is a TRANSACTIONAL one
the whole batch of INSERTs has to be performed as an unique transaction,
otherwise performance will be surely very poor
*/
    strcpy (sql, "BEGIN");
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
/* an error occurred */
	  printf ("BEGIN error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  goto abort;
      }

/*
preparing to populate the test table
we'll use a Prepared Statement we can reuse in order to insert each row
*/
    strcpy (sql, "INSERT INTO test (pk, geom) VALUES (?, ?)");
    ret = sqlite3_prepare_v2 (handle, sql, strlen (sql), &stmt, NULL);
    if (ret != SQLITE_OK)
      {
/* an error occurred */
	  printf ("INSERT SQL error: %s\n", sqlite3_errmsg (handle));
	  goto abort;
      }

    pk = 0;
    for (ix = 0; ix < 1000; ix++)
      {
	  x = 1000000.0 + (ix * 10.0);
	  for (iy = 0; iy < 1000; iy++)
	    {
/* this double loop will insert 1 million rows into the the test table */

		y = 4000000.0 + (iy * 10.0);
		pk++;
		if ((pk % 25000) == 0)
		  {
		      t1 = clock ();
		      printf ("insert row: %d\t\t[elapsed time: %1.3f]\n",
			      pk, (double) (t1 - t0) / CLOCKS_PER_SEC);
		  }

/* preparing the geometry to insert */
		geo = gaiaAllocGeomColl ();
		geo->Srid = 3003;
		gaiaAddPointToGeomColl (geo, x, y);

/* transforming this geometry into the SpatiaLite BLOB format */
		gaiaToSpatiaLiteBlobWkb (geo, &blob, &blob_size);

/* we can now destroy the geometry object */
		gaiaFreeGeomColl (geo);

/* resetting Prepared Statement and bindings */
		sqlite3_reset (stmt);
		sqlite3_clear_bindings (stmt);

/* binding parameters to Prepared Statement */
		sqlite3_bind_int64 (stmt, 1, pk);
		sqlite3_bind_blob (stmt, 2, blob, blob_size, free);

/* performing actual row insert */
		ret = sqlite3_step (stmt);
		if (ret == SQLITE_DONE || ret == SQLITE_ROW)
		    ;
		else
		  {
/* an unexpected error occurred */
		      printf ("sqlite3_step() error: %s\n",
			      sqlite3_errmsg (handle));
		      sqlite3_finalize (stmt);
		      goto abort;
		  }

	    }
      }
/* we have now to finalize the query [memory cleanup] */
    sqlite3_finalize (stmt);

/*
committing the transaction

*** this step is absolutely critical ***

if we don't confirm the still pending transaction,
any update will be lost
*/
    strcpy (sql, "COMMIT");
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
/* an error occurred */
	  printf ("COMMIT error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  goto abort;
      }

/*
now we'll optimize the table
*/
    strcpy (sql, "ANALYZE test");
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
/* an error occurred */
	  printf ("ANALYZE error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  goto abort;
      }

    for (ix = 0; ix < 3; ix++)
      {
	  printf ("\nperforming test#%d - not using Spatial Index\n", ix);
/*
now we'll perform the spatial query WITHOUT using the Spatial Index
we'll loop 3 times in order to avoid buffering-caching side effects
*/
	  strcpy (sql, "SELECT Count(*) FROM test ");
	  strcat (sql, "WHERE MbrWithin(geom, BuildMbr(");
	  strcat (sql, "1000400.5, 4000400.5, ");
	  strcat (sql, "1000450.5, 4000450.5))");
	  t0 = clock ();
	  ret = sqlite3_get_table (handle, sql, &results, &n_rows, &n_columns,
				   &err_msg);
	  if (ret != SQLITE_OK)
	    {
/* an error occurred */
		printf ("NoSpatialIndex SQL error: %s\n", err_msg);
		sqlite3_free (err_msg);
		goto abort;
	    }
	  count = "";
	  for (i = 1; i <= n_rows; i++)
	    {
		count = results[(i * n_columns) + 0];
	    }
	  t1 = clock ();
	  printf ("Count(*) = %d\t\t[elapsed time: %1.4f]\n", atoi (count),
		  (double) (t1 - t0) / CLOCKS_PER_SEC);
/* we can now free the table results */
	  sqlite3_free_table (results);
      }

    for (ix = 0; ix < 3; ix++)
      {
	  printf ("\nperforming test#%d - using the R*Tree Spatial Index\n",
		  ix);
/*
now we'll perform the spatial query USING the R*Tree Spatial Index
we'll loop 3 times in order to avoid buffering-caching side effects
*/
	  strcpy (sql, "SELECT Count(*) FROM test ");
	  strcat (sql, "WHERE MbrWithin(geom, BuildMbr(");
	  strcat (sql, "1000400.5, 4000400.5, ");
	  strcat (sql, "1000450.5, 4000450.5)) AND ROWID IN (");
	  strcat (sql, "SELECT pkid FROM idx_test_geom WHERE ");
	  strcat (sql, "xmin > 1000400.5 AND ");
	  strcat (sql, "xmax < 1000450.5 AND ");
	  strcat (sql, "ymin > 4000400.5 AND ");
	  strcat (sql, "ymax < 4000450.5)");
/*
YES, this query is a very unhappy one
the idea is simply to simulate exactly the same conditions as above
*/
	  t0 = clock ();
	  ret = sqlite3_get_table (handle, sql, &results, &n_rows, &n_columns,
				   &err_msg);
	  if (ret != SQLITE_OK)
	    {
/* an error occurred */
		printf ("SpatialIndex SQL error: %s\n", err_msg);
		sqlite3_free (err_msg);
		goto abort;
	    }
	  count = "";
	  for (i = 1; i <= n_rows; i++)
	    {
		count = results[(i * n_columns) + 0];
	    }
	  t1 = clock ();
	  printf ("Count(*) = %d\t\t[elapsed time: %1.4f]\n", atoi (count),
		  (double) (t1 - t0) / CLOCKS_PER_SEC);
/* we can now free the table results */
	  sqlite3_free_table (results);
      }

/* disconnecting the test DB */
    ret = sqlite3_close (handle);
    if (ret != SQLITE_OK)
      {
	  printf ("close() error: %s\n", sqlite3_errmsg (handle));
	  return -1;
      }
    printf ("\n\nsample successfully terminated\n");
    return 0;

  abort:
    sqlite3_close (handle);
    spatialite_cleanup();
    return -1;
}


text:
import os
import sys
import unittest
from os.path import join, pardir, abspath, dirname

os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.conf'
sys.path.insert(0, abspath(join(dirname(__file__), pardir)))

class AssertQueriesCountMixin(object):
    def assert_queries_count(self, num, func=None, *args, **kwargs):
        from django.test.testcases import _AssertNumQueriesContext
        from django.db import connections, DEFAULT_DB_ALIAS

        using = kwargs.pop("using", DEFAULT_DB_ALIAS)
        conn = connections[using]

        context = _AssertNumQueriesContext(self, num, conn)
        if func is None:
            return None

        with context:
            return func(*args, **kwargs)

class TestCase(unittest.TestCase):
    assert_equal = unittest.TestCase.assertEqual
    assert_not_equal = unittest.TestCase.assertNotEqual
    assert_true = unittest.TestCase.assertTrue
    assert_false = unittest.TestCase.assertFalse
    assert_raises = unittest.TestCase.assertRaises

    def assert_items_equal(self, first, second):
        self.assert_equal(set(first), set(second))

class DBTestCase(TestCase, AssertQueriesCountMixin):
    test_runner, old_config = None, None

    def setUp(self):
        from django.test.simple import DjangoTestSuiteRunner
        self.test_runner = DjangoTestSuiteRunner()
        self.before_environment_setup()                       # HOOK
        self.test_runner.setup_test_environment()
        self.before_database_setup()                          # HOOK
        self.old_config = self.test_runner.setup_databases()
        self.setup()

    def tearDown(self):
        self.test_runner.teardown_databases(self.old_config)
        self.test_runner.teardown_test_environment()
        self.teardown()  # just to make it look like pep8

    def before_environment_setup(self):
        pass

    def before_database_setup(self):
        pass

    def setup(self):
        pass

    def teardown(self):
        pass
# ##############################################################


text:
import BunqErrorHandler from "../Functions/BunqErrorHandler";
import MasterCardAction from "../Models/MasterCardAction";

import { masterCardActionsSetInfo } from "./master_card_actions";

export function masterCardActionSetInfo(master_card_action_info, account_id, master_card_action_id) {
    return {
        type: "MASTER_CARD_ACTION_INFO_SET_INFO",
        payload: {
            master_card_action_info: master_card_action_info,
            master_card_action_id: master_card_action_id,
            account_id: account_id
        }
    };
}

export function masterCardActionInfoUpdate(BunqJSClient, user_id, account_id, master_card_action_id) {
    const failedMessage = window.t("We failed to load the mastercard payment information");

    return dispatch => {
        dispatch(masterCardActionInfoLoading());
        BunqJSClient.api.masterCardAction
            .get(user_id, account_id, master_card_action_id)
            .then(masterCardAction => {
                const masterCardActionInfo = new MasterCardAction(masterCardAction);

                // update this item in the list and the stored data
                dispatch(masterCardActionsSetInfo([masterCardActionInfo], parseInt(account_id), false, BunqJSClient));

                dispatch(masterCardActionSetInfo(masterCardActionInfo, parseInt(account_id), master_card_action_id));
                dispatch(masterCardActionInfoNotLoading());
            })
            .catch(error => {
                dispatch(masterCardActionInfoNotLoading());
                BunqErrorHandler(dispatch, error, failedMessage);
            });
    };
}

export function masterCardActionInfoLoading() {
    return { type: "MASTER_CARD_ACTION_INFO_IS_LOADING" };
}

export function masterCardActionInfoNotLoading() {
    return { type: "MASTER_CARD_ACTION_INFO_IS_NOT_LOADING" };
}

export function masterCardActionInfoClear() {
    return { type: "MASTER_CARD_ACTION_INFO_CLEAR" };
}


text:
package org.esbench.generator.field;

import static org.testng.Assert.assertNull;

import org.apache.commons.lang3.RandomUtils;
import org.testng.annotations.Test;

public class NullFieldFactoryTest {

	@Test(invocationCount = 10)
	public void newInstance() {
		NullFieldFactory factory = new NullFieldFactory();
		assertNull(factory.newInstance(RandomUtils.nextInt(0, Integer.MAX_VALUE)));
	}
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**_id** | **NSNumber*** |  | [optional]
**token** | **NSString*** |  | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Cake.Core.Configuration.Parser;

namespace Cake.Core.Configuration
{
    internal sealed class ConfigurationTokenStream : IReadOnlyList<ConfigurationToken>
    {
        private readonly List<ConfigurationToken> _tokens;
        private int _position;

        public ConfigurationToken Current
        {
            get
            {
                return _position >= Count ? null : _tokens[_position];
            }
        }

        public ConfigurationToken this[int index]
        {
            get { return _tokens[index]; }
        }

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

        public ConfigurationTokenStream(IEnumerable<ConfigurationToken> tokens)
        {
            _tokens = new List<ConfigurationToken>(tokens ?? Enumerable.Empty<ConfigurationToken>());
        }

        public ConfigurationToken Peek()
        {
            return _position >= Count ? null : _tokens[_position];
        }

        public ConfigurationToken Expect(ConfigurationTokenKind tokenType, string message)
        {
            if (Current == null || Current.Kind != tokenType)
            {
                throw new InvalidOperationException(message);
            }
            return Current;
        }

        public ConfigurationToken Consume()
        {
            if (_position >= Count)
            {
                return null;
            }
            var token = _tokens[_position];
            _position++;
            return token;
        }

        public IEnumerator<ConfigurationToken> GetEnumerator()
        {
            return _tokens.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CasDataConsumer (Apache UIMA Java SDK 2.8.1 User-Level API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.uima.collection.base_cpm

Interface CasDataConsumer

All Superinterfaces:

CasDataProcessor, CasProcessor, ConfigurableResource, Resource

All Known Implementing Classes:

CasDataConsumer_ImplBase

public interface CasDataConsumer
extends ConfigurableResource, CasDataProcessor

Any component that operates on analysis results produced by a UIMA CasDataProcessor.
 CASDataConsumers may be registered with a
 CollectionProcessingManager (CPM). During collection
 processing, the CPM will pass each CasData from CasProcessor to each consumer's process method.
 The CAS consumer can do anything it wants with the CASes it receives; commonly CAS consumers will
 build aggregate data structures such as search engine indexes or glossaries.

 The CPM will also call each CAS Consumer's batchProcessComplete(ProcessTrace) method at
 the end of each batch and their collectionProcessComplete(ProcessTrace) method called at
 the end of the collection.

 CasConsumers are also ConfigurableResources, and can be instantiated
 from descriptors. See
 XMLParser.parseCasConsumerDescription(XMLInputSource) and
 UIMAFramework.produceCasConsumer(ResourceSpecifier,Map) for more
 information.

Field Summary

Fields inherited from interface org.apache.uima.resource.Resource

PARAM_AGGREGATE_SOFA_MAPPINGS, PARAM_CONFIG_MANAGER, PARAM_CONFIG_PARAM_SETTINGS, PARAM_EXTERNAL_OVERRIDE_SETTINGS, PARAM_PERFORMANCE_TUNING_SETTINGS, PARAM_RESOURCE_MANAGER, PARAM_UIMA_CONTEXT

Method Summary

Methods

Modifier and Type
Method and Description

void
batchProcessComplete(ProcessTrace aTrace)

Completes the processing of a batch.

void
collectionProcessComplete(ProcessTrace aTrace)

Completes the processing of an entire collection.

Methods inherited from interface org.apache.uima.resource.ConfigurableResource

getConfigParameterValue, getConfigParameterValue, reconfigure, setConfigParameterValue, setConfigParameterValue

Methods inherited from interface org.apache.uima.resource.Resource

destroy, getLogger, getMetaData, getResourceManager, getUimaContext, getUimaContextAdmin, initialize, setLogger

Methods inherited from interface org.apache.uima.collection.base_cpm.CasDataProcessor

process, process

Methods inherited from interface org.apache.uima.collection.base_cpm.CasProcessor

getProcessingResourceMetaData, isReadOnly, isStateless

Method Detail

batchProcessComplete

void batchProcessComplete(ProcessTrace aTrace)
                          throws ResourceProcessException,
                                 IOException

Completes the processing of a batch. A collection may be divided into one or more batches - it
 is up to the CollectionProcessingManager or the application to determine the number and size of
 batches.

Specified by:

batchProcessComplete in interface CasProcessor

Parameters:

aTrace - an object that records information, such as timing, about this method's execution.

Throws:

ResourceProcessException - if an exception occurs during processing

IOException - if an I/O failure occurs

collectionProcessComplete

void collectionProcessComplete(ProcessTrace aTrace)
                               throws ResourceProcessException,
                                      IOException

Completes the processing of an entire collection.

Specified by:

collectionProcessComplete in interface CasProcessor

Parameters:

aTrace - an object that records information, such as timing, about this method's execution.

Throws:

ResourceProcessException - if an exception occurs during processing

IOException - if an I/O failure occurs

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2006–2015 The Apache Software Foundation. All rights reserved.


text:
package com.google.android.exoplayer.chunk.parser;

import com.google.android.exoplayer.C;
import com.google.android.exoplayer.MediaFormat;
import com.google.android.exoplayer.ParserException;
import com.google.android.exoplayer.SampleHolder;
import com.google.android.exoplayer.upstream.NonBlockingInputStream;

import java.util.Map;
import java.util.UUID;

/**
 * Facilitates extraction of media samples from a container format.
 */
public interface Extractor {

  /**
   * An attempt to read from the input stream returned insufficient data.
   */
  public static final int RESULT_NEED_MORE_DATA = 1;
  /**
   * The end of the input stream was reached.
   */
  public static final int RESULT_END_OF_STREAM = 2;
  /**
   * A media sample was read.
   */
  public static final int RESULT_READ_SAMPLE = 4;
  /**
   * Initialization data was read. The parsed data can be read using {@link #getFormat()} and
   * {@link #getPsshInfo}.
   */
  public static final int RESULT_READ_INIT = 8;
  /**
   * A sidx atom was read. The parsed data can be read using {@link #getIndex()}.
   */
  public static final int RESULT_READ_INDEX = 16;
  /**
   * The next thing to be read is a sample, but a {@link SampleHolder} was not supplied.
   */
  public static final int RESULT_NEED_SAMPLE_HOLDER = 32;

  /**
   * Returns the segment index parsed from the stream.
   *
   * @return The segment index, or null if a SIDX atom has yet to be parsed.
   */
  public SegmentIndex getIndex();

  /**
   * Returns true if the offsets in the index returned by {@link #getIndex()} are relative to the
   * first byte following the initialization data, or false if they are absolute (i.e. relative to
   * the first byte of the stream).
   *
   * @return True if the offsets are relative to the first byte following the initialization data.
   *     False otherwise.
   */
  public boolean hasRelativeIndexOffsets();

  /**
   * Returns the format of the samples contained within the media stream.
   *
   * @return The sample media format, or null if the format has yet to be parsed.
   */
  public MediaFormat getFormat();

  /**
   * Returns the duration of the stream in microseconds, or {@link C#UNKNOWN_TIME_US} if unknown.
   */
  public long getDurationUs();

  /**
   * Returns the pssh information parsed from the stream.
   *
   * @return The pssh information. May be null if pssh data has yet to be parsed, or if the stream
   *     does not contain any pssh data.
   */
  public Map<UUID, byte[]> getPsshInfo();

  /**
   * Consumes data from a {@link NonBlockingInputStream}.
   * <p>
   * The read terminates if the end of the input stream is reached, if an attempt to read from the
   * input stream returned 0 bytes of data, or if a sample is read. The returned flags indicate
   * both the reason for termination and data that was parsed during the read.
   *
   * @param inputStream The input stream from which data should be read.
   * @param out A {@link SampleHolder} into which the next sample should be read. If null then
   *     {@link #RESULT_NEED_SAMPLE_HOLDER} will be returned once a sample has been reached.
   * @return One or more of the {@code RESULT_*} flags defined in this class.
   * @throws ParserException If an error occurs parsing the media data.
   */
  public int read(NonBlockingInputStream inputStream, SampleHolder out) throws ParserException;

  /**
   * Seeks to a position before or equal to the requested time.
   *
   * @param seekTimeUs The desired seek time in microseconds.
   * @param allowNoop Allow the seek operation to do nothing if the seek time is in the current
   *     fragment run, is equal to or greater than the time of the current sample, and if there
   *     does not exist a sync frame between these two times.
   * @return True if the operation resulted in a change of state. False if it was a no-op.
   */
  public boolean seekTo(long seekTimeUs, boolean allowNoop);

}


text:
module.exports = {
  'secret': process.env.BADGEE_SECRET
};


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

namespace WebDav
{
    public class SearchParameters
    {
        public SearchParameters()
        {
            Scope = "/";
            Namespaces = new List<NamespaceAttr>();
            SelectProperties = new List<XName>();
            Headers = new List<KeyValuePair<string, string>>();
            CancellationToken = CancellationToken.None;
        }

        /// <summary>
        /// Gets or sets a directory to search in.
        /// </summary>
        public string Scope { get; set; }

        /// <summary>
        /// Gets or sets the search property in the DAV:like element.
        /// </summary>
        public XName SearchProperty { get; set; }

        /// <summary>
        /// Gets or sets the search keyword to be used in the DAV:like element.
        /// Example: 'test%' (without quotes), results in 'LIKE test%' search.
        /// </summary>
        public string SearchKeyword { get; set; }

        /// <summary>
        /// Gets or sets the collection of xml namespaces of properties.
        /// </summary>
        public IReadOnlyCollection<NamespaceAttr> Namespaces { get; set; }

        /// <summary>
        /// Gets or sets the Select properties.
        /// </summary>
        public IReadOnlyCollection<XName> SelectProperties { get; set; }

        /// <summary>
        /// Gets or sets the collection of the headers.
        /// </summary>
        public IReadOnlyCollection<KeyValuePair<string, string>> Headers { get; set; }

        /// <summary>
        /// Gets or sets the cancellation token.
        /// </summary>
        public CancellationToken CancellationToken { get; set; }

        public void AssertParametersAreValid()
        {
            if (string.IsNullOrEmpty(Scope))
                throw new ArgumentException("Scope is required.", nameof(Scope));

            if (SearchProperty == null)
                throw new ArgumentException("Search property is required.", nameof(SearchProperty));

            if (string.IsNullOrEmpty(SearchKeyword))
                throw new ArgumentException("Search keyword is required.", nameof(SearchKeyword));
        }
    }
}


text:
require 'spec_helper'

describe Admin::SiteContentsController do

  it "is a subclass of AdminController" do
    (Admin::SiteContentsController < Admin::AdminController).should be_true
  end

  context 'while logged in as an admin' do
    before do
      @user = log_in(:admin)
    end

    context '.show' do
      let(:content_type) { SiteContent.content_types.first.content_type }

      it 'returns success' do
        xhr :get, :show, id: content_type
        response.should be_success
      end

      it 'returns JSON' do
        xhr :get, :show, id: content_type
        ::JSON.parse(response.body).should be_present
      end
    end
  end

end


text:
/**
 * This file is part of the mingw-w64 runtime package.
 * No warranty is given; refer to the file DISCLAIMER within this package.
 */
#ifndef _NAMEDPIPE_H_
#define _NAMEDPIPE_H_

#include <apiset.h>
#include <apisetcconv.h>
#include <minwindef.h>
#include <minwinbase.h>

#ifdef __cplusplus
extern "C" {
#endif

#if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_DESKTOP)
  WINADVAPI WINBOOL WINAPI ImpersonateNamedPipeClient (HANDLE hNamedPipe);
  WINBASEAPI WINBOOL WINAPI CreatePipe (PHANDLE hReadPipe, PHANDLE hWritePipe, LPSECURITY_ATTRIBUTES lpPipeAttributes, DWORD nSize);
  WINBASEAPI WINBOOL WINAPI ConnectNamedPipe (HANDLE hNamedPipe, LPOVERLAPPED lpOverlapped);
  WINBASEAPI WINBOOL WINAPI DisconnectNamedPipe (HANDLE hNamedPipe);
  WINBASEAPI WINBOOL WINAPI SetNamedPipeHandleState (HANDLE hNamedPipe, LPDWORD lpMode, LPDWORD lpMaxCollectionCount, LPDWORD lpCollectDataTimeout);
  WINBASEAPI WINBOOL WINAPI PeekNamedPipe (HANDLE hNamedPipe, LPVOID lpBuffer, DWORD nBufferSize, LPDWORD lpBytesRead, LPDWORD lpTotalBytesAvail, LPDWORD lpBytesLeftThisMessage);
  WINBASEAPI WINBOOL WINAPI TransactNamedPipe (HANDLE hNamedPipe, LPVOID lpInBuffer, DWORD nInBufferSize, LPVOID lpOutBuffer, DWORD nOutBufferSize, LPDWORD lpBytesRead, LPOVERLAPPED lpOverlapped);
  WINBASEAPI HANDLE WINAPI CreateNamedPipeW (LPCWSTR lpName, DWORD dwOpenMode, DWORD dwPipeMode, DWORD nMaxInstances, DWORD nOutBufferSize, DWORD nInBufferSize, DWORD nDefaultTimeOut, LPSECURITY_ATTRIBUTES lpSecurityAttributes);
  WINBASEAPI WINBOOL WINAPI WaitNamedPipeW (LPCWSTR lpNamedPipeName, DWORD nTimeOut);
#if _WIN32_WINNT >= 0x0600
  WINBASEAPI WINBOOL WINAPI GetNamedPipeClientComputerNameW (HANDLE Pipe, LPWSTR ClientComputerName, ULONG ClientComputerNameLength);
#endif

#ifdef UNICODE
#define CreateNamedPipe CreateNamedPipeW
#define WaitNamedPipe WaitNamedPipeW
#define GetNamedPipeClientComputerName GetNamedPipeClientComputerNameW
#endif
#endif

#ifdef __cplusplus
}
#endif
#endif


text:
package org.apache.toree.utils

import org.scalatest.{BeforeAndAfter, Matchers, FunSpec}
import joptsimple.{OptionSet, OptionSpec, OptionParser}
import org.scalatestplus.mockito.MockitoSugar

import org.mockito.Mockito._
import org.mockito.Matchers._

import collection.JavaConverters._

class ArgumentParsingSupportSpec extends FunSpec with Matchers
  with BeforeAndAfter with MockitoSugar
{
  private var mockOptions: OptionSet = _
  private var mockParser: OptionParser = _
  private var argumentParsingInstance: ArgumentParsingSupport = _

  before {
    mockOptions = mock[OptionSet]
    mockParser = mock[OptionParser]
    doReturn(mockOptions).when(mockParser).parse(anyVararg[String]())

    argumentParsingInstance = new Object() with ArgumentParsingSupport {
      override protected lazy val parser: OptionParser = mockParser
    }
  }

  describe("ArgumentParsingSupport") {
    describe("#parseArgs") {
      it("should invoke the underlying parser's parse method") {
        doReturn(Nil.asJava).when(mockOptions).nonOptionArguments()
        argumentParsingInstance.parseArgs("")

        verify(mockParser).parse(anyString())
      }

      it("should return an empty list if there are no non-option arguments") {
        val expected = Nil
        doReturn(expected.asJava).when(mockOptions).nonOptionArguments()
        val actual = argumentParsingInstance.parseArgs((
          "--transitive" :: expected
        ).mkString(" "))

        actual should be (expected)
      }

      it("should return a list containing non-option arguments") {
        val expected = "non-option" :: Nil
        doReturn(expected.asJava).when(mockOptions).nonOptionArguments()
        val actual = argumentParsingInstance.parseArgs((
          "--transitive" :: expected
          ).mkString(" "))

        actual should be (expected)
      }
    }
  }
}


text:
Jaysus::Local.store_dir = File.expand_path(File.dirname(__FILE__) + '/../store/')

Jaysus::Remote.base_url = 'http://testapi'


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="PhpIncludePathManager">
    <include_path>
      <path value="$PROJECT_DIR$/vendor/psr/log" />
      <path value="$PROJECT_DIR$/vendor/symfony/polyfill-mbstring" />
      <path value="$PROJECT_DIR$/vendor/symfony/debug" />
      <path value="$PROJECT_DIR$/vendor/symfony/console" />
      <path value="$PROJECT_DIR$/vendor/guzzlehttp/promises" />
      <path value="$PROJECT_DIR$/vendor/composer" />
      <path value="$PROJECT_DIR$/vendor/guzzlehttp/psr7" />
      <path value="$PROJECT_DIR$/vendor/guzzlehttp/guzzle" />
      <path value="$PROJECT_DIR$/vendor/psr/http-message" />
      <path value="$PROJECT_DIR$/vendor/symfony/var-dumper" />
      <path value="$PROJECT_DIR$/vendor/psr/container" />
      <path value="$PROJECT_DIR$/vendor/league/json-guard" />
      <path value="$PROJECT_DIR$/vendor/sabre/uri" />
      <path value="$PROJECT_DIR$/vendor/league/json-reference" />
      <path value="$PROJECT_DIR$/vendor/psr/simple-cache" />
    </include_path>
  </component>
  <component name="PhpProjectSharedConfiguration" php_language_level="7" />
</project>


text:
<?php

namespace Wtk\Settings;

class ArrayUtils
{
    /**
     * Expands flat array to multi-dimensional associative array
     * using keys names as paths.
     *
     * @param  array      $flatten
     *
     * @return array
     */
    public static function expand(array $flatten)
    {
        $nested = array();

        foreach ($flatten as $path => $value) {
            ArrayUtils::set($nested, $path, $value);
        }

        return $nested;
    }

    /**
     * Flatten a multi-dimensional associative array with dots.
     *
     * @param  array   $array
     * @param  string  $prepend
     * @return array
     */
    public static function dot(array $array, $prepend = '')
    {
        $results = array();

        foreach ($array as $key => $value)
        {
            if (is_array($value))
            {
                $results = array_merge(
                    $results,
                    self::dot($value, $prepend.$key.'.')
                );
            }
            else
            {
                $results[$prepend.$key] = $value;
            }
        }

        return $results;
    }

    /**
     * Returns array key.
     * Supports dot notation.
     *
     * @param  array      $array
     * @param  string     $key
     * @param  mixed      $default
     *
     * @return mixed
     */
    public static function get(array $array, $key, $default = null)
    {
        if (is_null($key)) return $array;

        if (isset($array[$key])) return $array[$key];

        foreach (explode('.', $key) as $segment)
        {
            if ( ! is_array($array) or ! array_key_exists($segment, $array))
            {
                return $default;
            }

            $array = $array[$segment];
        }

        return $array;
    }

    /**
     * Set an array item to a given value using "dot" notation.
     *
     * If no key is given to the method, the entire array will be replaced.
     *
     * @param  array   $array
     * @param  string  $key
     * @param  mixed   $value
     * @return array
     */
    public static function set(&$array, $key, $value)
    {
        if (is_null($key)) return $array = $value;

        $keys = explode('.', $key);

        while (count($keys) > 1)
        {
            $key = array_shift($keys);

            // If the key doesn't exist at this depth, we will just create an empty array
            // to hold the next value, allowing us to create the arrays to hold final
            // values at the correct depth. Then we'll keep digging into the array.
            if ( ! isset($array[$key]) or ! is_array($array[$key]))
            {
                $array[$key] = array();
            }

            $array =& $array[$key];
        }

        $array[array_shift($keys)] = $value;

        return $array;
    }
}


text:
<?
class Shineisp_Api_Customers extends Shineisp_Api_Abstract_Action  {

    public function insert( $params ) {
        $this->authenticate();

        $form = new Api_Form_CustomerForm ( array ('action' => '#', 'method' => 'post' ) );
        #Add email validator
        $mailValidator = new Shineisp_Validate_Email();
        $form->getElement('email')->addValidator($mailValidator);

        $form->addElement('password', 'password', array(
            'filters'    => array('StringTrim'),
            'required'   => true,
            'decorators' => array('Composite'),
            'validators' => array(
                array('regex', false, '/^[a-zA-Z0-9\-\_\.\%\!\$]{6,20}$/')
            ),
            'description'      => 'Write here your password. (min.6 chars - max.20 chars)',
            'label'      => 'Password',
            'class'      => 'text-input large-input'
        ));

        if( array_key_exists('countrycode', $params) ) {
            $country_id     = Countries::getIDbyCode($params['countrycode']);
            if( $country_id == null ) {
                throw new Shineisp_Api_Exceptions( 400005, ":: 'countrycode' not valid" );
                exit();
            }

            unset($params['coutrycode']);
            $params['country_id']   = $country_id;
        }

        if( array_key_exists('provincecode',$params) && $params['provincecode'] != "" ) {
            $params['area'] = $params['provincecode'];
            unset($params['provincecode']);
        }

        if ($form->isValid ( $params ) ) {
            if( $params['status'] == false ) {
                $params['status'] = 'disabled';
            }

            $idcustomers    = Customers::Create($params);

            $customer       = Customers::find($idcustomers);
            return $customer['uuid'];
        } else {
            $errors     = $form->getMessages();
            $message    = "";
            foreach( $errors as  $field => $errorsField ) {
                $message .= "Field '{$field}'
";
                foreach( $errorsField as $error => $describe ) {
                    $message .=" => {$error} ({$describe})";
                }
            }

            throw new Shineisp_Api_Exceptions( 400004, ":\n{$message}" );
            exit();
        }
    }

    public function get( $uuid ) {
        $this->authenticate();

        $customer   = Customers::findWithUuid($uuid);
        if( empty($customer) ) {
            return false;
        }
        $customerid = $customer['customer_id'];
        $fields = ' c.company as company, c.firstname as firstname, c.lastname as lastname,c.sex,c.email, c.taxpayernumber, c.vat, l.legalform_id as legalformid,c.birthdate as birthdate,
                    c.sex as sex, a.address_id, a.address as address, a.city as city,a.code as code,a.country_id as countryid ,a.region_id as regionid,a.area as area, ct.code as countrycode
                    ,cn.*,cnts.*';
        $customerid = $customer['customer_id'];
        $customer   = Customers::getAllInfo( $customerid, $fields );
        unset($customer['password']);
        return $customer;

    }

    public function update( $uuid, $params ) {
        $this->authenticate();

        $form = new Api_Form_CustomerForm ( array ('action' => '#', 'method' => 'post' ) );

        if( array_key_exists('countrycode', $params) ) {
            $country_id     = Countries::getIDbyCode($params['countrycode']);
            if( $country_id == null ) {
                throw new Shineisp_Api_Exceptions( 400005, ":: 'countrycode' not valid" );
                exit();
            }

            unset($params['coutrycode']);
            $params['country_id']   = $country_id;
        }

        if( array_key_exists('provincecode',$params) && $params['provincecode'] != "" ) {
            $params['area'] = $params['provincecode'];
            unset($params['provincecode']);
        }

        if ($form->isValid ( $params ) ) {
            if( $params['status'] == false ) {
                $params['status'] = 'disabled';
            }
            $customer   = Customers::findWithUuid($uuid);
            if( empty($customer) ) {
                return false;
            }
            $customerid = $customer['customer_id'];

            // $data       = explode('/', $params['birthdate']);
            // list( $gg, $mm, $yyyy )  = $data;
            // $params['birthdate']    = $yyyy.'-'.$mm.'-'.$gg;

            foreach( $customer as $name => &$value ) {
                if( array_key_exists($name, $params) ) {
                    $value  = $params[$name];
                }
            }

            $fields = $params;
            unset( $fields['address'] );
            unset( $fields['contact'] );

            Customers::saveAll( $customerid, $fields );

            $address    = array();
            $address['address']      = $params['address'];
            $address['city']        = $params['city'];
            $address['code']        = $params['code'];
            $address['area']        = $params['area'];
            $address['region_id']   = $params['regionid'];
            $address['country_id']  = $params['country_id'];
            $address['customer_id'] = $customerid;
            if( $params['addressid'] != 0 ) {
                Addresses::AddNew($address, $params['addressid']);
            } else {
                Addresses::AddNew($address);
            }

            if( array_key_exists('contacts', $params) && !empty( $params['contacts']) ) {
                foreach( $params['contacts'] as $contact ) {
                    if( $contact['contact'] == "" ) {
                        continue;
                    }
                    $c  = array();
                    $c['contact']       = $contact['contact'];
                    $c['type_id']       = $contact['contacttypes'];
                    $c['customer_id']   = $customerid;

                    if( intval($contact['idcontact']) != 0 ){
                        Contacts::AddNew($c, intval($contact['idcontact']));
                    } else {
                        Contacts::AddNew($c);
                    }
                }
            }

            return true;
        } else {
            $errors     = $form->getMessages();
            $message    = "";
            foreach( $errors as  $field => $errorsField ) {
                $message .= "Field '{$field}'
";
                foreach( $errorsField as $error => $describe ) {
                    $message .=" => {$error} ({$describe})";
                }
            }

            throw new Shineisp_Api_Exceptions( 400004, ":\n{$message}" );
            exit();
        }

    }

}


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

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:name=".ui.SmartPantry"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".ui.activities.MainActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/app_name"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ui.activities.ManageLocationsActivity"
            android:label="@string/activity_label_manage_locations"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name=".ui.activities.ManageLocationsActivity" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ui.activities.AboutActivity"
            android:label="@string/activity_label_about"
            android:screenOrientation="portrait" />
        <activity
            android:name=".ui.activities.SettingsActivity"
            android:label="@string/activity_label_settings"
            android:screenOrientation="portrait" />
        <activity
            android:name=".ui.activities.InsertItemActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/activity_label_insert_item"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme_SlidableTransparent" />
        <activity
            android:name=".ui.activities.EditItemActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/activity_label_edit_item"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme_SlidableTransparent"
            android:windowSoftInputMode="stateHidden" />

        <provider
            android:name=".content.MyContentProvider"
            android:authorities="com.macadamian.smartpantry.content.MyContentProvider"
            android:enabled="true"
            android:exported="false" />

        <receiver android:name=".ui.receivers.AlarmReceiver" />
        <receiver android:name=".ui.receivers.BootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <!-- Google play services -->
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name=".ui.activities.Shop"
            android:configChanges="orientation|screenSize"
            android:screenOrientation="portrait"
            android:label="@string/title_activity_shop"></activity>
    </application>

</manifest>


text:
'use strict';

//dependencies
const _ = require('lodash');
const mongoose = require('mongoose');
const Service = mongoose.model('Service');

/**
 * Service Controller
 *
 * @description :: Server-side logic for managing Service.
 */
module.exports = {
  /**
   * @function
   * @name services.index()
   * @description display a list of all services
   * @param  {HttpRequest} request  a http request
   * @param  {HttpResponse} response a http response
   */
  index: function (request, response, next) {
    Service
      .list(request, function (error, results) {
        if (error) {
          next(error);
        } else {
          //map to legacy api
          results.services =
            _.map(results.services, function (service) {
              return Service.mapToLegacy(service);
            });
          response.ok(results);
        }
      });
  },

  /**
   * @function
   * @name services.create()
   * @description create a new service
   * @param  {HttpRequest} request  a http request
   * @param  {HttpResponse} response a http response
   */
  create: function (request, response, next) {
    //support legacy
    let body = request.body;
    body = _.merge({}, body, {
      name: { en: body.name },
      description: { en: body.description || body.name },
      flags: { external: body.isExternal }
    });

    Service
      .create(body, function (error, service) {
        if (error) {
          next(error);
        } else {
          const _service = Service.mapToLegacy(service);
          response.created(_service);
        }
      });
  },

  /**
   * @function
   * @name services.show()
   * @description display a specific service
   * @param  {HttpRequest} request  a http request
   * @param  {HttpResponse} response a http response
   */
  show: function (request, response, next) {
    Service
      .show(request, function (error, service) {
        if (error) {
          next(error);
        } else {
          const _service = Service.mapToLegacy(service);
          response.ok(_service);
        }
      });
  },

  /**
   * @function
   * @name services.update()
   * @description update a specific service
   * @param  {HttpRequest} request  a http request
   * @param  {HttpResponse} response a http response
   */
  update: function (request, response, next) {
    //support legacy
    let body = request.body;
    body = _.merge({}, body, {
      name: { en: body.name },
      description: { en: body.description || body.name },
      flags: { external: body.isExternal }
    });

    Service
      .findByIdAndUpdate(
        request.params.id,
        body, {
          upsert: true,
          new: true
        },
        function (error, service) {
          if (error) {
            next(error);
          } else {
            const _service = Service.mapToLegacy(service);
            response.ok(_service);
          }
        });
  },

  /**
   * @function
   * @name services.destroy()
   * @description delete a specific service
   * @param  {HttpRequest} request  a http request
   * @param  {HttpResponse} response a http response
   */
  destroy: function (request, response, next) {
    Service
      .findByIdAndRemove(
        request.params.id,
        function (error, service) {
          if (error) {
            next(error);
          } else {
            const _service = Service.mapToLegacy(service);
            response.ok(_service);
          }
        });
  }

};


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

#nullable disable

using System.Linq;
using osu.Game.Rulesets.Objects.Types;

namespace osu.Game.Beatmaps
{
    /// <summary>
    /// Provides functionality to alter a <see cref="IBeatmap"/> after it has been converted.
    /// </summary>
    public class BeatmapProcessor : IBeatmapProcessor
    {
        public IBeatmap Beatmap { get; }

        public BeatmapProcessor(IBeatmap beatmap)
        {
            Beatmap = beatmap;
        }

        public virtual void PreProcess()
        {
            IHasComboInformation lastObj = null;

            bool isFirst = true;

            foreach (var obj in Beatmap.HitObjects.OfType<IHasComboInformation>())
            {
                if (isFirst)
                {
                    obj.NewCombo = true;

                    // first hitobject should always be marked as a new combo for sanity.
                    isFirst = false;
                }

                obj.ComboIndex = lastObj?.ComboIndex ?? 0;
                obj.ComboIndexWithOffsets = lastObj?.ComboIndexWithOffsets ?? 0;
                obj.IndexInCurrentCombo = (lastObj?.IndexInCurrentCombo + 1) ?? 0;

                if (obj.NewCombo)
                {
                    obj.IndexInCurrentCombo = 0;
                    obj.ComboIndex++;
                    obj.ComboIndexWithOffsets += obj.ComboOffset + 1;

                    if (lastObj != null)
                        lastObj.LastInCombo = true;
                }

                lastObj = obj;
            }
        }

        public virtual void PostProcess()
        {
        }
    }
}


text:
package ru.job4j.models;
public class Car {

}


text:
using System;
using NUnit.Framework;

namespace Org.Apache.Etch.Bindings.Csharp.Msg
{

    [TestFixture]
    public class TestField
    {
        [TestFixtureSetUp]
        public void First()
        {
            Console.WriteLine();
            Console.Write( "TestField" );
        }

        [Test]
        public void FieldIntegerString()
        {
            TestMf(1, "one");
            TestMf(2, "two");
            TestMf(3, "three");
        }

        [Test]
        public void FieldString()
        {
            TestMf("one");
            TestMf("two");
            TestMf("three");
        }

        private void TestMf(int id, string name)
        {
            Field mf = new Field(id, name);
            Assert.AreEqual(id, mf.Id);
            Assert.AreEqual(name, mf.Name);
        }

        private void TestMf(string name)
        {
            Field mf = new Field(name);
            Assert.AreEqual(IdName.Hash(name), mf.Id);
            Assert.AreEqual(name, mf.Name);
        }
    }
}


text:
package foo.bar;

public class NotAllowedToCallExit {
  public static void main(String... argv) {
    // This is kosher since non-white-listed classes still have access to
    // the public API of white-listed classes.
    AllowedToCallExit.main(argv);
  }
}


text:
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="edu.cs4730.fragformexample.FormFragment">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="16dp"
        tools:layout_editor_absoluteX="16dp"
        tools:layout_editor_absoluteY="0dp"/>

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="367dp"
        tools:layout_editor_absoluteX="367dp"
        tools:layout_editor_absoluteY="0dp"/>

    <TextView
        android:id="@+id/Label01"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="0dp"
        android:text="TextView item, Hello Form"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="@+id/guideline"
        app:layout_constraintRight_toLeftOf="@+id/guideline2"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1"/>

    <TextView
        android:id="@+id/TVname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:paddingTop="15dp"
        android:text="Enter:"
        app:layout_constraintLeft_toLeftOf="@+id/guideline"
        app:layout_constraintTop_toBottomOf="@+id/Label01"/>

    <EditText
        android:id="@+id/ETname"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@id/TVname"
        android:layout_marginBottom="0dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_toRightOf="@id/TVname"
        android:hint="Name"
        app:layout_constraintBottom_toBottomOf="@+id/TVname"
        app:layout_constraintHorizontal_bias="0.145"
        app:layout_constraintLeft_toRightOf="@+id/TVname"
        app:layout_constraintRight_toLeftOf="@+id/guideline2"
        app:layout_constraintTop_toTopOf="@+id/TVname"
        app:layout_constraintVertical_bias="0.526"/>

    <TextView
        android:id="@+id/TVsound"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="24dp"
        android:text="Radio Button Group"
        app:layout_constraintLeft_toLeftOf="@+id/guideline"
        app:layout_constraintTop_toBottomOf="@+id/TVname"/>

    <RadioGroup
        android:id="@+id/SndGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintLeft_toLeftOf="@+id/guideline"
        app:layout_constraintRight_toRightOf="@+id/TVsound"
        app:layout_constraintTop_toBottomOf="@+id/TVsound">

        <RadioButton
            android:id="@+id/RB01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Information"/>

        <RadioButton
            android:id="@+id/RB02"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Confirmation"/>

        <RadioButton
            android:id="@+id/RB03"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Warning"/>

    </RadioGroup>

    <TextView
        android:id="@+id/TVbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="30dp"
        android:text="Button alert:"
        app:layout_constraintLeft_toLeftOf="@+id/guideline"
        app:layout_constraintTop_toBottomOf="@+id/SndGroup"/>

    <Button
        android:id="@+id/Button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="0dp"
        android:layout_marginLeft="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Toast!"
        app:layout_constraintBottom_toBottomOf="@+id/TVbutton"
        app:layout_constraintLeft_toRightOf="@+id/TVbutton"
        app:layout_constraintTop_toTopOf="@+id/TVbutton"
        app:layout_constraintVertical_bias="0.512"/>

    <TextView
        android:id="@+id/TVpic"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="32dp"
        android:text="Picture:"
        app:layout_constraintHorizontal_bias="0.476"
        app:layout_constraintLeft_toLeftOf="@+id/guideline"
        app:layout_constraintRight_toRightOf="@+id/TVbutton"
        app:layout_constraintTop_toBottomOf="@+id/TVbutton"/>

    <ImageView
        android:id="@+id/ImageView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="0dp"
        android:layout_marginLeft="8dp"
        android:layout_marginStart="35dp"
        android:layout_marginTop="8dp"
        android:src="@drawable/phone"
        app:layout_constraintBottom_toBottomOf="@+id/TVpic"
        app:layout_constraintLeft_toRightOf="@+id/TVpic"
        app:layout_constraintTop_toBottomOf="@+id/Button01"
        app:layout_constraintVertical_bias="0.294"/>

</androidx.constraintlayout.widget.ConstraintLayout>


text:
const GLfloat kTileSize = 32;
const GLint kBoardNumRows = 20;
const GLint kBoardNumCols = 10;
const GLfloat kBoardWidth = kBoardNumCols * kTileSize;
const GLfloat kBoardHeight = kBoardNumRows * kTileSize;
const GLfloat kMargin = 10;
const GLfloat kHudWidth = 160;
const GLfloat kWidth = 3 * kMargin + kBoardWidth + kHudWidth;
const GLfloat kHeight = 2 * kMargin + kBoardHeight;
const GLfloat kHudX = kMargin;
const GLfloat kHudY = kMargin;
const GLfloat kBoardX = 2 * kMargin + kHudWidth;
const GLfloat kBoardY = kMargin;
const GLfloat kHudPieceBoxHeight = 2.5f * kTileSize;
const GLuint kFontSize = 18;

const double kGameTimeStep = 0.005;
const double kFps = 30;
const double kSecondsPerFrame = 1.0 / kFps;

Board board(kBoardNumRows, kBoardNumCols);
Tetris* tetris;

enum GameState {kGameStart, kGameRun, kGamePaused, kGameOver};
GameState gameState = kGameStart;

bool softDrop = false;
bool moveRight = false;
bool moveLeft = false;
int startLevel = 1;

GLFWwindow* setupGlContext() {
    if (!glfwInit())
        return nullptr;

    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    GLFWwindow *window = glfwCreateWindow(kWidth, kHeight, "TETRIS", nullptr, nullptr);

    if (window == nullptr)
        glfwTerminate();

	glfwMakeContextCurrent(window);

#if defined(WIN32)
	glewExperimental = GL_TRUE;
	glewInit();
#endif

    return window;
}

void keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) {
    switch (gameState) {
        case kGameRun:
            if (action == GLFW_PRESS) {
                switch (key) {
                    case GLFW_KEY_Z:
                        tetris->rotate(Rotation::kLeft);
                        break;
                    case GLFW_KEY_X:
                        tetris->rotate(Rotation::kRight);
                        break;
                    case GLFW_KEY_SPACE:
                        tetris->hardDrop();
                        break;
                    case GLFW_KEY_C:
                        tetris->hold();
                        break;
                    case GLFW_KEY_LEFT:
                        moveLeft = true;
                        break;
                    case GLFW_KEY_RIGHT:
                        moveRight = true;
                        break;
                    case GLFW_KEY_DOWN:
                        softDrop = true;
                        break;
                    case GLFW_KEY_ESCAPE:
                        gameState = kGamePaused;
                }
            } else if (action == GLFW_RELEASE) {
                switch (key) {
                    case GLFW_KEY_LEFT:
                        moveLeft = false;
                        break;
                    case GLFW_KEY_RIGHT:
                        moveRight = false;
                        break;
                    case GLFW_KEY_DOWN:
                        softDrop = false;
                }
            }
            break;
        case kGamePaused:
            if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
                gameState = kGameRun;
            else if (key == GLFW_KEY_ENTER && action == GLFW_PRESS)
                gameState = kGameStart;
            break;
        case kGameOver:
            if (key == GLFW_KEY_ENTER && action == GLFW_PRESS)
                gameState = kGameStart;
            break;
        case kGameStart:
            if (key == GLFW_KEY_ENTER && action == GLFW_PRESS) {
                moveRight = false;
                moveLeft = false;
                softDrop = false;
                tetris->restart(startLevel);
                gameState = kGameRun;
            } else if (key == GLFW_KEY_UP && action == GLFW_PRESS) {
                startLevel = std::min(15, startLevel + 1);
            } else if (key == GLFW_KEY_DOWN && action == GLFW_PRESS) {
                startLevel = std::max(1, startLevel - 1);
            }
    }
}

void windowFocusCallback(GLFWwindow* window, int focused) {
    if (!focused && gameState == kGameRun)
        gameState = kGamePaused;
}

int main() {
    GLFWwindow* window = setupGlContext();

	if (window == nullptr)
        return EXIT_FAILURE;

    auto font = loadFont("resources/kenvector_future.ttf", kFontSize);

	std::vector<Texture> tileTextures, ghostTextures;
    std::vector<std::string> colors = {"cyan", "blue", "orange", "yellow", "green", "purple", "red"};
    for (int color = kCyan; color <= kRed; ++color) {
        std::string path = "resources/tile_" + colors[color] + ".png";
        tileTextures.push_back(loadRgbaTexture(path));
        path = "resources/contour_" + colors[color] + ".png";
        ghostTextures.push_back(loadRgbaTexture(path));
    }

    Texture keyArrowLeft = loadRgbaTexture("resources/Keyboard_White_Arrow_Left.png");
    Texture keyArrowRight = loadRgbaTexture("resources/Keyboard_White_Arrow_Right.png");
    Texture keyArrowDown = loadRgbaTexture("resources/Keyboard_White_Arrow_Down.png");
    Texture keyArrowUp = loadRgbaTexture("resources/Keyboard_White_Arrow_Up.png");
    Texture keyZ = loadRgbaTexture("resources/Keyboard_White_Z.png");
    Texture keyX = loadRgbaTexture("resources/Keyboard_White_X.png");
    Texture keyC = loadRgbaTexture("resources/Keyboard_White_C.png");
    Texture keySpace = loadRgbaTexture("resources/Keyboard_White_Space.png");
    Texture keyEsc = loadRgbaTexture("resources/Keyboard_White_Esc.png");
    Texture keyEnter = loadRgbaTexture("resources/Keyboard_White_Enter.png");

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glm::mat4 projection = glm::ortho(0.0f, kWidth, kHeight, 0.0f, -1.0f, 1.0f);

    tetris = new Tetris(board, kGameTimeStep, static_cast<unsigned int>(glfwGetTime() * 1e4));

    glfwSetKeyCallback(window, keyCallback);
    glfwSetWindowFocusCallback(window, windowFocusCallback);

    TextRenderer textRenderer(projection, font);

    GLfloat letterHeight = textRenderer.computeHeight("A");
    GLfloat letterWidth = textRenderer.computeWidth("A");

    SpriteRenderer spriteRenderer(projection);
    PieceRenderer pieceRenderer(kTileSize, tileTextures, spriteRenderer);
    PieceRenderer ghostRenderer(kTileSize, ghostTextures, spriteRenderer);
    BoardRenderer boardRenderer(projection, kTileSize, kBoardX, kBoardY, kBoardNumRows, kBoardNumCols,
                                tileTextures, spriteRenderer, pieceRenderer, ghostRenderer);

    double timeLastGameUpdate = 0;
    double timeLastRender = 0;

    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();

        if (gameState == kGameRun) {
            double time = glfwGetTime();
            if (time - timeLastGameUpdate >= kGameTimeStep) {
                timeLastGameUpdate = time;
                tetris->update(softDrop, moveRight, moveLeft);
            }

            if (tetris->isGameOver())
                gameState = kGameOver;
        }

        double time = glfwGetTime();
        if (time - timeLastRender >= kSecondsPerFrame) {
            timeLastRender = time;

            glClearColor(1, 1, 1, 1);
            glClear(GL_COLOR_BUFFER_BIT);

            textRenderer.renderCentered("NEXT", kHudX, kHudY, kHudWidth, kColorBlack);
            textRenderer.renderCentered("HOLD", kHudX, kHudY + 2 * kHudPieceBoxHeight, kHudWidth, kColorBlack);

            if (gameState != kGameStart) {
                pieceRenderer.renderInitialShapeCentered(
                        tetris->nextPiece(), kHudX, std::round(kHudY + 1.5f * letterHeight),
                        kHudWidth, kHudPieceBoxHeight);

                pieceRenderer.renderInitialShapeCentered(
                        tetris->heldPiece(), kHudX,
                        std::round(kHudY + 2 * kHudPieceBoxHeight + 1.5f * letterHeight),
                        kHudWidth, kHudPieceBoxHeight);
            }

            int level, linesCleared, score;
            if (gameState == kGameStart) {
                level = startLevel;
                linesCleared = 0;
                score = 0;
            } else {
                level = tetris->level();
                linesCleared = tetris->linesCleared();
                score = tetris->score();
            }

            GLfloat y = 0.6f * kHeight;
            textRenderer.renderCentered("LEVEL", kHudX, y, kHudWidth, kColorBlack);
            y += 1.4 * letterHeight;
            textRenderer.renderCentered(std::to_string(level), kHudX, y, kHudWidth, kColorBlack);

            y += 2.5 * letterHeight;
            textRenderer.renderCentered("LINES", kHudX, y, kHudWidth, kColorBlack);
            y += 1.4 * letterHeight;
            textRenderer.renderCentered(std::to_string(linesCleared), kHudX, y, kHudWidth, kColorBlack);

            y += 2.5 * letterHeight;
            textRenderer.renderCentered("SCORE", kHudX, y, kHudWidth, kColorBlack);
            y += 1.4 * letterHeight;
            textRenderer.renderCentered(std::to_string(score), kHudX, y, kHudWidth, kColorBlack);

            boardRenderer.renderBackground();

            switch (gameState) {
                case kGameRun:
                    boardRenderer.renderTiles(board);
                    if (tetris->isPausedForLinesClear()) {
                        boardRenderer.playLinesClearAnimation(board, tetris->linesClearPausePercent());
                    } else {
                        boardRenderer.renderGhost(board.piece(), board.ghostRow(), board.pieceCol());
                        boardRenderer.renderPiece(board.piece(), board.pieceRow(), board.pieceCol(),
                                                  tetris->lockPercent());
                    }
                    break;
                case kGamePaused: {
                    boardRenderer.renderTiles(board, 0.4);
                    boardRenderer.renderPiece(board.piece(), board.pieceRow(), board.pieceCol(), 0, 0.4);

                    GLfloat y = kBoardY + 0.38f * kBoardHeight;

                    textRenderer.renderCentered("PAUSED", kBoardX, y, kBoardWidth, kColorWhite);

                    y = kBoardY + 0.5f * kBoardHeight;
                    GLfloat xName = kBoardX + 0.1f * kBoardWidth;
                    GLfloat xIcon = kBoardX + 0.9f * kBoardWidth;

                    GLfloat dyAlignment = 0.5f * (keyArrowLeft.height - letterHeight);
                    textRenderer.render("CONTINUE", xName, y, kColorWhite);
                    spriteRenderer.render(keyEsc, xIcon - keyEsc.width, y - dyAlignment, keyEsc.width, keyEsc.height);

                    y += 5.5 * letterHeight;
                    textRenderer.render("START SCREEN", xName, y, kColorWhite);
                    dyAlignment = 0.75f * (keyEnter.height - letterHeight);
                    spriteRenderer.render(keyEnter, xIcon - keyEnter.width, y - dyAlignment,
                                          keyEnter.width, keyEnter.height);

                    break;
                }
                case kGameStart: {
                    GLfloat y = kBoardY + 0.05f * kBoardHeight;

                    textRenderer.renderCentered("CONTROLS", kBoardX, y, kBoardWidth, kColorWhite);

                    y += 4 * letterHeight;

                    GLfloat xName = kBoardX + 0.1f * kBoardWidth;
                    GLfloat xIcon = kBoardX + 0.9f * kBoardWidth;
                    GLfloat dyAlignment = 0.5f * (keyArrowLeft.height - letterHeight);
                    GLfloat dyBetweenRows = 3.8f * letterHeight;

                    textRenderer.render("MOVE", xName, y, kColorWhite);

                    GLfloat iconsWidth = keyArrowLeft.width + keyArrowRight.width;
                    spriteRenderer.render(keyArrowLeft, xIcon - iconsWidth, y - dyAlignment, keyArrowLeft.width,
                                          keyArrowLeft.height);
                    spriteRenderer.render(keyArrowRight, xIcon - iconsWidth + keyArrowLeft.width,
                                          y - dyAlignment, keyArrowLeft.width, keyArrowLeft.height);

                    y += dyBetweenRows;
                    textRenderer.render("ROTATE", xName, y, kColorWhite);
                    iconsWidth = keyZ.width + keyX.width;
                    spriteRenderer.render(keyZ, xIcon - iconsWidth, y - dyAlignment, keyZ.width, keyZ.height);
                    spriteRenderer.render(keyX, xIcon - iconsWidth + keyZ.width , y - dyAlignment,
                                          keyX.width, keyZ.height);

                    y += dyBetweenRows;
                    textRenderer.render("SOFT DROP", xName, y, kColorWhite);
                    spriteRenderer.render(keyArrowDown, xIcon - keyArrowDown.width, y - dyAlignment,
                                          keyArrowDown.width, keyArrowDown.height);

                    y += dyBetweenRows;
                    textRenderer.render("HARD DROP", xName, y, kColorWhite);
                    spriteRenderer.render(keySpace, xIcon - keySpace.width, y - dyAlignment, keySpace.width,
                                          keySpace.height);

                    y += dyBetweenRows;
                    textRenderer.render("HOLD", xName, y, kColorWhite);
                    spriteRenderer.render(keyC, xIcon - keyC.width, y - dyAlignment, keyC.width, keyC.height);

                    y += dyBetweenRows;
                    textRenderer.render("PAUSE", xName, y, kColorWhite);
                    spriteRenderer.render(keyEsc, xIcon - keyEsc.width, y - dyAlignment, keyEsc.width, keyEsc.height);

                    y = kBoardY + 0.585f * kBoardHeight;
                    GLfloat lineWidth = textRenderer.computeWidth("USE") + keyArrowDown.width + keyArrowUp.width
                                       + 2 * letterWidth + textRenderer.computeWidth("TO SELECT");
                    GLfloat x = kBoardX + 0.5f * (kBoardWidth - lineWidth);

                    textRenderer.render("USE", x, y, kColorWhite);
                    x += textRenderer.computeWidth("USE") + letterWidth;
                    spriteRenderer.render(keyArrowDown, x, y - dyAlignment, keyArrowDown.width, keyArrowDown.height);
                    x += keyArrowDown.width;
                    spriteRenderer.render(keyArrowUp, x, y - dyAlignment, keyArrowUp.width, keyArrowUp.height);
                    x += keyArrowUp.width + letterWidth;
                    textRenderer.render("TO SELECT", x, y, kColorWhite);
                    y += dyBetweenRows;
                    textRenderer.renderCentered("THE LEVEL", kBoardX, y, kBoardWidth, kColorWhite);

                    y = kBoardY + 0.8f * kBoardHeight;
                    lineWidth = textRenderer.computeWidth("PRESS") + keyEnter.width + 2 * letterWidth +
                                textRenderer.computeWidth("TO START");
                    x = kBoardX + 0.5f * (kBoardWidth - lineWidth);
                    dyAlignment = 0.7f * (keyEnter.height - letterHeight);

                    textRenderer.render("PRESS", x, y, kColorWhite);
                    x += textRenderer.computeWidth("PRESS") + letterWidth;
                    spriteRenderer.render(keyEnter, x, y - dyAlignment, keyEnter.width, keyEnter.height);
                    x += keyEnter.width + letterWidth;
                    textRenderer.render("TO START", x, y, kColorWhite);
                    break;
                }
                case kGameOver: {
                    boardRenderer.renderTiles(board, 0.4);

                    GLfloat y = kBoardY + 0.4f * kBoardHeight;
                    textRenderer.renderCentered("GAME OVER", 2 * kMargin + kHudWidth, y, kBoardWidth,
                                                kColorWhite);

                    y = kBoardY + 0.53f * kBoardHeight;
                    GLfloat lineWidth = textRenderer.computeWidth("PRESS") + keyEnter.width + 2 * letterWidth +
                                        textRenderer.computeWidth("TO");
                    GLfloat x = kBoardX + 0.5f * (kBoardWidth - lineWidth);
                    GLfloat dyAlignment = 0.7f * (keyEnter.height - letterHeight);

                    textRenderer.render("PRESS", x, y, kColorWhite);
                    x += textRenderer.computeWidth("PRESS") + letterWidth;
                    spriteRenderer.render(keyEnter, x, y - dyAlignment, keyEnter.width, keyEnter.height);
                    x += keyEnter.width + letterWidth;
                    textRenderer.render("TO", x, y, kColorWhite);
                    y += 3.5 * letterHeight;
                    textRenderer.renderCentered("CONTINUE", kBoardX, y, kBoardWidth, kColorWhite);
                }
            }
            glfwSwapBuffers(window);
        }
    }

    return EXIT_SUCCESS;
}


text:
@extends('app')

@section('content')

    @include('nav_admin')

Users Permissions

For Project {{$current_project->name}}

                Id
                Name
                Email
                Level
                Attach/Detach from Project

            @foreach($users as $user)

id}}' onclick="selectRow({{$user->id}})">
                    {{$user->id}}
                    {{$user->name}}
                    {{$user->email}}
                    @if ($user->projects()->find($current_project->id))

                            {{$levels->find($user->projects()->find($current_project->id)->pivot->level_id)->description}}

                        <button  class="detach_user" id="{{$user->id}}">  </button>
                    @else
                        -
                        <button class="attach_user" id="{{$user->id}}">  </button>
                    @endif

            @endforeach

@endsection


text:
package 'git'

template '/.gitignore' do
  source 'root.gitignore.erb'
end

bash "Setup backup dir: #{node['chef_wordpress']['config_backup_repo_path']}" do
  code <<-EOH
    unset GIT_WORK_TREE
    git --bare init #{node['chef_wordpress']['config_backup_repo_path']}
  EOH
  not_if { ::Dir.exist?(node['chef_wordpress']['config_backup_repo_path']) }
end

template '/usr/local/bin/backupwpgit' do
  source 'backupwpgit.sh.erb'
  variables(
    config_backup_repo_path: node['chef_wordpress']['config_backup_repo_path']
  )
  mode 0o755
end

cron 'backup nginx' do
  minute '*/15'
  user 'root'
  command %w{
    /usr/local/bin/backupwpgit
  }.join(' ')
end

execute 'backup config now' do
  command '/usr/local/bin/backupwpgit'
  return [0, 1]
end


text:
class CreateLeaders < ActiveRecord::Migration
  def change
    create_table :leaders do |t|
      t.string :name
      t.integer :count

      t.timestamps null: false
    end
  end
end


text:
/*
 * Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;

using Amazon.RDS.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.RDS.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// AddSourceIdentifierToSubscription Request Marshaller
    /// </summary>
    public class AddSourceIdentifierToSubscriptionRequestMarshaller : IMarshaller<IRequest, AddSourceIdentifierToSubscriptionRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
    {
        /// <summary>
        /// Marshaller the request object to the HTTP request.
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public IRequest Marshall(AmazonWebServiceRequest input)
        {
            return this.Marshall((AddSourceIdentifierToSubscriptionRequest)input);
        }

        /// <summary>
        /// Marshaller the request object to the HTTP request.
        /// </summary>
        /// <param name="publicRequest"></param>
        /// <returns></returns>
        public IRequest Marshall(AddSourceIdentifierToSubscriptionRequest publicRequest)
        {
            IRequest request = new DefaultRequest(publicRequest, "Amazon.RDS");
            request.Parameters.Add("Action", "AddSourceIdentifierToSubscription");
            request.Parameters.Add("Version", "2014-10-31");

            if(publicRequest != null)
            {
                if(publicRequest.IsSetSourceIdentifier())
                {
                    request.Parameters.Add("SourceIdentifier", StringUtils.FromString(publicRequest.SourceIdentifier));
                }
                if(publicRequest.IsSetSubscriptionName())
                {
                    request.Parameters.Add("SubscriptionName", StringUtils.FromString(publicRequest.SubscriptionName));
                }
            }
            return request;
        }
    }
}


text:
using System;
using System.IO;
using WindowsAccessBridgeInterop;

namespace AccessBridgeExplorer {
  public class PropertyGroupErrorEventArgs : ErrorEventArgs {
    private readonly PropertyGroup _propertyGroup;

    public PropertyGroupErrorEventArgs(PropertyGroup propertyGroup, Exception exception) : base(exception) {
      _propertyGroup = propertyGroup;
    }

    public PropertyGroup PropertyGroup {
      get { return _propertyGroup; }
    }
  }
}


text:
layout: posts
title: VINCI Best Poster Award
author: Sophie Engle
icon: fas fa-trophy
---

Our poster "Interactive Exploration of Multidimensional YouTube Data Using the GPLOM Technique" by Seimei Matsusaki, Xi Han, Alark Joshi, and Sophie Engle won the Best Poster Award at the 9th International Symposium on Visual Information Communication and Interaction (VINCI)!

Check out the poster, the abstract, or the live tool!