text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Autopilot\V1\Assistant;

use Twilio\ListResource;
use Twilio\Version;

/**
 * PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
 */
class DialogueList extends ListResource {
    /**
     * Construct the DialogueList
     *
     * @param Version $version Version that contains the resource
     * @param string $assistantSid The unique ID of the parent Assistant.
     * @return \Twilio\Rest\Autopilot\V1\Assistant\DialogueList
     */
    public function __construct(Version $version, $assistantSid) {
        parent::__construct($version);

        // Path Solution
        $this->solution = array('assistantSid' => $assistantSid, );
    }

    /**
     * Constructs a DialogueContext
     *
     * @param string $sid The sid
     * @return \Twilio\Rest\Autopilot\V1\Assistant\DialogueContext
     */
    public function getContext($sid) {
        return new DialogueContext($this->version, $this->solution['assistantSid'], $sid);
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString() {
        return '[Twilio.Autopilot.V1.DialogueList]';
    }
}


text:
xap9x  --- BETA ---
=================

##XAP 9.x Recipe

### Overview

This folder contains service recipes that run GigaSpace XAP version 9.x.  The recipes consist of a management and container recipe.  When composed in an application recipe, the container recipe should start after the management recipe.

#####Recipe Installation

######Configuration
Both service recipes are configured via a standard service properties file.   The most critical configuration option is the license property, which needs to be set to a valid XAP license key (look in your gs-license.xml file).   The recipe will function without it, but the grid will be limited per the "lite" license (limited memory and instances).  The lusPort property needs to be the same for both container and management recipes.  If multiple instances of the recipe suite are installed simultaneously, this port must be different for each.

#####Installation
The only requirement for installation is that the management recipe be installed prior to the container recipe.

###Recipe Details
#####Recipe #1 : xap-management
The xap-management recipe launches the XAP management processes: GSA, GSM and LUS, as well as the Web UI.  The LUS port is configurable in the recipe properties, and effectively identifies the cluster.  All clusters (including Cloudify itself) must have unique LUS ports.

xap-management can support up to 2 instances.  Containers (GSCs) are deployed via the xap-container recipe.  xap-management, on starting, updates the hosts table on the containers (if any) via a custom command.  Containers likewise update their hosts tables on startup to avoid static IP configuration in the recipes.
Note that in localcloud mode the webui url is http://localhost:9099

The recipe provides a link to the XAP Web UI in the details section of the Cloudify UI.

The xap-management recipe launches a butterfly server by default (see butterfly below).
Set the flag "butterflyEnabled" in the properties file to true/false to enable/disable launching butterfly server.

Url: http://ip:8081.

###### Custom Commands

The recipe provides several custom commands:

deploy-pu

 Deploys a stateful/grid processing unit.  Usage: deploy-pu puurl schema partitions backups max-per-vm max-per-machine name.  Arguments (all args are required):

name: The deployd name for the processing unit.  Defaults to the pu file name unless overridden.

puurl: A URL where the processing unit jar can be found

schema: The cluster schema (e.g. partitioned-sync2backup)

partitions: The number of partitions. Ignored if not partitioned.

backups: The number of backups per partition. Ignored if not partitioned.

max-per-vm: Maximum instances per JVM/container.  See here for details

max-per-machine: Maximum instances per physical machine/cloud vm.   See here for details

deploy-pu-basic

A convenience command that provides defaults to deploy-pu for a basic installation. Arguments (all args are required):

puurl: A URL where the processing unit jar can be found

Notes: deploys a non-partitioned, single instance cluster.  Useful for simple applications or testing.

deploy-grid

Deploys a space.  Usage: deploy-grid spaceName schema partitions backups max-per-vm max-per-machine.

Notes: see deploy-pu for argument meanings.

deploy-grid-basic

Deploys a space with one primary and one backup instances.  Usage: deploy-grid-basic spaceName.

undeploy-grid

Undeploys a grid by name.  Usage: undeploy-grid name.  Args:

name: The name of the grid as assigned in the deploy-grid command.

deploy-gateway

Creates and deploys a WAN gateway.   --COMING SOON--

get-lookuplocators

Returns the LOOKUPLOCATORS environment variable which XAP starts with.

#####Recipe #2: xap-container

The xap-container recipe starts a single GSC.

When it starts it locates the management nodes and updates it's lookuplocators by invoking get-lookuplocators.
The recipe has effectively no upper limit on instances and is elastic.  It has no custom commands intended for public use.

After starting (postStart), it invokes deploy-grid-basic myDataGrid

#####Recipe #3: butterfly
The butterfly recipe starts a web terminal based on websocket and tornado (butterfly).
When it starts it locates the management nodes and updates it's lookuplocators by invoking get-lookuplocators.

Url: http://localcloud:8080

Works only on Linux.

Butterfly runs a Groovy script that prompts the user to choose:

(1) Start a demo that connects to the myDataGrid space and performs write, read, read with JDBC, read with SQLQuery on Pojos and Documents Objects. When it ends, it opens a Groovy Shell as in option (2) below.

(2) Open Groovy Interactive Shell. All XAP's classes are imported to the Groovy Shell.

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://secure.travis-ci.org/netvlies/basecamp-php.png)](https://secure.travis-ci.org/netvlies/basecamp-php)

The **Basecamp SDK for PHP** enables PHP developers to easily integrate [37signals Basecamp all new API][basecamp] into their applications.

**NOTE**: This library is under heavy development and a lot of calls haven't been implemented yet. We're looking forward to any of your PR's.

## Installation
We recommend Composer for managing dependencies. Installing is as easy as:

    $ php composer.phar require netvlies/basecamp-php

## Usage

To use the library the only requirement is you have a account.
Upon creating the client you have to pass your credentials or an OAuth token. Furthermore you need your userId to construct the URI's.

### Authorization with username and password

```php
<?php

$client = \Basecamp\BasecampClient::factory(array(
    'auth' => 'http',
    'username' => 'you@email.com',
    'password' => 'secret',
    'user_id' => 99999999,
    'app_name' => 'My Wicked Application',
    'app_contact' => 'http://mywickedapplication.com'
));
```

### Authorization with OAuth token

This library doesn't handle the OAuth authorization process for you. There are already a lot of libraries out there which handle this process perfectly for you. When you recieved your token you'll have to pass it on to the client:

```php
<?php

$client = \Basecamp\BasecampClient::factory(array(
    'auth'     => 'oauth',
    'token'    => 'Wtj4htewhtuewhuoitewh',
    'user_id'   => 99999999,
    'app_name' => 'My Wicked Application',
    'app_contact' => 'http://mywickedapplication.com'
));

```

### Identification

It is required to identify you application. This can be accomplished by using app_name and app_contact.

## About this API client

This client is build upon the shoulders of the impressive [Guzzle library][guzzle]. If you're willing to contribute to this client, make sure
to check out the docs.

## Caching

It is required to implement caching in your application. Lucky for you, using Guzzle this is peanuts! Please refer to the [official docs][caching] for more information.

Here's a quick example using the Doctrine cache:

```php
<?php

use Basecamp\BasecampClient;
use Doctrine\Common\Cache\FilesystemCache;
use Guzzle\Cache\DoctrineCacheAdapter;
use Guzzle\Plugin\Cache\CachePlugin;

$cachePlugin = new CachePlugin(array(
    'adapter' => new DoctrineCacheAdapter(new FilesystemCache(__DIR__.'/../../../../app/cache/basecamp'))
));

$this->client = BasecampClient::factory(array(
    // config options
));
$this->client->addSubscriber($cachePlugin);

```

## API calls

All services are documented below. View full service description in [src/Basecamp/Resources/service.php][service.php]

### Get archived Projects
[Basecamp API: Projects](https://github.com/basecamp/bcx-api/blob/master/sections/projects.md)

```php
$response = $client->getArchivedProjects();
```

### Get active Projects
[Basecamp API: Projects](https://github.com/basecamp/bcx-api/blob/master/sections/projects.md)

```php
$response = $client->getProjects();
```

### Get a Project
[Basecamp API: Projects](https://github.com/basecamp/bcx-api/blob/master/sections/projects.md)

```php
$response = $client->getProject( array(
    'id' => 1234567,  // Required. Project ID
) );
```

### Get all Documents
[Basecamp API: Documents](https://github.com/basecamp/bcx-api/blob/master/sections/documents.md)

```php
$response = $client->getDocumentsByProject( array(
    'projectId' => 1234567,  // Required. Project ID
) );
```

### Get a Document
[Basecamp API: Documents](https://github.com/basecamp/bcx-api/blob/master/sections/documents.md)

```php
$response = $client->getDocument( array(
    'projectId' => 1234567,  // Required. Project ID
    'documentId' => 1234567,  // Required. Document ID
) );
```

### Get Topics
[Basecamp API: Topics](https://github.com/basecamp/bcx-api/blob/master/sections/topics.md)

```php
$response = $client->getTopicsByProject( array(
    'projectId' => 1234567,  // Required. Project ID
) );
```

### Get Todo Lists
[Basecamp API: Todo lists](https://github.com/basecamp/bcx-api/blob/master/sections/todolists.md)

```php
$response = $client->getTodolistsByProject( array(
    'projectId' => 1234567,  // Required. Project ID
) );
```

### Get Todo Lists assigned to a Person
[Basecamp API: Todo lists](https://github.com/basecamp/bcx-api/blob/master/sections/todolists.md)

```php
$response = $client->getAssignedTodolistsByPerson( array(
    'personId' => 1234567,  // Required. Person id
    'page' => 1234567,  // Optional. The page to retrieve. API returns 50 todos per page.
    'due_since' => 'example',  // Optional. Will return all the to-do lists with to-dos assigned to the specified person due after the date specified. (format: 2012-03-24T11:00:00-06:00)
) );
```

### Get completed Todo Lists
[Basecamp API: Todo lists](https://github.com/basecamp/bcx-api/blob/master/sections/todolists.md)

```php
$response = $client->getCompletedTodolistsByProject( array(
    'projectId' => 1234567,  // Required. Project id
) );
```

### Create a new project
[Basecamp API: Projects](https://github.com/basecamp/bcx-api/blob/master/sections/projects.md)

```php
$response = $client->createProject( array(
    'name' => 'Example name',  // Required.
    'description' => 'Example description',  // Required.
) );
```

### Create a new document
[Basecamp API: Documents](https://github.com/basecamp/bcx-api/blob/master/sections/documents.md)

```php
$response = $client->createDocument( array(
    'projectId' => 1234567,  // Required. Project ID
    'title' => 'example',  // Required.
    'content' => 'Example content',  // Required.
) );
```

### Create Todo List
[Basecamp API: Todo lists](https://github.com/basecamp/bcx-api/blob/master/sections/todolists.md)

```php
$response = $client->createTodolistByProject( array(
    'projectId' => 1234567,  // Required. Project id
    'name' => 'Example name',  // Required.
    'description' => 'Example description',  // Required.
) );
```

### Create Todo
[Basecamp API: Todos](https://github.com/basecamp/bcx-api/blob/master/sections/todos.md)

```php
$response = $client->createTodoByTodolist( array(
    'projectId' => 1234567,  // Required. Project id
    'todolistId' => 1234567,  // Required. Todo list id
    'content' => 'Example content',  // Required.
    'assignee' => array( 'id' => 1234567, 'type' => 'Person' ),  // Optional.
) );
```

### Create Comment on Todo
[Basecamp API: Comments](https://github.com/basecamp/bcx-api/blob/master/sections/comments.md)

```php
$response = $client->createCommentByTodo( array(
    'projectId' => 1234567,  // Required. Project id
    'todoId' => 1234567,  // Required. Todo id
    'content' => 'Example content',  // Required.
    'attachments' => array( array( 'token' => $upload_token, 'name' => 'file.jpg' ) ),  // Optional.
) );
```

### Get Attachments
[Basecamp API: Attachments](https://github.com/basecamp/bcx-api/blob/master/sections/attachments.md)

```php
$response = $client->getAttachmentsByProject( array(
    'projectId' => 1234567,  // Required. Project id
) );
```

### Create Attachment
[Basecamp API: Attachments](https://github.com/basecamp/bcx-api/blob/master/sections/attachments.md)

```php
$response = $client->createAttachment( array(
    'mimeType' => 'image/jpeg',  // Required. The content type of the data
    'data' => file_get_contents( 'image.jpg' ),  // Required. The attachment's binary data
) );
```

### Get Todo List
[Basecamp API: Todo lists](https://github.com/basecamp/bcx-api/blob/master/sections/todolists.md)

```php
$response = $client->getTodolist( array(
    'projectId' => 1234567,  // Required. Project id
    'todolistId' => 1234567,  // Required. Todolist id
) );
```

### Get Todo
[Basecamp API: Todos](https://github.com/basecamp/bcx-api/blob/master/sections/todos.md)

```php
$response = $client->getTodo( array(
    'projectId' => 1234567,  // Required. Project id
    'todoId' => 1234567,  // Required. Todo id
) );
```

### Update Todo
[Basecamp API: Todos](https://github.com/basecamp/bcx-api/blob/master/sections/todos.md)

```php
$response = $client->updateTodo( array(
    'projectId' => 1234567,  // Required. Project id
    'todoId' => 1234567,  // Required. Todo id
    'content' => 'Example content',  // Optional.
    'due_at' => 'example',  // Optional.
    'assignee' => array( 'id' => 1234567, 'type' => 'Person' ),  // Optional.
    'completed' => 'example',  // Optional.
) );
```

### Get current User
[Basecamp API: People](https://github.com/basecamp/bcx-api/blob/master/sections/people.md)

```php
$response = $client->getCurrentUser();
```

### Get global Events
[Basecamp API: Events](https://github.com/basecamp/bcx-api/blob/master/sections/events.md)

```php
$response = $client->getGlobalEvents( array(
    'since' => '2012-03-24T11:00:00-06:00',  // Optional. All events since given datetime (format: 2012-03-24T11:00:00-06:00)
    'page' => 1234567,  // Optional. The page to retrieve. API returns 50 events per page.
) );
```

### Get Project Events
[Basecamp API: Events](https://github.com/basecamp/bcx-api/blob/master/sections/events.md)

```php
$response = $client->getProjectEvents( array(
    'projectId' => 1234567,  // Required. Project id
    'since' => '2012-03-24T11:00:00-06:00',  // Optional. All events since given datetime (format: 2012-03-24T11:00:00-06:00)
) );
```

### Get Accesses to Project
[Basecamp API: Accesses](https://github.com/basecamp/bcx-api/blob/master/sections/accesses.md)

```php
$response = $client->getAccessesByProject( array(
    'projectId' => 1234567,  // Required. Project id
) );
```

### Get Accesses to Calendar
[Basecamp API: Accesses](https://github.com/basecamp/bcx-api/blob/master/sections/accesses.md)

```php
$response = $client->getAccessesByCalendar( array(
    'calendarId' => 1234567,  // Required. Calendar id
) );
```

### Get all People
[Basecamp API: People](https://github.com/basecamp/bcx-api/blob/master/sections/people.md)

```php
$response = $client->getPeople();
```

### Get all Groups
[Basecamp API: People](https://github.com/basecamp/bcx-api/blob/master/sections/groups.md)

```php
$response = $client->getGroups();
```

### Grant access
[Basecamp API: Access](https://github.com/basecamp/bcx-api/blob/master/sections/accesses.md)

```php
$response = $client->grantAccess( array(
    'projectId' => 1234567,  // Required. Project id
    'ids' => '',  // Required. Existing user ids
    'email_addresses' => 'example',  // Optional. Grant access to new users
) );
```

### Get all Calendars
[Basecamp API: Calendars](https://github.com/basecamp/bcx-api/blob/master/sections/calendars.md)

```php
$response = $client->getCalendars();
```

### Get single Calendar
[Basecamp API: Calendars](https://github.com/basecamp/bcx-api/blob/master/sections/calendars.md)

```php
$response = $client->getCalendar( array(
    'calendarId' => 1234567,  // Required. Calendar id
) );
```

### Create new Calendar
[Basecamp API: Calendars](https://github.com/basecamp/bcx-api/blob/master/sections/calendars.md)

```php
$response = $client->createCalendar( array(
    'name' => 'Example name',  // Required.
) );
```

### Update Calendar
[Basecamp API: Calendars](https://github.com/basecamp/bcx-api/blob/master/sections/calendars.md)

```php
$response = $client->updateCalendar( array(
    'calendarId' => 1234567,  // Required. Calendar id
    'name' => 'Example name',  // Required.
) );
```

### Delete Calendar
[Basecamp API: Calendars](https://github.com/basecamp/bcx-api/blob/master/sections/calendars.md)

```php
$response = $client->deleteCalendar( array(
    'calendarId' => 1234567,  // Required. Calendar id
) );
```

### Get all events
[Basecamp API: Calendar Events](https://github.com/basecamp/bcx-api/blob/master/sections/calendar_events.md)

```php
$response = $client->getAllCalendarEvents( array(
    'start_date' => 'example',  // Optional. Will return 6 weeks worth of events after the start date if the end date is not supplied (format: 2015-09-15)
    'end_date' => 'example',  // Optional. Will return 6 weeks worth of events after the start date if the end date is not supplied (format: 2015-09-15)
) );
```

### Get upcoming calendar events
[Basecamp API: Calendar Events](https://github.com/basecamp/bcx-api/blob/master/sections/calendar_events.md)

```php
$response = $client->getCalendarEvents( array(
    'calendarId' => 1234567,  // Required. Calendar id
    'start_date' => 'example',  // Optional. Will return 6 weeks worth of events after the start date if the end date is not supplied (format: 2015-09-15)
    'end_date' => 'example',  // Optional. Will return 6 weeks worth of events after the start date if the end date is not supplied (format: 2015-09-15)
) );
```

### Get past calendar events
[Basecamp API: Calendar Events](https://github.com/basecamp/bcx-api/blob/master/sections/calendar_events.md)

```php
$response = $client->getCalendarEventsPast( array(
    'calendarId' => 1234567,  // Required. Calendar id
) );
```

### Get single calendar event
[Basecamp API: Calendar Events](https://github.com/basecamp/bcx-api/blob/master/sections/calendar_events.md)

```php
$response = $client->getCalendarEvent( array(
    'calendarId' => 1234567,  // Required. Calendar id
    'eventId' => 1234567,  // Required. Event id
) );
```

### Create calendar event
[Basecamp API: Calendar Events](https://github.com/basecamp/bcx-api/blob/master/sections/calendar_events.md)

```php
$response = $client->createCalendarEvent( array(
    'calendarId' => 1234567,  // Required. Calendar id
    'summary' => 'example',  // Required. Event Summary / title
    'description' => 'Example description',  // Optional. Event Description
    'starts_at' => 'example',  // Required. Date (and time if not an all day event) that the event starts at (format: 2015-09-15 or 2015-09-15T11:50:00-05:00)
    'ends_at' => 'example',  // Optional. Date (and time if not an all day event) that the event ends at (format: 2015-09-15 or 2015-09-15T11:50:00-05:00)
    'remind_at' => 'example',  // Optional. Datetime to remind subscribers about the event via email (format: 2015-09-15T11:50:00-05:00)
    'subscribers' => '',  // Optional. Array of user id's to subscribe to the event.
    'recurring' => '',  // Optional. Array of recurring parrameters - starts_at, frequency, count, until, excluding
    'all_day' => '',  // Optional. Is the event a full day event?
) );
```

### Update a calendar event
[Basecamp API: Calendar Events](https://github.com/basecamp/bcx-api/blob/master/sections/calendar_events.md)

```php
$response = $client->updateCalendarEvent( array(
    'calendarId' => 1234567,  // Required. Calendar id
    'eventId' => 1234567,  // Required. Event id
    'summary' => 'example',  // Optional. Event Summary / title
    'description' => 'Example description',  // Optional. Event Description
    'starts_at' => 'example',  // Optional. Date (and time if not an all day event) that the event starts at (format: 2015-09-15 or 2015-09-15T11:50:00-05:00)
    'ends_at' => 'example',  // Optional. Date (and time if not an all day event) that the event ends at (format: 2015-09-15 or 2015-09-15T11:50:00-05:00)
    'remind_at' => 'example',  // Optional. Datetime to remind subscribers about the event via email (format: 2015-09-15T11:50:00-05:00)
    'subscribers' => '',  // Optional. Array of user id's to subscribe to the event.
    'recurring' => '',  // Optional. Array of recurring parrameters - starts_at, frequency, count, until, excluding
    'all_day' => '',  // Optional. Is the event a full day event?
) );
```

### Delete a calendar event
[Basecamp API: Calendar Events](https://github.com/basecamp/bcx-api/blob/master/sections/calendar_events.md)

```php
$response = $client->deleteCalendarEvent( array(
    'calendarId' => 1234567,  // Required. Calendar id
    'eventId' => 1234567,  // Required. Event id
) );
```

### Get upcoming project calendar events
[Basecamp API: Calendar Events](https://github.com/basecamp/bcx-api/blob/master/sections/calendar_events.md)

```php
$response = $client->getProjectCalendarEvents( array(
    'projectId' => 1234567,  // Required. Project ID
    'start_date' => 'example',  // Optional. Will return 6 weeks worth of events after the start date if the end date is not supplied (format: 2015-09-15)
    'end_date' => 'example',  // Optional. Will return 6 weeks worth of events after the start date if the end date is not supplied (format: 2015-09-15)
) );
```

### Get past project calendar events
[Basecamp API: Calendar Events](https://github.com/basecamp/bcx-api/blob/master/sections/calendar_events.md)

```php
$response = $client->getProjectCalendarEventsPast( array(
    'projectId' => 1234567,  // Required. Project ID
) );
```

### Get single project calendar event
[Basecamp API: Calendar Events](https://github.com/basecamp/bcx-api/blob/master/sections/calendar_events.md)

```php
$response = $client->getProjectCalendarEvent( array(
    'projectId' => 1234567,  // Required. Project id
    'eventId' => 1234567,  // Required. Event id
) );
```

### Create project calendar event
[Basecamp API: Calendar Events](https://github.com/basecamp/bcx-api/blob/master/sections/calendar_events.md)

```php
$response = $client->createProjectCalendarEvent( array(
    'projectId' => 1234567,  // Required. Project id
    'summary' => 'example',  // Required. Event Summary / title
    'description' => 'Example description',  // Optional. Event Description
    'starts_at' => 'example',  // Required. Date (and time if not an all day event) that the event starts at (format: 2015-09-15 or 2015-09-15T11:50:00-05:00)
    'ends_at' => 'example',  // Optional. Date (and time if not an all day event) that the event ends at (format: 2015-09-15 or 2015-09-15T11:50:00-05:00)
    'remind_at' => 'example',  // Optional. Datetime to remind subscribers about the event via email (format: 2015-09-15T11:50:00-05:00)
    'subscribers' => '',  // Optional. Array of user id's to subscribe to the event.
    'recurring' => '',  // Optional. Array of recurring parrameters - starts_at, frequency, count, until, excluding
    'all_day' => '',  // Optional. Is the event a full day event?
) );
```

### Update a project calendar event
[Basecamp API: Calendar Events](https://github.com/basecamp/bcx-api/blob/master/sections/calendar_events.md)

```php
$response = $client->updateProjectCalendarEvent( array(
    'projectId' => 1234567,  // Required. Project id
    'eventId' => 1234567,  // Required. Event id
    'summary' => 'example',  // Optional. Event Summary / title
    'description' => 'Example description',  // Optional. Event Description
    'starts_at' => 'example',  // Optional. Date (and time if not an all day event) that the event starts at (format: 2015-09-15 or 2015-09-15T11:50:00-05:00)
    'ends_at' => 'example',  // Optional. Date (and time if not an all day event) that the event ends at (format: 2015-09-15 or 2015-09-15T11:50:00-05:00)
    'remind_at' => 'example',  // Optional. Datetime to remind subscribers about the event via email (format: 2015-09-15T11:50:00-05:00)
    'subscribers' => '',  // Optional. Array of user id's to subscribe to the event.
    'recurring' => '',  // Optional. Array of recurring parrameters - starts_at, frequency, count, until, excluding
    'all_day' => '',  // Optional. Is the event a full day event?
) );
```

### Delete a project calendar event
[Basecamp API: Calendar Events](https://github.com/basecamp/bcx-api/blob/master/sections/calendar_events.md)

```php
$response = $client->deleteProjectCalendarEvent( array(
    'projectId' => 1234567,  // Required. Project id
    'eventId' => 1234567,  // Required. Event id
) );
```

[basecamp]: https://basecamp.com/
[guzzle]: http://guzzlephp.org/
[caching]: http://guzzlephp.org/plugins/cache-plugin.html
[service.php]: https://github.com/netvlies/basecamp-php/blob/master/src/Basecamp/Resources/service.php


text:
"use strict";

// Start the main app logic.
requirejs(
  [ 'hft/gameserver',
    'hft/gamesupport',
    'clocksyncimpl',
  ],
  function(GameServer, GameSupport, ClockSyncImpl) {

  var globals = {
    haveServer: true,
  };

  var noop = function() {
  };

  var setupPlayer = function(netPlayer, name) {
    // The only reason I connect these is so people don't ask about the 'no event' messages that might appear in the console
    netPlayer.addEventListener('setName', noop);
    netPlayer.addEventListener('setColor', noop);
    netPlayer.addEventListener('disconnect', noop);
  };

  var server = new GameServer();
  server.addEventListener('playerconnect', setupPlayer);
  GameSupport.init(server, globals);

  ClockSyncImpl(arguments);
});


text:
An array of all the subdomains in this request's URL.

### Usage
```usage
req.subdomains;
```

### Example

If the requested URL was "https://ww3.staging.ibm.com":

```javascript
req.subdomains;
// -> ['ww3', 'staging']
```

<docmeta name="displayName" value="req.subdomains">
<docmeta name="pageType" value="property">


text:
<?php
namespace Laraquick\Controllers\Traits\Crud;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Laraquick\Helpers\DB;

/**
 * Methods for updating a resource
 *
 */
trait Update
{
    use Authorize;

    /**
     * Create a 404 not found error response
     *
     * @param string $message The message to send with a 404 status code
     * @return Response
     */
    abstract protected function notFoundError($message = "Resource not found");

    /**
     * Error message for when an update action fails
     *
     * @param string $message The message to send with a 500 status code
     * @return Response
     */
    abstract protected function updateFailedError($message = 'Update failed');

    /**
     * Create a model not set error response
     *
     * @param string $message The message to send with a 500 status code
     * @return Response
     */
    abstract protected function modelNotSetError($message = 'Model not set for action');

    /**
     * The model to use in the update method.
     *
     * @return mixed
     */
    abstract protected function updateModel();

    /**
     * Called after validation but before update method is called
     *
     * @param array $data The data to update the model with
     * @param Model $model The model to be updated
     * @return mixed The response to send or null
     */
    protected function beforeUpdate(array &$data, Model $model)
    {
    }

    /**
     * Called when an error occurs in a update operation
     *
     * @param array $data The data from the request
     * @param Model $model The model from the id
     * @return void
     */
    protected function rollbackUpdate(array &$data, Model $model)
    {
    }

    /**
     * Update the specified resource.
     * @param  Request $request
     * @param int $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        $model = $this->updateModel();

        $requestData = $request->all();
        $data = $this->validateRequest($this->validationRules($requestData, $id), $this->validationMessages($requestData, $id));

        $item = is_object($model)
            ? $model->find($id)
            : $model::find($id);

        if (!$item) {
            return $this->notFoundError();
        }

        $this->authorizeMethod('update', [$model, $item]);

        return DB::transaction(
            function () use (&$data, &$item) {
                if ($resp = $this->beforeUpdate($data, $item)) {
                    return $resp;
                }

                $result = $item->update($data);

                if (!$result) {
                    throw new \Exception('Update method returned falsable');
                }

                if ($resp = $this->beforeUpdateResponse($item)) {
                    return $resp;
                }

                return $this->updateResponse($item);
            },
            function ($ex) use ($data, $item) {
                $message = $ex->getMessage();

                try {
                    $this->rollbackUpdate($data, $item);
                } catch (\Exception $ex) {
                    $message = $ex->getMessage();
                }

                return $this->updateFailedError($message);
            }
        );
    }

    /**
     * Called on success but before sending the response
     *
     * @param Model $model
     * @return mixed The response to send or null
     */
    protected function beforeUpdateResponse(Model $model)
    {
    }

    /**
     * Called for the response to method update()
     *
     * @param Model $model
     * @return Response|array
     */
    abstract protected function updateResponse(Model $model);
}


text:
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Route } from 'react-router-dom'
import { Client, Provider } from 'nesquirk'

import TodoList from './TodoList'
import AddTodo from './AddTodo'
import EditTodo from './EditTodo'
import ViewTodo from './ViewTodo'

// Setup the client connection
const client = new Client('ws://localhost:3000')
client.connect((err) => { if (err) console.error('Failed to connect', err) })

ReactDOM.render(
  <Provider client={client}>
    <Router>
      <div className='container'>
        <Route exact path='/' component={TodoList} />
        <Route exact path='/add' component={AddTodo} />
        <Route exact path='/edit/:todoId' component={EditTodo} />
        <Route exact path='/view/:todoId' component={ViewTodo} />
      </div>
    </Router>
  </Provider>,
  document.getElementById('root')
)


text:
<?php

namespace Wadify\Test\Token;

use Wadify\Token\Token;

class TokenTest extends \PHPUnit_Framework_TestCase
{

    public function testGetters()
    {
        // Arrange.
        $accessToken = 'foo';
        $expires = 'bar';
        $refreshToken = 'bar-foo';

        // Act.
        $token = new Token($accessToken, $expires, $refreshToken);

        // Assert
        $this->assertEquals($accessToken, $token->getAccessToken());
        $this->assertEquals($expires, $token->getExpires());
        $this->assertEquals($refreshToken, $token->getRefreshToken());
    }

    public function testToStringReturnsAValidJson()
    {
        // Arrange.
        $accessToken = 'foo';
        $expires = 'bar';
        $refreshToken = 'bar-foo';

        // Act.
        $token = new Token($accessToken, $expires, $refreshToken);

        // Assert.
        $this->assertJson((string)$token);
    }
}


text:
package parser

import (
	"math/big"

	"github.com/ark-lang/ark/src/lexer"
)

type ParseNode interface {
	Where() lexer.Span
	SetWhere(lexer.Span)

	Attrs() AttrGroup
	SetAttrs(AttrGroup)

	Documentable
	SetDocComments([]*DocComment)
}

type DocComment struct {
	Contents string
	Where    lexer.Span
}

type Documentable interface {
	DocComments() []*DocComment
}

// utility
type baseNode struct {
	where lexer.Span
	attrs AttrGroup
	dcs   []*DocComment
}

func (v *baseNode) Where() lexer.Span                { return v.where }
func (v *baseNode) SetWhere(where lexer.Span)        { v.where = where }
func (v *baseNode) Attrs() AttrGroup                 { return v.attrs }
func (v *baseNode) SetAttrs(attrs AttrGroup)         { v.attrs = attrs }
func (v *baseNode) DocComments() []*DocComment       { return v.dcs }
func (v *baseNode) SetDocComments(dcs []*DocComment) { v.dcs = dcs }

type LocatedString struct {
	Where lexer.Span
	Value string
}

func NewLocatedString(token *lexer.Token) LocatedString {
	return LocatedString{Where: token.Where, Value: token.Contents}
}

func (v LocatedString) IsEmpty() bool {
	return v.Value == ""
}

// main tree
type ParseTree struct {
	baseNode
	Source *lexer.Sourcefile
	Nodes  []ParseNode
	//Name   string
}

func (v *ParseTree) AddNode(node ParseNode) {
	v.Nodes = append(v.Nodes, node)
}

// for handling modules
type NameNode struct {
	baseNode
	Modules []LocatedString
	Name    LocatedString
}

// directives
type LinkDirectiveNode struct {
	baseNode
	Library LocatedString
}

type UseDirectiveNode struct {
	baseNode
	Module *NameNode
}

// types
type ReferenceTypeNode struct {
	baseNode
	TargetType *TypeReferenceNode
	Mutable    bool
}

type PointerTypeNode struct {
	baseNode
	TargetType *TypeReferenceNode
	Mutable    bool
}

type TupleTypeNode struct {
	baseNode
	MemberTypes []*TypeReferenceNode
}

type FunctionTypeNode struct {
	baseNode
	ParameterTypes []*TypeReferenceNode
	ReturnType     *TypeReferenceNode
	IsVariadic     bool
}

type ArrayTypeNode struct {
	baseNode
	MemberType    *TypeReferenceNode
	IsFixedLength bool
	Length        int
}

type NamedTypeNode struct {
	baseNode
	Name *NameNode
}

type TypeReferenceNode struct {
	baseNode
	Type             ParseNode
	GenericArguments []*TypeReferenceNode
}

// decls

type DeclNode interface {
	ParseNode
	IsPublic() bool // only used for top-level nodes
	SetPublic(bool)
}

type baseDecl struct {
	baseNode
	public bool
}

func (v *baseDecl) SetPublic(p bool) {
	v.public = p
}

func (v baseDecl) IsPublic() bool {
	return v.public
}

type InterfaceTypeNode struct {
	baseNode
	Functions    []*FunctionHeaderNode
	GenericSigil *GenericSigilNode
}

type StructTypeNode struct {
	baseNode
	Members      []*StructMemberNode
	GenericSigil *GenericSigilNode
}

type StructMemberNode struct {
	baseNode
	Public bool
	Name   LocatedString
	Type   *TypeReferenceNode
}

type FunctionHeaderNode struct {
	baseNode
	Anonymous    bool
	Name         LocatedString
	GenericSigil *GenericSigilNode
	Arguments    []*VarDeclNode
	ReturnType   *TypeReferenceNode
	Variadic     bool

	StaticReceiverType *NamedTypeNode // use this if static
	Receiver           *VarDeclNode   // use this if not static. this would be so much nicer with tagged unions...
}

type FunctionNode struct {
	baseNode
	Header *FunctionHeaderNode
	Body   *BlockNode
	Stat   ParseNode
	Expr   ParseNode
}

type FunctionDeclNode struct {
	baseDecl
	Function *FunctionNode
}

type LambdaExprNode struct {
	baseNode
	Function *FunctionNode
}

type EnumTypeNode struct {
	baseNode
	Members      []*EnumEntryNode
	GenericSigil *GenericSigilNode
}

type EnumEntryNode struct {
	baseNode
	Name       LocatedString
	Value      *NumberLitNode
	TupleBody  *TupleTypeNode
	StructBody *StructTypeNode
}

type VarDeclNode struct {
	baseDecl
	Name    LocatedString
	Type    *TypeReferenceNode
	Value   ParseNode
	Mutable LocatedString

	IsImplicit           bool
	ReceiverGenericSigil *GenericSigilNode
}

type DestructVarDeclNode struct {
	baseDecl
	Names   []LocatedString
	Mutable []bool
	Value   ParseNode
}

type TypeDeclNode struct {
	baseDecl
	Name         LocatedString
	GenericSigil *GenericSigilNode
	Type         ParseNode
}

type GenericSigilNode struct {
	baseNode
	GenericParameters []*TypeParameterNode
}

type TypeParameterNode struct {
	baseNode
	Name        LocatedString
	Constraints []*TypeReferenceNode // should be all interface type references
}

// statements
type DeferStatNode struct {
	baseNode
	Call *CallExprNode
}

type IfStatNode struct {
	baseNode
	Parts    []*ConditionBodyNode
	ElseBody *BlockNode
}

type ConditionBodyNode struct {
	baseNode
	Condition ParseNode
	Body      *BlockNode
}

type MatchStatNode struct {
	baseNode
	Value ParseNode
	Cases []*MatchCaseNode
}

type MatchCaseNode struct {
	baseNode
	Pattern ParseNode
	Body    ParseNode
}

type LoopStatNode struct {
	baseNode
	Condition ParseNode
	Body      *BlockNode
}

type ReturnStatNode struct {
	baseNode
	Value ParseNode
}

type BlockStatNode struct {
	baseNode
	Body *BlockNode
}

type BlockNode struct {
	baseNode
	NonScoping bool
	Nodes      []ParseNode
}

type CallStatNode struct {
	baseNode
	Call *CallExprNode
}

type AssignStatNode struct {
	baseNode
	Target ParseNode
	Value  ParseNode
}

type BinopAssignStatNode struct {
	baseNode
	Target   ParseNode
	Operator BinOpType
	Value    ParseNode
}

type BreakStatNode struct {
	baseNode
}

type NextStatNode struct {
	baseNode
}

// expressions
type BinaryExprNode struct {
	baseNode
	Lhand    ParseNode
	Rhand    ParseNode
	Operator BinOpType
}

type ArrayLenExprNode struct {
	baseNode
	ArrayExpr ParseNode
}

type SizeofExprNode struct {
	baseNode
	Value ParseNode
	Type  *TypeReferenceNode
}

type AddrofExprNode struct {
	baseNode
	Value       ParseNode
	Mutable     bool
	IsReference bool
}

type CastExprNode struct {
	baseNode
	Type  *TypeReferenceNode
	Value ParseNode
}

type UnaryExprNode struct {
	baseNode
	Value    ParseNode
	Operator UnOpType
}

type CallExprNode struct {
	baseNode
	Function  ParseNode
	Arguments []ParseNode
}

type GenericNameNode struct { // TODO what is this
	baseNode
	Name              *NameNode
	GenericParameters []*TypeReferenceNode
}

// access expressions
type VariableAccessNode struct {
	baseNode
	Name              *NameNode
	GenericParameters []*TypeReferenceNode // TODO rename to GArguments
}

type StructAccessNode struct {
	baseNode
	Struct ParseNode
	Member LocatedString
}

type ArrayAccessNode struct {
	baseNode
	Array ParseNode
	Index ParseNode
}

type DiscardAccessNode struct {
	baseNode
}

type EnumPatternNode struct {
	baseNode
	MemberName *NameNode
	Names      []LocatedString
}

// literals

type TupleLiteralNode struct {
	baseNode
	Values []ParseNode
}

type CompositeLiteralNode struct {
	baseNode
	Type   *TypeReferenceNode
	Fields []LocatedString // has same length as Values. missing fields have zero value.
	Values []ParseNode
}

type BoolLitNode struct {
	baseNode
	Value bool
}

type NumberLitNode struct {
	baseNode
	IsFloat    bool
	IntValue   *big.Int
	FloatValue float64
	FloatSize  rune
}

type StringLitNode struct {
	baseNode
	Value     string
	IsCString bool
}

type RuneLitNode struct {
	baseNode
	Value rune
}


text:
/* SPDX-License-Identifier: BSD-2-Clause */

#include <tilck/common/basic_defs.h>
#include <tilck/common/string_util.h>
#include <tilck/common/printk.h>
#include <tilck/common/arch/generic_x86/x86_utils.h>
#include <tilck/common/arch/generic_x86/cpu_features.h>

#include <multiboot.h>

#include "realmode_call.h"
#include "common.h"
#include "mm.h"

#define BIOS_INT15h_READ_MEMORY_MAP        0xE820
#define BIOS_INT15h_READ_MEMORY_MAP_MAGIC  0x534D4150

static u64
calculate_tot_usable_mem(struct mem_info *mi)
{
   u64 tot_usable = 0;

   for (u32 i = 0; i < mi->count; i++) {

      if (mi->mem_areas[i].type == MEM_USABLE)
         tot_usable += mi->mem_areas[i].len;
   }

   return tot_usable;
}

static void
e820_mmap(void *buf, size_t buf_size, struct mem_info *mi)
{
   struct PACKED {

      u32 base_low;
      u32 base_hi;
      u32 len_low;
      u32 len_hi;
      u32 type;
      u32 acpi;

   } *bios_mem_area = (void *)BIOS_MEM_AREA_BUF;

   u32 eax, ebx, ecx, edx, esi, edi, flags;
   struct mem_area *mem_areas = buf;
   ulong buf_end = (ulong) buf + buf_size;
   u32 mem_areas_count = 0;

   /*
    * NOTE: ES = 0. This means that `bios_mem_area` MUST BE a pointer in the
    * first 64 KB. In order to support pointers in the 1st MB, realmode_call()
    * has to be extended to support passing a value for the ES segment register
    * as well.
    */
   edi = (u32)bios_mem_area;
   ebx = 0;

   while (true) {

      mem_areas->acpi = 1;
      eax = BIOS_INT15h_READ_MEMORY_MAP;
      edx = BIOS_INT15h_READ_MEMORY_MAP_MAGIC;
      ecx = sizeof(*bios_mem_area);

      realmode_call(&realmode_int_15h, &eax, &ebx,
                    &ecx, &edx, &esi, &edi, &flags);

      if (!ebx)
         break;

      if (flags & EFLAGS_CF) {

         if (mem_areas_count > 0)
            break;

         panic("Error while reading memory map: CF set");
      }

      if (eax != BIOS_INT15h_READ_MEMORY_MAP_MAGIC)
         panic("Error while reading memory map: eax != magic");

      struct mem_area m = {
         .base = bios_mem_area->base_low | ((u64)bios_mem_area->base_hi << 32),
         .len  = bios_mem_area->len_low  | ((u64)bios_mem_area->len_hi << 32),
         .type = bios_mem_area->type,
         .acpi = bios_mem_area->acpi,
      };

      if (m.base == 0 && m.len == 0) {

         /*
          * Hack: on some emulators, like PCem, while emulating an Intel VC440FX
          * machine, E820 seems to exist and behave well, but in reality it
          * doesn't report EBX=0 as "end", nor it sets the carry in EFLAGS.
          * This might be caused by a corrupted firmware. This needs testing on
          * real hardware.
          */
         break;
      }

      if ((ulong)(mem_areas + mem_areas_count) >= buf_end)
         panic("No enough memory for the memory map");

      memcpy(mem_areas + mem_areas_count, &m, sizeof(struct mem_area));
      mem_areas_count++;
   }

   mi->mem_areas = mem_areas;
   mi->count = mem_areas_count;
}

static void
legacy_88h_mmap(void *buf, size_t buf_size, struct mem_info *mi)
{
   /*
    * INT 15h, AH=88h - Get Extended Memory Size
    * For more, see: http://www.uruk.org/orig-grub/mem64mb.html
    */

   u32 eax = 0x88;
   u32 ebx = 0;
   u32 ecx = 0;
   u32 edx = 0;
   u32 esi = 0;
   u32 edi = 0;
   u32 flags = 0;

   realmode_call(&realmode_int_15h, &eax, &ebx,
                 &ecx, &edx, &esi, &edi, &flags);

   if (flags & EFLAGS_CF)
      panic("INT 15h, AH=88h failed");

   /*
    * Now in AX we should get the number of contiguous KB above 1 MB.
    * For the memory below 1 MB, we can use a conservative hard-coded
    * configuration.
    */

   mi->mem_areas = buf;

   mi->mem_areas[0].base = 0x500;
   mi->mem_areas[0].len = 0x80000 - 0x500;
   mi->mem_areas[0].type = MEM_USABLE;

   mi->mem_areas[1].base = 1 * MB; // + 1 MB
   mi->mem_areas[1].len = (eax & 0xffff) * KB;
   mi->mem_areas[1].type = MEM_USABLE;

   mi->count = 2;
}

void read_memory_map(void *buf, size_t buf_size, struct mem_info *mi)
{
   /* Try first with the most reliable method for machines made after 2002 */
   e820_mmap(buf, buf_size, mi);

   if (calculate_tot_usable_mem(mi) >= 1 * MB) {

      /*
       * E820 succeeded.
       *
       * Why checking for success in this weird way? On older machines, at
       * least on emulators like PCem, E820 might appear to work, but reporting
       * only 640 KB of available memory, despite the VM having more than 16 MB.
       * So, to detect such weird cases, we just check if E820 detected more
       * than 1 MB of usable memory. If it didn't, something went seriously
       * wrong.
       *
       * Q: What if E820 legitimately returned a memory map with less than 1 MB
       * of usable memory?
       *
       * A: Tilck cannot boot nor run in any case on x86 with less than 1 MB of
       * memory. On other architectures, it might be able to, but it won't use
       * this x86-specific bootloader.
       */

      return;
   }

   /* E820 explicitly failed or didn't work properly */
   bzero(buf, buf_size);
   mi->count = 0;

   /* Try with INT 15h, AX=88h, which should work on any PC */
   legacy_88h_mmap(buf, buf_size, mi);
}

void poison_usable_memory(struct mem_info *mi)
{
   if (!in_hypervisor())
      return; /* it's better to use this feature only in VMs */

   for (u32 i = 0; i < mi->count; i++) {

      struct mem_area *ma = mi->mem_areas + i;

      if (ma->type == MEM_USABLE && ma->base >= MB) {

         /* Poison only memory regions above the 1st MB */
         memset32(TO_PTR(ma->base), FREE_MEM_POISON_VAL, (u32)ma->len / 4);
      }
   }
}

ulong get_usable_mem(struct mem_info *mi, ulong min_paddr, ulong size)
{
   struct mem_area *ma;
   u64 mbase, mend;

   for (u32 i = 0; i < mi->count; i++) {

      ma = mi->mem_areas + i;
      mbase = ma->base;
      mend = ma->base + ma->len;

      if (ma->type != MEM_USABLE)
         continue;

      if (mend <= min_paddr)
         continue;

      if (mbase < min_paddr) {
         /*
          * The memory area starts before the lowest address we can use,
          * therefore, for our purposes it's as if it just started at min_addr.
          */
         mbase = min_paddr;
      }

      if (mbase + size >= (1ull << 32))
         continue;

      if (mend - mbase >= size) {

         /* Great, we have enough space in this area. */
         return mbase;
      }
   }

   return 0;
}

ulong get_high_usable_mem(struct mem_info *mi, ulong size)
{
   struct mem_area *ma;
   u64 mbase, mend;
   u64 candidate = 0;

   for (u32 i = 0; i < mi->count; i++) {

      ma = mi->mem_areas + i;
      mbase = ma->base;
      mend = ma->base + ma->len;

      if (ma->type != MEM_USABLE)
         continue;

      if (ma->len < size)
         continue;

      if (mend - size >= (1ull << 32)) {

         if ((1ull << 32) - size >= mbase) {

            /*
             * This is, by definition, the highest possible addr in the 32-bit
             * address space. Since it belongs to this free mem area, it's the
             * ultimate candidate addr.
             */

            candidate = (1ull << 32) - size;
            break;
         }

         /*
          * The mem area goes beyond the 32-bit limit, but it cannot contain
          * a chunk of our size within the 32-bit limit.
          */
         continue;
      }

      /* If the end of this area is higher than the candidate, take it */
      if (mend - size > candidate)
         candidate = mend - size;
   }

   return (ulong)candidate;
}


text:
<?php

/**
 * @file
 * Contains \Drupal\image\Tests\ImageItemTest.
 */

namespace Drupal\image\Tests;

use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\field\Tests\FieldUnitTestBase;

/**
 * Tests using entity fields of the image field type.
 *
 * @group image
 */
class ImageItemTest extends FieldUnitTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('file', 'image');

  /**
   * Created file entity.
   *
   * @var \Drupal\file\Entity\File
   */
  protected $image;

  /**
   * @var \Drupal\Core\Image\ImageFactory
   */
  protected $imageFactory;

  protected function setUp() {
    parent::setUp();

    $this->installEntitySchema('file');
    $this->installSchema('file', array('file_usage'));

    entity_create('field_storage_config', array(
      'entity_type' => 'entity_test',
      'field_name' => 'image_test',
      'type' => 'image',
      'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
    ))->save();
    entity_create('field_config', array(
      'entity_type' => 'entity_test',
      'field_name' => 'image_test',
      'bundle' => 'entity_test',
    ))->save();
    file_unmanaged_copy(\Drupal::root() . '/core/misc/druplicon.png', 'public://example.jpg');
    $this->image = entity_create('file', array(
      'uri' => 'public://example.jpg',
    ));
    $this->image->save();
    $this->imageFactory = $this->container->get('image.factory');
  }

  /**
   * Tests using entity fields of the image field type.
   */
  public function testImageItem() {
    // Create a test entity with the image field set.
    $entity = entity_create('entity_test');
    $entity->image_test->target_id = $this->image->id();
    $entity->image_test->alt = $alt = $this->randomMachineName();
    $entity->image_test->title = $title = $this->randomMachineName();
    $entity->name->value = $this->randomMachineName();
    $entity->save();

    $entity = entity_load('entity_test', $entity->id());
    $this->assertTrue($entity->image_test instanceof FieldItemListInterface, 'Field implements interface.');
    $this->assertTrue($entity->image_test[0] instanceof FieldItemInterface, 'Field item implements interface.');
    $this->assertEqual($entity->image_test->target_id, $this->image->id());
    $this->assertEqual($entity->image_test->alt, $alt);
    $this->assertEqual($entity->image_test->title, $title);
    $image = $this->imageFactory->get('public://example.jpg');
    $this->assertEqual($entity->image_test->width, $image->getWidth());
    $this->assertEqual($entity->image_test->height, $image->getHeight());
    $this->assertEqual($entity->image_test->entity->id(), $this->image->id());
    $this->assertEqual($entity->image_test->entity->uuid(), $this->image->uuid());

    // Make sure the computed entity reflects updates to the referenced file.
    file_unmanaged_copy(\Drupal::root() . '/core/misc/druplicon.png', 'public://example-2.jpg');
    $image2 = entity_create('file', array(
      'uri' => 'public://example-2.jpg',
    ));
    $image2->save();

    $entity->image_test->target_id = $image2->id();
    $entity->image_test->alt = $new_alt = $this->randomMachineName();
    // The width and height is only updated when width is not set.
    $entity->image_test->width = NULL;
    $entity->save();
    $this->assertEqual($entity->image_test->entity->id(), $image2->id());
    $this->assertEqual($entity->image_test->entity->getFileUri(), $image2->getFileUri());
    $image = $this->imageFactory->get('public://example-2.jpg');
    $this->assertEqual($entity->image_test->width, $image->getWidth());
    $this->assertEqual($entity->image_test->height, $image->getHeight());
    $this->assertEqual($entity->image_test->alt, $new_alt);

    // Check that the image item can be set to the referenced file directly.
    $entity->image_test = $this->image;
    $this->assertEqual($entity->image_test->target_id, $this->image->id());

    // Delete the image and try to save the entity again.
    $this->image->delete();
    $entity = entity_create('entity_test', array('mame' => $this->randomMachineName()));
    $entity->save();

    // Test image item properties.
    $expected = array('target_id', 'entity', 'alt', 'title', 'width', 'height');
    $properties = $entity->getFieldDefinition('image_test')->getFieldStorageDefinition()->getPropertyDefinitions();
    $this->assertEqual(array_keys($properties), $expected);

    // Test the generateSampleValue() method.
    $entity = entity_create('entity_test');
    $entity->image_test->generateSampleItems();
    $this->entityValidateAndSave($entity);
  }

}


text:
/***************************************************************************/
/*                                                                         */
/*  pshmod.h                                                               */
/*                                                                         */
/*    PostScript hinter module interface (specification).                  */
/*                                                                         */
/*  Copyright 2001 by                                                      */
/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
/*                                                                         */
/*  This file is part of the FreeType project, and may only be used,       */
/*  modified, and distributed under the terms of the FreeType project      */
/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
/*  this file you indicate that you have read the license and              */
/*  understand and accept it fully.                                        */
/*                                                                         */
/***************************************************************************/

#ifndef __PSHMOD_H__
#define __PSHMOD_H__

#include <ft2build.h>
#include FT_MODULE_H

FT_BEGIN_HEADER

  FT_EXPORT_VAR( const FT_Module_Class )  pshinter_module_class;

FT_END_HEADER

#endif /* __PSHMOD_H__ */

/* END */


text:
package com.nms.vnm.eip.service.entity;

import com.nms.vnm.eip.entity.Category;
import com.nms.vnm.eip.entity.Product;
import com.nms.vnm.eip.service.MobileChecker;
import java.util.List;

public interface ProductService<E extends Product, C extends Category> extends BaseService<E> {

 public List<E> findByCat(int start, int range, C category, String orderField, boolean asc);

 public List<E> findExcludeCurrent(int start, int range, E product, MobileChecker mobileChecker);

 public List<E> getPromotions(int start, int range, C category, String orderField, boolean asc);

 public List<E> getFrees(int start, int range, C category, String orderField, boolean asc);

 public List<E> getNoFrees(int start, int range, C category, String orderField, boolean asc);

 public int countPromotions(C category);

 public int countFrees(C category);

 public int countByCat(C category);

 public void increaseViewCount(E product);

 public void increateDownloadCount(E product);

 public List<E> search(String keywords, C category, MobileChecker mobileChecker,
         String orderField, boolean asc, int start, int ranger);

 public int count(String keywords, C category, MobileChecker mobileChecker);
}


text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: android.test.IsolatedContext
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ANDROID_TEST_ISOLATEDCONTEXT_HPP_DECL
#define J2CPP_ANDROID_TEST_ISOLATEDCONTEXT_HPP_DECL

namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace util { class List; } } }
namespace j2cpp { namespace java { namespace io { class File; } } }
namespace j2cpp { namespace android { namespace content { class ServiceConnection; } } }
namespace j2cpp { namespace android { namespace content { class IntentFilter; } } }
namespace j2cpp { namespace android { namespace content { class Intent; } } }
namespace j2cpp { namespace android { namespace content { class BroadcastReceiver; } } }
namespace j2cpp { namespace android { namespace content { class ContentResolver; } } }
namespace j2cpp { namespace android { namespace content { class Context; } } }
namespace j2cpp { namespace android { namespace content { class ContextWrapper; } } }
namespace j2cpp { namespace android { namespace net { class Uri; } } }

#include <android/content/BroadcastReceiver.hpp>
#include <android/content/ContentResolver.hpp>
#include <android/content/Context.hpp>
#include <android/content/ContextWrapper.hpp>
#include <android/content/Intent.hpp>
#include <android/content/IntentFilter.hpp>
#include <android/content/ServiceConnection.hpp>
#include <android/net/Uri.hpp>
#include <java/io/File.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
#include <java/util/List.hpp>

namespace j2cpp {

namespace android { namespace test {

	class IsolatedContext;
	class IsolatedContext
		: public object<IsolatedContext>
	{
	public:

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)
		J2CPP_DECLARE_METHOD(1)
		J2CPP_DECLARE_METHOD(2)
		J2CPP_DECLARE_METHOD(3)
		J2CPP_DECLARE_METHOD(4)
		J2CPP_DECLARE_METHOD(5)
		J2CPP_DECLARE_METHOD(6)
		J2CPP_DECLARE_METHOD(7)
		J2CPP_DECLARE_METHOD(8)
		J2CPP_DECLARE_METHOD(9)
		J2CPP_DECLARE_METHOD(10)

		explicit IsolatedContext(jobject jobj)
		: object<IsolatedContext>(jobj)
		{
		}

		operator local_ref<java::lang::Object>() const;
		operator local_ref<android::content::Context>() const;
		operator local_ref<android::content::ContextWrapper>() const;

		IsolatedContext(local_ref< android::content::ContentResolver > const&, local_ref< android::content::Context > const&);
		local_ref< java::util::List > getAndClearBroadcastIntents();
		local_ref< android::content::ContentResolver > getContentResolver();
		jboolean bindService(local_ref< android::content::Intent >  const&, local_ref< android::content::ServiceConnection >  const&, jint);
		local_ref< android::content::Intent > registerReceiver(local_ref< android::content::BroadcastReceiver >  const&, local_ref< android::content::IntentFilter >  const&);
		void sendBroadcast(local_ref< android::content::Intent >  const&);
		void sendOrderedBroadcast(local_ref< android::content::Intent >  const&, local_ref< java::lang::String >  const&);
		jint checkUriPermission(local_ref< android::net::Uri >  const&, local_ref< java::lang::String >  const&, local_ref< java::lang::String >  const&, jint, jint, jint);
		jint checkUriPermission(local_ref< android::net::Uri >  const&, jint, jint, jint);
		local_ref< java::lang::Object > getSystemService(local_ref< java::lang::String >  const&);
		local_ref< java::io::File > getFilesDir();
	}; //class IsolatedContext

} //namespace test
} //namespace android

} //namespace j2cpp

#endif //J2CPP_ANDROID_TEST_ISOLATEDCONTEXT_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ANDROID_TEST_ISOLATEDCONTEXT_HPP_IMPL
#define J2CPP_ANDROID_TEST_ISOLATEDCONTEXT_HPP_IMPL

namespace j2cpp {

android::test::IsolatedContext::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

android::test::IsolatedContext::operator local_ref<android::content::Context>() const
{
	return local_ref<android::content::Context>(get_jobject());
}

android::test::IsolatedContext::operator local_ref<android::content::ContextWrapper>() const
{
	return local_ref<android::content::ContextWrapper>(get_jobject());
}

android::test::IsolatedContext::IsolatedContext(local_ref< android::content::ContentResolver > const &a0, local_ref< android::content::Context > const &a1)
: object<android::test::IsolatedContext>(
	call_new_object<
		android::test::IsolatedContext::J2CPP_CLASS_NAME,
		android::test::IsolatedContext::J2CPP_METHOD_NAME(0),
		android::test::IsolatedContext::J2CPP_METHOD_SIGNATURE(0)
	>(a0, a1)
)
{
}

local_ref< java::util::List > android::test::IsolatedContext::getAndClearBroadcastIntents()
{
	return call_method<
		android::test::IsolatedContext::J2CPP_CLASS_NAME,
		android::test::IsolatedContext::J2CPP_METHOD_NAME(1),
		android::test::IsolatedContext::J2CPP_METHOD_SIGNATURE(1),
		local_ref< java::util::List >
	>(get_jobject());
}

local_ref< android::content::ContentResolver > android::test::IsolatedContext::getContentResolver()
{
	return call_method<
		android::test::IsolatedContext::J2CPP_CLASS_NAME,
		android::test::IsolatedContext::J2CPP_METHOD_NAME(2),
		android::test::IsolatedContext::J2CPP_METHOD_SIGNATURE(2),
		local_ref< android::content::ContentResolver >
	>(get_jobject());
}

jboolean android::test::IsolatedContext::bindService(local_ref< android::content::Intent > const &a0, local_ref< android::content::ServiceConnection > const &a1, jint a2)
{
	return call_method<
		android::test::IsolatedContext::J2CPP_CLASS_NAME,
		android::test::IsolatedContext::J2CPP_METHOD_NAME(3),
		android::test::IsolatedContext::J2CPP_METHOD_SIGNATURE(3),
		jboolean
	>(get_jobject(), a0, a1, a2);
}

local_ref< android::content::Intent > android::test::IsolatedContext::registerReceiver(local_ref< android::content::BroadcastReceiver > const &a0, local_ref< android::content::IntentFilter > const &a1)
{
	return call_method<
		android::test::IsolatedContext::J2CPP_CLASS_NAME,
		android::test::IsolatedContext::J2CPP_METHOD_NAME(4),
		android::test::IsolatedContext::J2CPP_METHOD_SIGNATURE(4),
		local_ref< android::content::Intent >
	>(get_jobject(), a0, a1);
}

void android::test::IsolatedContext::sendBroadcast(local_ref< android::content::Intent > const &a0)
{
	return call_method<
		android::test::IsolatedContext::J2CPP_CLASS_NAME,
		android::test::IsolatedContext::J2CPP_METHOD_NAME(5),
		android::test::IsolatedContext::J2CPP_METHOD_SIGNATURE(5),
		void
	>(get_jobject(), a0);
}

void android::test::IsolatedContext::sendOrderedBroadcast(local_ref< android::content::Intent > const &a0, local_ref< java::lang::String > const &a1)
{
	return call_method<
		android::test::IsolatedContext::J2CPP_CLASS_NAME,
		android::test::IsolatedContext::J2CPP_METHOD_NAME(6),
		android::test::IsolatedContext::J2CPP_METHOD_SIGNATURE(6),
		void
	>(get_jobject(), a0, a1);
}

jint android::test::IsolatedContext::checkUriPermission(local_ref< android::net::Uri > const &a0, local_ref< java::lang::String > const &a1, local_ref< java::lang::String > const &a2, jint a3, jint a4, jint a5)
{
	return call_method<
		android::test::IsolatedContext::J2CPP_CLASS_NAME,
		android::test::IsolatedContext::J2CPP_METHOD_NAME(7),
		android::test::IsolatedContext::J2CPP_METHOD_SIGNATURE(7),
		jint
	>(get_jobject(), a0, a1, a2, a3, a4, a5);
}

jint android::test::IsolatedContext::checkUriPermission(local_ref< android::net::Uri > const &a0, jint a1, jint a2, jint a3)
{
	return call_method<
		android::test::IsolatedContext::J2CPP_CLASS_NAME,
		android::test::IsolatedContext::J2CPP_METHOD_NAME(8),
		android::test::IsolatedContext::J2CPP_METHOD_SIGNATURE(8),
		jint
	>(get_jobject(), a0, a1, a2, a3);
}

local_ref< java::lang::Object > android::test::IsolatedContext::getSystemService(local_ref< java::lang::String > const &a0)
{
	return call_method<
		android::test::IsolatedContext::J2CPP_CLASS_NAME,
		android::test::IsolatedContext::J2CPP_METHOD_NAME(9),
		android::test::IsolatedContext::J2CPP_METHOD_SIGNATURE(9),
		local_ref< java::lang::Object >
	>(get_jobject(), a0);
}

local_ref< java::io::File > android::test::IsolatedContext::getFilesDir()
{
	return call_method<
		android::test::IsolatedContext::J2CPP_CLASS_NAME,
		android::test::IsolatedContext::J2CPP_METHOD_NAME(10),
		android::test::IsolatedContext::J2CPP_METHOD_SIGNATURE(10),
		local_ref< java::io::File >
	>(get_jobject());
}

J2CPP_DEFINE_CLASS(android::test::IsolatedContext,"android/test/IsolatedContext")
J2CPP_DEFINE_METHOD(android::test::IsolatedContext,0,"<init>","(Landroid/content/ContentResolver;Landroid/content/Context;)V")
J2CPP_DEFINE_METHOD(android::test::IsolatedContext,1,"getAndClearBroadcastIntents","()Ljava/util/List;")
J2CPP_DEFINE_METHOD(android::test::IsolatedContext,2,"getContentResolver","()Landroid/content/ContentResolver;")
J2CPP_DEFINE_METHOD(android::test::IsolatedContext,3,"bindService","(Landroid/content/Intent;Landroid/content/ServiceConnection;I)Z")
J2CPP_DEFINE_METHOD(android::test::IsolatedContext,4,"registerReceiver","(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;")
J2CPP_DEFINE_METHOD(android::test::IsolatedContext,5,"sendBroadcast","(Landroid/content/Intent;)V")
J2CPP_DEFINE_METHOD(android::test::IsolatedContext,6,"sendOrderedBroadcast","(Landroid/content/Intent;Ljava/lang/String;)V")
J2CPP_DEFINE_METHOD(android::test::IsolatedContext,7,"checkUriPermission","(Landroid/net/Uri;Ljava/lang/String;Ljava/lang/String;III)I")
J2CPP_DEFINE_METHOD(android::test::IsolatedContext,8,"checkUriPermission","(Landroid/net/Uri;III)I")
J2CPP_DEFINE_METHOD(android::test::IsolatedContext,9,"getSystemService","(Ljava/lang/String;)Ljava/lang/Object;")
J2CPP_DEFINE_METHOD(android::test::IsolatedContext,10,"getFilesDir","()Ljava/io/File;")

} //namespace j2cpp

#endif //J2CPP_ANDROID_TEST_ISOLATEDCONTEXT_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION


text:
////////////////////////////////////////////////////////////////////////////////
//
//  TYPHOON FRAMEWORK
//  Copyright 2013, Typhoon Framework Contributors
//  All Rights Reserved.
//
//  NOTICE: The authors permit you to use, modify, and distribute this file
//  in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////

#import <objc/runtime.h>
#import <objc/message.h>
#import "TyphoonIntrospectionUtils.h"
#import "TyphoonTypeDescriptor.h"

@implementation TyphoonIntrospectionUtils

+ (TyphoonTypeDescriptor *)typeForPropertyNamed:(NSString *)propertyName inClass:(Class)clazz
{
    TyphoonTypeDescriptor *typeDescriptor = nil;
    objc_property_t propertyReflection = class_getProperty(clazz, [propertyName cStringUsingEncoding:NSASCIIStringEncoding]);
    if (propertyReflection) {
        const char *attributes = property_getAttributes(propertyReflection);

        if (attributes == NULL) {
            return (NULL);
        }

        static char buffer[256];
        const char *e = strchr(attributes, ',');
        if (e == NULL) {
            return (NULL);
        }

        int len = (int) (e - attributes);
        memcpy( buffer, attributes, len );
        buffer[len] = '\0';

        NSString *typeCode = [NSString stringWithCString:buffer encoding:NSASCIIStringEncoding];
        typeDescriptor = [TyphoonTypeDescriptor descriptorWithTypeCode:typeCode];
    }
    return typeDescriptor;
}

+ (SEL)setterForPropertyWithName:(NSString *)propertyName inClass:(Class)clazz
{
    SEL setterSelector = nil;

    objc_property_t property = class_getProperty(clazz, [propertyName cStringUsingEncoding:NSASCIIStringEncoding]);
    if (property) {
        if (![self isReadonlyProperty:property]) {
            NSString *selectorString = [self customSetterForProperty:property];
            if (!selectorString) {
                selectorString = [self defaultSetterForPropertyWithName:propertyName];
            }
            setterSelector = NSSelectorFromString(selectorString);
        }
    }
    else if (propertyName.length > 0) {
        NSString *selectorString = [self defaultSetterForPropertyWithName:propertyName];
        SEL aSelector = NSSelectorFromString(selectorString);
        if (class_getInstanceMethod(clazz, aSelector)) {
            setterSelector = aSelector;
        }
    }

    return setterSelector;
}

+ (SEL)getterForPropertyWithName:(NSString *)propertyName inClass:(Class)clazz
{
    SEL getterSelector = nil;
    objc_property_t property = class_getProperty(clazz, [propertyName cStringUsingEncoding:NSASCIIStringEncoding]);
    if (property) {
        NSString *getterString = [self customGetterForProperty:property];
        if (!getterString) {
            getterString = [self defaultGetterForPropertyWithName:propertyName];
        }
        getterSelector = NSSelectorFromString(getterString);
    }
    return getterSelector;
}

+ (NSMethodSignature *)methodSignatureWithArgumentsAndReturnValueAsObjectsFromSelector:(SEL)selector
{
    NSUInteger argc = [self numberOfArgumentsInSelector:selector];
    NSMutableString *signatureString = [[NSMutableString alloc]
        initWithCapacity:argc + 3]; //one symbol per encoded type
    [signatureString appendFormat:@"%s%s%s", @encode(id), @encode(id), @encode(SEL)];
    for (NSUInteger i = 0; i < argc; i++) {
        [signatureString appendString:[NSString stringWithCString:@encode(id) encoding:NSASCIIStringEncoding]];
    }
    NSMethodSignature *signature = [NSMethodSignature signatureWithObjCTypes:[signatureString cStringUsingEncoding:NSASCIIStringEncoding]];

    return signature;
}

+ (NSUInteger)numberOfArgumentsInSelector:(SEL)selector
{
    NSString *string = NSStringFromSelector(selector);
    NSUInteger count = 0;
    for (NSUInteger i = 0; i < string.length; i++) {
        if ([string characterAtIndex:i] == ':') {
            count++;
        }
    }
    return count;
}

+ (NSSet *)propertiesForClass:(Class)clazz upToParentClass:(Class)parent
{
    NSMutableSet *propertyNames = [[NSMutableSet alloc] init];

    while (clazz && clazz != parent) {
        unsigned int count = 0;
        objc_property_t *properties = class_copyPropertyList(clazz, &count);

        for (unsigned int propertyIndex = 0; propertyIndex < count; propertyIndex++) {
            objc_property_t aProperty = properties[propertyIndex];
            NSString *propertyName = [NSString stringWithCString:property_getName(aProperty)
                encoding:NSUTF8StringEncoding];

            [propertyNames addObject:propertyName];
        }

        clazz = class_getSuperclass(clazz);

        free(properties);
    }

    return propertyNames;
}

+ (NSSet *)methodsForClass:(Class)clazz upToParentClass:(Class)parent
{
    NSMutableSet *methodSelectors = [[NSMutableSet alloc] init];

    while (clazz && clazz != parent) {
        unsigned int methodCount;
        Method *methodList = class_copyMethodList(clazz, &methodCount);
        for (unsigned int i = 0; i < methodCount; i++) {
            Method method = methodList[i];
            [methodSelectors addObject:NSStringFromSelector(method_getName(method))];
        }
        free(methodList);
        clazz = class_getSuperclass(clazz);
    }

    return methodSelectors;
}

#pragma mark - Property Attributes Utils

+ (NSString *)classNameOfProperty:(objc_property_t)property
{
    NSString *propertyAttributes = [NSString stringWithCString:property_getAttributes(property)
        encoding:NSUTF8StringEncoding];
    NSArray *splitPropertyAttributes = [propertyAttributes componentsSeparatedByString:@"\""];
    if (splitPropertyAttributes.count >= 2) {

        return [splitPropertyAttributes objectAtIndex:1];
    }

    return nil;
}

+ (BOOL)isReadonlyProperty:(objc_property_t)property
{
    char *readonlyFlag = property_copyAttributeValue(property, "R");
    BOOL isReadonly = readonlyFlag != NULL;
    free(readonlyFlag);
    return isReadonly;
}

+ (NSString *)customSetterForProperty:(objc_property_t)property
{
    NSString *customSetter = nil;

    char *setterName = property_copyAttributeValue(property, "S");

    if (setterName != NULL) {
        customSetter = [NSString stringWithCString:setterName encoding:NSASCIIStringEncoding];;
        free(setterName);
    }

    return customSetter;
}

+ (NSString *)customGetterForProperty:(objc_property_t)property
{
    NSString *customGetter = nil;

    char *getterName = property_copyAttributeValue(property, "G");

    if (getterName != NULL) {
        customGetter = [NSString stringWithCString:getterName encoding:NSASCIIStringEncoding];;
        free(getterName);
    }

    return customGetter;
}

+ (NSString *)defaultSetterForPropertyWithName:(NSString *)propertyName
{
    NSString *firstLetterUppercase = [[propertyName substringToIndex:1] uppercaseString];
    NSString *propertyPart = [propertyName stringByReplacingCharactersInRange:NSMakeRange(0, 1)
        withString:firstLetterUppercase];
    return [NSString stringWithFormat:@"set%@:", propertyPart];
}

+ (NSString *)defaultGetterForPropertyWithName:(NSString *)propertyName
{
    return propertyName;
}

@end

NSString *TyphoonTypeStringFor(id classOrProtocol)
{
    if (IsClass(classOrProtocol)) {
        return NSStringFromClass(classOrProtocol);
    }
    else {
        return [NSString stringWithFormat:@"id<%@>", NSStringFromProtocol(classOrProtocol)];
    }
}

Class TyphoonClassFromString(NSString *className)
{
    Class clazz = NSClassFromString(className);
    if (!clazz) {
        NSString *defaultModuleName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleExecutable"];
        defaultModuleName = [[defaultModuleName stringByReplacingOccurrencesOfString:@" " withString:@"_"]
                stringByReplacingOccurrencesOfString:@"-" withString:@"_"];
        clazz = NSClassFromString([defaultModuleName stringByAppendingFormat:@".%@", className]);
    }
    if (!clazz) {
        /**
        Swift issue:
        When calling property_getAttributes() for a Swift class that belongs in a different
        module, the module name is *NOT* returned, therefore attempting to resolve the
        Swift class via name wont work:

        1. Foo.BarAssembly in Foo.framework
        2. App.app includes Foo.framework and references Foo.BarAssembly in AppAssembly

        import Foo

        class AppAssembly: TyphonAssembly {

        var barAssembly: Foo.BarAssembly?
        }
        3. property_getAttributes() called on `barAssembly` returns @T"BarAssembly" but
        should return @T"Foo.BarAssembly"
        4. NSClassforString("BarAssembly") returns nil because the App.app does not define
        this class

        Poor workaround, not the best, but no other way around it unless Apple fixes the objc reflection of
        Swift classes there is no other way:

        If we are unable to find the class in the top level project iterate all dynamic
        frameworks and attempt to resolve the class name by appending the module name

        This is somewhat brittle as we loose the namespacing modules give us (for example,
        if 2 modules define the same class then which ever appears first in the list will
        be used which might not be expected). In order for this to work, developers are required
        to:
        - have unique names of assemblies across modules
        - frameworks bundle ids much match the following format: *.{Name} where Name is
        the name of the module

        */
        NSArray *frameworks = [NSBundle allFrameworks];
        for (uint i = 0; i < frameworks.count && clazz == nil; ++i) {
            NSBundle *framework = [frameworks objectAtIndex:i];
            NSString *bundleIdentifier = [framework bundleIdentifier];
            // ignore apple frameworks
            if (![bundleIdentifier hasPrefix:@"com.apple"]) {
                NSRange range = [bundleIdentifier rangeOfString:@"." options:NSBackwardsSearch];
                if (range.location != NSNotFound) {
                    NSString *frameworkName = [bundleIdentifier substringFromIndex:range.location + 1];
                    if (frameworkName != nil) {
                        clazz = NSClassFromString([frameworkName stringByAppendingFormat:@".%@", className]);
                    }
                }
            }
        }
    }
    return clazz;
}

BOOL IsClass(id classOrProtocol)
{
    return class_isMetaClass(object_getClass(classOrProtocol));
}

BOOL IsProtocol(id classOrProtocol)
{
    return object_getClass(classOrProtocol) == object_getClass(@protocol(NSObject));
}


text:
package org.elasticsearch.common.blobstore;

import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * The list of paths where a blob can reside.  The contents of the paths are dependent upon the implementation of {@link BlobContainer}.
 */
public class BlobPath {

    public static final BlobPath EMPTY = new BlobPath(Collections.emptyList());

    private static final String SEPARATOR = "/";

    private final List<String> paths;

    private BlobPath(List<String> paths) {
        this.paths = paths;
    }

    public List<String> parts() {
        return paths;
    }

    public BlobPath add(String path) {
        return new BlobPath(CollectionUtils.appendToCopy(this.paths, path));
    }

    public String buildAsString() {
        String p = String.join(SEPARATOR, paths);
        if (p.isEmpty() || p.endsWith(SEPARATOR)) {
            return p;
        }
        return p + SEPARATOR;
    }

    /**
     * Returns this path's parent path.
     *
     * @return Parent path or {@code null} if there is none
     */
    @Nullable
    public BlobPath parent() {
        int size = paths.size();
        switch (size) {
            case 0:
                return null;
            case 1:
                return EMPTY;
            default:
                return new BlobPath(List.copyOf(paths.subList(0, size - 1)));
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (String path : paths) {
            sb.append('[').append(path).append(']');
        }
        return sb.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        BlobPath other = (BlobPath) o;
        return paths.equals(other.paths);
    }

    @Override
    public int hashCode() {
        return Objects.hash(paths);
    }
}


text:
package com.github.imcharsi.vaadin.vaadinutil.converter

import java.text.NumberFormat
import java.util.Locale

import com.vaadin.data.util.converter.Converter.ConversionException

import scala.util.{Failure, Success, Try}

/**
 * Created by KangWoo,Lee on 14. 7. 29.
 */
object OptionIntConverter extends AbstractOptionStringConverter[Int] {
  override protected def innerConvertToModel(value: String, targetType: Class[_ <: Option[Int]], locale: Locale): Option[Int] = {
    Try(NumberFormat.getInstance().parse(value)).map(_.intValue()) match {
      case Success(x) ⇒ Some(x)
      case Failure(x) ⇒ throw new ConversionException(x)
    }
  }

  override protected def innerConvertToPresentation(value: Option[Int], targetType: Class[_ <: String], locale: Locale): String = {
    Try(value.map(x ⇒ NumberFormat.getInstance().format(x))) match {
      case Success(Some(x)) ⇒ x
      case Success(None) ⇒ null
      case Failure(x) ⇒ throw new ConversionException(x)
    }
  }
}


text:
package com.hubspot.jinjava.lib.tag;

import static org.assertj.core.api.Assertions.assertThat;

import com.google.common.collect.Maps;
import com.hubspot.jinjava.BaseInterpretingTest;
import com.hubspot.jinjava.interpret.RenderResult;
import com.hubspot.jinjava.interpret.TemplateError.ErrorReason;
import org.junit.Test;

public class DoTagTest extends BaseInterpretingTest {

  @Test
  public void itResolvesExpressions() {
    String template = "{% set output = [] %}{% do output.append('hey') %}{{ output }}";
    assertThat(jinjava.render(template, Maps.newHashMap())).isEqualTo("['hey']");
  }

  @Test
  public void itAddsTemplateErrorOnEmptyExpression() {
    String template = "{% do %}";
    RenderResult renderResult = jinjava.renderForResult(template, Maps.newHashMap());
    assertThat(renderResult.getErrors()).hasSize(1);
    assertThat(renderResult.getErrors().get(0).getReason())
      .isEqualTo(ErrorReason.SYNTAX_ERROR);
  }
}


text:
namespace UiMetadataFramework.Web.Metadata.ClientFunctions
{
	using System.Collections.Generic;
	using UiMetadataFramework.Core;
	using UiMetadataFramework.Core.Binding;

	public class GrowlNotification
	{
		public GrowlNotification(string message, string style) : this(null, message, style)
		{
			this.Message = message;
			this.Style = style;
		}

		public GrowlNotification(string heading, string message, string style)
		{
			this.Heading = heading;
			this.Message = message;
			this.Style = style;
		}

		public string Heading { get; set; }
		public string Message { get; set; }
		public string Style { get; set; }

		public ClientFunctionMetadata GetClientFunctionMetadata()
		{
			var customProperties = new Dictionary<string, object>()
				.Set(nameof(this.Heading), this.Heading)
				.Set(nameof(this.Message), this.Heading)
				.Set(nameof(this.Style), this.Style);

			return new ClientFunctionMetadata("growl", customProperties);
		}

		public static class Styles
		{
			public const string Success = "success";
			public const string Warning = "warning";
			public const string Danger = "danger";
		}
	}
}


text:
require_relative '../../../helpers/application_helper'
module Api
  module V1
    class UsersController < ApplicationController

      include ApplicationHelper
      def index
        @users = User.all
        render json: @users
      end

      def via_facebook_token
        #grab authenticated user access token
        access_token = params['access-token']

        # make request to facebook api
        uri = URI("https://graph.facebook.com/v2.6/me?access_token=#{access_token}&fields=name%2Cemail%2Cid&format=json&method=get&pretty=0&suppress_http_code=1")

        user_json = Net::HTTP.get_response(uri).body

        hash = JSON.parse(user_json)

        #format data for user creation
        clean_user_data(hash)

        @user = User.new(hash)

        if @user.save
          render json: @user
        else
          render json: {errors: @user.errors}
        end

      end

      def create
        @user = User.new(user_params)

        if @user.save
          render json: @user, status: 201
        else
          render json: {errors:@user.errors}, status: 422
        end
      end

      private
        def user_params
          params.require(:user).permit(:name, :email)
        end

    end
  end
end


text:
#ifndef AOM_DSP_BITWRITER_BUFFER_H_
#define AOM_DSP_BITWRITER_BUFFER_H_

#include "aom/aom_integer.h"

#ifdef __cplusplus
extern "C" {
#endif

struct aom_write_bit_buffer {
  uint8_t *bit_buffer;
  size_t bit_offset;
};

size_t aom_wb_bytes_written(const struct aom_write_bit_buffer *wb);

void aom_wb_write_bit(struct aom_write_bit_buffer *wb, int bit);

void aom_wb_overwrite_bit(struct aom_write_bit_buffer *wb, int bit);

void aom_wb_write_literal(struct aom_write_bit_buffer *wb, int data, int bits);

void aom_wb_overwrite_literal(struct aom_write_bit_buffer *wb, int data,
                              int bits);

void aom_wb_write_inv_signed_literal(struct aom_write_bit_buffer *wb, int data,
                                     int bits);

#ifdef __cplusplus
}  // extern "C"
#endif

#endif  // AOM_DSP_BITWRITER_BUFFER_H_


text:
<?php
// © 2017 Rob Schlüter. For licensing details see the LICENSE file.
use kwebble\wiki\Page;
use kwebble\wiki\PageGenerationStage;

/**
 * A command that outputs the name of the current page.
 */
class PagenameCommand implements \kwebble\wiki\Command {

    /**
     * Returns the page name.
     */
    function run(Page $page, string $options, string $before, string $after): string {
        return $before . $page->getTitle() . $after;
    }

    function runAt(): PageGenerationStage {
        return PageGenerationStage::DURING();
    }

}


text:
import { Component, OnInit } from '@angular/core';
import { GroupService } from '../shared/services/group.service';
import { ToastrService } from 'ngx-toastr';
import { Router, ActivatedRoute} from '@angular/router';

@Component({
  templateUrl: './score.component.detail.html',
  styleUrls: ['./score.component.scss']
})
export class ScoreDetailComponent implements OnInit {
  private groupData = [];
  private token: string = '';
  // trigger-variable for Ladda
  isLoading = false;
  private pathToCopy: string;
  constructor(
    private groupService: GroupService,
    private router: Router,
    private toastr: ToastrService,
    private route: ActivatedRoute
  ) {
    let pathToCo = window.location.href;
    this.pathToCopy = pathToCo.substring(0, pathToCo.lastIndexOf("/success"))
  }

  getInitials(name) {
    if (name) {
      let initials = name.match(/\b\w/g) || [];
      initials = ((initials.shift() || '') + (initials.pop() || '')).toUpperCase();
      return initials;
    }
    return '';
  }

  ngOnInit() {
    this.token = this.route.snapshot.params['token'];
    this.groupService.getGroupDetailsForScore(this.token)
      .subscribe(data => {
        this.groupData = data;
        console.log(this.groupData)
      }, err => {
        this.toastr.error(err, 'Error');
        this.router.navigate(['/']);
        console.log(err)
      })
  }
}


text:
<?php
//// <%=field.type%> <%=field.key%> ////
$link<%=field.key%> = $<%=field.key%> ? $this->controller->getPageLink($<%=field.key%>) : array();
Loader::packageElement('link','sb_links', array('link' => $link<%=field.key%>));
?>


text:
<?php

/* bundlePPEMission2BootstrapBundle:Default:login.html.twig */
class __TwigTemplate_2e002ce537a4b03453da51e36c08f0ea extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("bundlePPEMission2BootstrapBundle:Default:base.html.twig");

        $this->blocks = array(
            'corps' => array($this, 'block_corps'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "bundlePPEMission2BootstrapBundle:Default:base.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 2
    public function block_corps($context, array $blocks = array())
    {
        // line 3
        echo "

<form action=\"\" method=\"post\">
";
        // line 6
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'widget');
        echo "

</form>
env->getExtension('routing')->getPath("bundle_ppe_mission2_bootstrap_creation", array());
        echo "\">Créer un compte

";
    }

    public function getTemplateName()
    {
        return "bundlePPEMission2BootstrapBundle:Default:login.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  42 => 9,  36 => 6,  31 => 3,  28 => 2,);
    }
}


text:
PlayerNSD v0.0.1
================

Introduction
------------

This is a player network simulator daemon that works in conjunction with nsdnet,
which allows messages to be sent between robots in [Player][1] and supports
the use of network simulation scripts and external simulators such as [ns3][2].
Please see COPYING for license information.

 [1]: http://playerstage.sourceforge.net/index.php?src=player
 [2]: http://www.nsnam.org/

Dependencies
------------

* [Python][4] (tested with python 2.5 and python 2.7)
* [Player][1] (tested with 3.0.2)
* [CMake][2] (tested with 2.8.1)
* [Doxygen][5] (for building documentation)

 [3]: http://www.cmake.org/
 [4]: http://www.python.org/
 [5]: http://www.stack.nl/~dimitri/doxygen/

### Optional

* [NSSim][6]

 [6]: http://github.com/raedwulf/nssim

Running
-------

This daemon can be run by using the wrapper playernsd script:

	$ ./playernsd

More options can be found by executing:

	$ ./playernsd --help

For example, to run an example wifi simulator using NS3 as a backend,
with verbose logging:

	$ ./playernsd -o "verbose=true" ../nssim/build/wifisim

Or for a simple script, that provides line of sight communication (for use
with Stage maps):

	$ ./playernsd -o image=pathto/cave.png,width=25,height=25 -v examples/lineofsight.py

These paths assume you are running directly from the repository.


text:
BlazeComponent.extendComponent({
  template: function() {
    return 'listHeader';
  },

  editTitle: function(evt) {
    evt.preventDefault();
    var form = this.componentChildren('inlinedForm')[0];
    var newTitle = form.getValue();
    if ($.trim(newTitle)) {
      Lists.update(this.currentData()._id, {
        $set: {
          title: newTitle
        }
      });
    }
  },

  events: function() {
    return [{
      'click .js-open-list-menu': Popup.open('listAction'),
      submit: this.editTitle
    }];
  }
}).register('listHeader');


text:
package backend

import bolt "go.etcd.io/bbolt"

var boltOpenOptions *bolt.Options = nil

// setting mmap size != 0 on windows will allocate the entire
// mmap size for the file, instead of growing it. So, force 0.

func (bcfg *BackendConfig) mmapSize() int { return 0 }


text:
// from http://stackoverflow.com/questions/5515869/string-length-in-bytes-in-javascript
// using UTF8 strings I noticed that the javascript .length of a string returned less
// characters than they actually were
var pendingSendMessages = [];
var ws = null;
var comTimeout = null;
var failedConnections = 0;

function byteLength(str) {
  // returns the byte length of an utf8 string
  var s = str.length;
  for (var i=str.length-1; i>=0; i--) {
    var code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s+=2;
    if (code >= 0xDC00 && code <= 0xDFFF) i--; //trail surrogate
  }
  return s;
}

var paramPacketize = function (ps){
    var ret = '';
    for (var pkey in ps) {
        if( ret.length>0 )ret = ret + '|';
        var pstring = pkey+'='+ps[pkey];
        var pstring_length = byteLength(pstring);
        pstring = pstring_length+'|'+pstring;
        ret = ret + pstring;
    }
    return ret;
};

function openSocket(){
    try{
        ws = new WebSocket('ws://'+net_interface_ip+':'+wsport+'/');
        console.debug('opening websocket');
        ws.onopen = websocketOnOpen;
        ws.onmessage = websocketOnMessage;
        ws.onclose = websocketOnClose;
        ws.onerror = websocketOnError;
    }catch(ex){ws=false;alert('websocketnot supported or server unreachable');}
}

openSocket();

function websocketOnMessage (evt){
    var received_msg = evt.data;
    /*console.debug('Message is received:' + received_msg);*/
    var s = received_msg.split(',');
    var command = s[0];
    var index = received_msg.indexOf(',')+1;
    received_msg = received_msg.substr(index,received_msg.length-index);/*removing the command from the message*/
    index = received_msg.indexOf(',')+1;
    var content = received_msg.substr(index,received_msg.length-index);

    /*console.debug('content:' + content);*/

    if( command=='show_window' ){
        document.body.innerHTML = '

';
        document.body.innerHTML += decodeURIComponent(content);
    }else if( command=='update_widget'){
        var elem = document.getElementById(s[1]);
        var index = received_msg.indexOf(',')+1;
        elem.insertAdjacentHTML('afterend',decodeURIComponent(content));
        elem.parentElement.removeChild(elem);
    }else if( command=='insert_widget'){
        if( document.getElementById(s[1])==null ){
            /*the content contains an additional field that we have to remove*/
            index = content.indexOf(',')+1;
            content = content.substr(index,content.length-index);
            var elem = document.getElementById(s[2]);
            elem.innerHTML = elem.innerHTML + decodeURIComponent(content);
        }
    }else if( command=='javascript'){
        try{
            console.debug("executing js code: " + received_msg);
            eval(received_msg);
        }catch(e){console.debug(e.message);};
    }else if( command=='ack'){
        pendingSendMessages.shift() /*remove the oldest*/
        if(comTimeout!=null)clearTimeout(comTimeout);
    }else if( command=='ping'){
        ws.send('pong');
    }else{
        //console.debug(">>>>UNKNOWN MESSAGE TYPE: " + decodeURIComponent(received_msg));
    }
};

/*this uses websockets*/
var sendCallbackParam = function (widgetID,functionName,params /*a dictionary of name:value*/){
    var paramStr = '';
    if(params!=null) paramStr=paramPacketize(params);
    var message = encodeURIComponent(unescape('callback' + '/' + widgetID+'/'+functionName + '/' + paramStr));
    console.debug(message.length);
    //console.debug(message);
    pendingSendMessages.push(message);
    if( pendingSendMessages.length < pending_messages_queue_length ){
        ws.send(message);
        if(comTimeout==null)
            comTimeout = setTimeout(checkTimeout, websocket_timeout_timer_ms);
    }else{
        console.debug('Renewing connection, ws.readyState when trying to send was: ' + ws.readyState)
        renewConnection();
    }
};

/*this uses websockets*/
var sendCallback = function (widgetID,functionName){
    sendCallbackParam(widgetID,functionName,null);
};

function renewConnection(){
    // ws.readyState:
    //A value of 0 indicates that the connection has not yet been established.
    //A value of 1 indicates that the connection is established and communication is possible.
    //A value of 2 indicates that the connection is going through the closing handshake.
    //A value of 3 indicates that the connection has been closed or could not be opened.
    if( ws.readyState == 1){
        try{
            ws.close();
        }catch(err){};
    }
    else if(ws.readyState == 0){
     // Don't do anything, just wait for the connection to be stablished
    }
    else{
        openSocket();
    }
};

function checkTimeout(){
    if(pendingSendMessages.length>0)
        renewConnection();
};

function websocketOnClose(evt){
    /* websocket is closed. */
    console.debug('Connection is closed... event code: ' + evt.code + ', reason: ' + evt.reason);
    // Some explanation on this error: http://stackoverflow.com/questions/19304157/getting-the-reason-why-websockets-closed
    // In practice, on a unstable network (wifi with a lot of traffic for example) this error appears
    // Got it with Chrome saying:
    // WebSocket connection to 'ws://x.x.x.x:y/' failed: Could not decode a text frame as UTF-8.
    // WebSocket connection to 'ws://x.x.x.x:y/' failed: Invalid frame header

    try {
        document.getElementById("loading").style.display = '';
    } catch(err) {
        console.log('Error hiding loading overlay ' + err.message);
    }

    failedConnections += 1;

    console.debug('failed connections=' + failedConnections + ' queued messages=' + pendingSendMessages.length);

    if(failedConnections > 3) {

        // check if the server has been restarted - which would give it a new websocket address,
        // new state, and require a reload
        console.debug('Checking if GUI still up ' + location.href);

        var http = new XMLHttpRequest();
        http.open('HEAD', location.href);
        http.onreadystatechange = function() {
            if (http.status == 200) {
                // server is up but has a new websocket address, reload
                location.reload();
            }
        };
        http.send();

        failedConnections = 0;
    }

    if(evt.code == 1006){
        renewConnection();
    }

};

function websocketOnError(evt){
    /* websocket is closed. */
    /* alert('Websocket error...');*/
    console.debug('Websocket error... event code: ' + evt.code + ', reason: ' + evt.reason);
};

function websocketOnOpen(evt){
    if(ws.readyState == 1){
        ws.send('connected');

        try {
            document.getElementById("loading").style.display = 'none';
        } catch(err) {
            console.log('Error hiding loading overlay ' + err.message);
        }

        failedConnections = 0;

        while(pendingSendMessages.length>0){
            ws.send(pendingSendMessages.shift()); /*whithout checking ack*/
        }
    }
    else{
        console.debug('onopen fired but the socket readyState was not 1');
    }
};

function uploadFile(widgetID, eventSuccess, eventFail, eventData, file){
    var reader = new FileReader();
	reader.onloadend = function(evt) {
        if (evt.target.readyState == FileReader.DONE) {
            var params={};
            params['file_name']=file.name;
            //params['file_data']=String.fromCharCode.apply(null, new Uint8Array(evt.target.result));
            params['file_data']=evt.target.result;
            sendCallbackParam(widgetID, eventData, params);
		}
	};

    //reader.readAsArrayBuffer(file.slice(0,file.size)); //readAsDataURL //readAsText //readAsBinaryString //readAsArrayBuffer
    reader.readAsText(file.slice(0,file.size), 'utf8');//'latin-1');//'ISO-8859-4');
}


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

public class GroundsBehaviour : MonoBehaviour
{
	public Material _Ground;
	public float _Speed;

	void Start ()
	{

	}

	// Update is called once per frame
	void LateUpdate ()
	{
		_Ground.mainTextureOffset += new Vector2(_Speed * Time.deltaTime, 0);
		if(_Ground.mainTextureOffset.x >= 18.0f)
			_Ground.mainTextureOffset = new Vector2(0, 0);
	}
}


text:
<?php namespace Anomaly\AddonsModule\Composer\Command;

use Anomaly\AddonsModule\Composer\ComposerAuthorizer;

class GetComposerAuthorization
{

    /**
     * The target type.
     *
     * @var string
     */
    protected $type;

    /**
     * The target command.
     *
     * @var string
     */
    protected $command;

    /**
     * Create a new GetComposerAuthorization instance.
     *
     * @param string $command
     * @param string $type
     */
    public function __construct($command, $type)
    {
        $this->type    = $type;
        $this->command = $command;
    }

    /**
     * Handle the command.
     *
     * @param ComposerAuthorizer $authorizer
     * @return bool
     */
    public function handle(ComposerAuthorizer $authorizer)
    {
        return $authorizer->authorize($this->command, $this->type);
    }
}