text:
Globalization Pipeline API
==========================

- back to [README.md](README.md)

API convention
==

Most APIs will return a promise. APIs that return a promise are either identified as `async`
or have the optional callback (`cb`) parameter. These APIs can be used using `async/await`
or else with `.then(…)`

```javascript
    await gpClient.ping();
```

```javascript
    gpClient.ping( { /* opts */ })
    .then( result => /* do something with result */)
    .catch( err => /* do something with err */ );
```

* opts: an object containing input parameters, if needed.

### Callback mode (deprecated)

Prior to v2.0, only the callback model was supported. This is still supported
for some APIs, but is deprecated.

```javascript
    gpClient.function( { /*opts*/ } ,  function callback(err, result))
```

* opts: an object containing input parameters, if needed.
* callback: a callback with:
    - `err`: if truthy, indicates an error has occured.
    - `result`: the operation's result

Sometimes the `opts` object is optional. If this is the case, the
API doc will indicate it with this notation:  `[opts]`
For example,  `bundle.getInfo(cb)` and `bundle.getInfo({}, cb)`  are equivalent.

### Naming

Also, note that there are aliases from the swagger doc function names
to the convenience name. For example, `bundle.uploadResourceStrings` can be
used in place of `bundle.uploadStrings`.

All language identifiers are [IETF BCP47](http://tools.ietf.org/html/bcp47) codes.

API reference
===

## Classes

Bundle

Accessor object for a Globalization Pipeline bundle

Client

Client object for Globalization Pipeline

DocumentTranslationRequest

Document Translation Request.

Cli

Command line interface to the Globalization Pipeline.
Example usage:

const Cli = require('g11n-pipeline/lib/gpcli');
new Cli(Cli.parseArgs(process.argv)).run().then(…);

HTMLDocument

HTML Document

MarkdownDocument

Markdown Document

ResourceEntry

Globalization Pipeline individual resource entry accessor

TranslationRequest

User

Globalization Pipeline user access object

## Members

serviceRegex

a Regex for matching the service.
Usage: var credentials = require('cfEnv')
     .getAppEnv().getServiceCreds(gp.serviceRegex);
(except that it needs to match by label)

exampleCredentials

Example credentials such as for documentation.

exampleCredentialsString

Example credentials string

version

Current version

## Functions

getClient(params) ⇒ Client

Construct a g11n-pipeline client.
params.credentials is required unless params.appEnv is supplied.

readJson(filename) ⇒ Promise.<Object>

Read a file, return promise to parsed obj

## Typedefs

basicCallback : function

Basic Callback used throughout the SDK

ExternalService : Object

info about external services available

WordCountsInfo : object

## Bundle
Accessor object for a Globalization Pipeline bundle

**Kind**: global class
**Properties**

| Name | Type | Description |
| --- | --- | --- |
| updatedBy | string | userid that updated this bundle |
| updatedAt | Date | date when the bundle was last updated |
| sourceLanguage | string | bcp47 id of the source language |
| targetLanguages | Array.<string> | array of target langauge bcp47 ids |
| readOnly | boolean | true if this bundle can only be read |
| metadata | Object.<string, string> | array of user-editable metadata |

* [Bundle](#Bundle)
    * [new Bundle(gp, props)](#new_Bundle_new)
    * _instance_
        * [.getInfoFields](#Bundle+getInfoFields)
        * [.delete([opts], cb)](#Bundle+delete)
        * [.create(body, cb)](#Bundle+create)
        * [.getInfo([opts], cb)](#Bundle+getInfo)
        * [.languages()](#Bundle+languages) ⇒ Array.<String>
        * [.getStrings(opts, cb)](#Bundle+getStrings)
        * [.entry(opts)](#Bundle+entry)
        * [.entries(opts, cb)](#Bundle+entries)
        * [.uploadStrings(opts, cb)](#Bundle+uploadStrings)
        * [.update(opts, cb)](#Bundle+update)
        * [.updateStrings(opts, cb)](#Bundle+updateStrings)
    * _inner_
        * [~getInfoCallback](#Bundle..getInfoCallback) : function
        * [~listEntriesCallback](#Bundle..listEntriesCallback) : function

### new Bundle(gp, props)
Note: this constructor is not usually called directly, use Client.bundle(id)

| Param | Type | Description |
| --- | --- | --- |
| gp | [Client](#Client) | parent g11n-pipeline client object |
| props | Object | properties to inherit |

### bundle.getInfoFields
List of fields usable with Bundle.getInfo()

**Kind**: instance property of [Bundle](#Bundle)

### bundle.delete([opts], cb)
Delete this bundle.

**Kind**: instance method of [Bundle](#Bundle)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [opts] | Object | {} | options |
| cb | [basicCallback](#basicCallback) |  |  |

### bundle.create(body, cb)
Create this bundle with the specified params.
Note that on failure, such as an illegal language being specified,
the bundle is not created.

**Kind**: instance method of [Bundle](#Bundle)

| Param | Type | Description |
| --- | --- | --- |
| body | Object |  |
| body.sourceLanguage | string | bcp47 id of source language such as 'en' |
| body.targetLanguages | Array | optional array of target languages |
| body.metadata | Object | optional metadata for the bundle |
| body.partner | string | optional ID of partner assigned to translate this bundle |
| body.notes | Array.<string> | optional note to translators |
| cb | [basicCallback](#basicCallback) |  |

### bundle.getInfo([opts], cb)
Get bundle info. Returns a new Bundle object with additional fields populated.

**Kind**: instance method of [Bundle](#Bundle)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [opts] | Object | {} | Options object |
| opts.fields | String |  | Comma separated list of fields |
| opts.translationStatusMetricsByLanguage | Boolean |  | Optional field (false by default) |
| opts.reviewStatusMetricsByLanguage | Boolean |  | Optional field (false by default) |
| opts.partnerStatusMetricsByLanguage | Boolean |  | Optional field (false by default) |
| cb | [getInfoCallback](#Bundle..getInfoCallback) |  | callback (err, Bundle ) |

### bundle.languages() ⇒ Array.<String>
Return all of the languages (source and target) for this bundle.
The source language will be the first element.
Will return undefined if this bundle was not returned by getInfo().

**Kind**: instance method of [Bundle](#Bundle)

### bundle.getStrings(opts, cb)
Fetch one language's strings

**Kind**: instance method of [Bundle](#Bundle)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| opts | Object |  | options |
| opts.languageId | String |  | language to fetch |
| [opts.fallback] | boolean | false | Whether if source language value is used if translated value is not available |
| [opts.fields] | string |  | Optional fields separated by comma |
| cb | [basicCallback](#basicCallback) |  | callback (err, { resourceStrings: { strings… } }) |

### bundle.entry(opts)
Create an entry object. Doesn't fetch data,

**Kind**: instance method of [Bundle](#Bundle)
**See**: ResourceEntry~getInfo

| Param | Type | Description |
| --- | --- | --- |
| opts | Object | options |
| opts.languageId | String | language |
| opts.resourceKey | String | resource key |

### bundle.entries(opts, cb)
List entries. Callback is called with a map of
resourceKey to ResourceEntry objects.

**Kind**: instance method of [Bundle](#Bundle)

| Param | Type | Description |
| --- | --- | --- |
| opts | Object | options |
| opts.languageId | String | language to fetch |
| cb | listEntriesCallback | Callback with (err, map of resourceKey:ResourceEntry ) |

### bundle.uploadStrings(opts, cb)
Upload resource strings, replacing all current contents for the language

**Kind**: instance method of [Bundle](#Bundle)

| Param | Type | Description |
| --- | --- | --- |
| opts | Object | options |
| opts.languageId | String | language to update |
| opts.strings | Object.<string, string> | strings to update |
| cb | [basicCallback](#basicCallback) |  |

### bundle.update(opts, cb)
**Kind**: instance method of [Bundle](#Bundle)

| Param | Type | Description |
| --- | --- | --- |
| opts | Object | options |
| opts.targetLanguages | array | optional: list of target languages to update |
| opts.readOnly | boolean | optional: set this bundle to be readonly or not |
| opts.metadata | object | optional: metadata to update |
| opts.partner | string | optional: partner id to update |
| opts.notes | Array.<string> | optional notes to translator |
| cb | [basicCallback](#basicCallback) | callback |

### bundle.updateStrings(opts, cb)
Update some strings in a language.

**Kind**: instance method of [Bundle](#Bundle)

| Param | Type | Description |
| --- | --- | --- |
| opts | Object | options |
| opts.strings | Object.<string, string> | strings to update. |
| opts.languageId | String | language to update |
| opts.resync | Boolean | optional: If true, resynchronize strings in the target language and resubmit previously-failing translation operations |
| cb | [basicCallback](#basicCallback) |  |

### Bundle~getInfoCallback : function
Callback returned by Bundle~getInfo().

**Kind**: inner typedef of [Bundle](#Bundle)

| Param | Type | Description |
| --- | --- | --- |
| err | object | error, or null |
| bundle | [Bundle](#Bundle) | bundle object with additional data |
| bundle.updatedBy | string | userid that updated this bundle |
| bundle.updatedAt | Date | date when the bundle was last updated |
| bundle.sourceLanguage | string | bcp47 id of the source language |
| bundle.targetLanguages | Array.<string> | array of target langauge bcp47 ids |
| bundle.readOnly | boolean | true if this bundle can only be read |
| bundle.metadata | Object.<string, string> | array of user-editable metadata |
| bundle.translationStatusMetricsByLanguage | Object | additional metrics information |
| bundle.reviewStatusMetricsByLanguage | Object | additional metrics information |

### Bundle~listEntriesCallback : function
Called by entries()

**Kind**: inner typedef of [Bundle](#Bundle)

| Param | Type | Description |
| --- | --- | --- |
| err | object | error, or null |
| entries | Object.<string, ResourceEntry> | map from resource key to ResourceEntry object. The .value field will be filled in with the string value. |

## Client
Client object for Globalization Pipeline

**Kind**: global class

* [Client](#Client)
    * _instance_
        * [.version](#Client+version)
        * [.url](#Client+url) ⇒ String
        * [.supportedTranslations([opts], cb)](#Client+supportedTranslations)
        * [.getServiceInfo([opts], cb)](#Client+getServiceInfo)
        * [.getServiceInstanceInfo([opts], cb)](#Client+getServiceInstanceInfo)
        * [.ping(args, cb)](#Client+ping)
        * [.createUser(opts, cb)](#Client+createUser)
        * [.user(id)](#Client+user) ⇒ [User](#User)
        * [.users([opts], cb)](#Client+users)
        * [.bundles([opts], cb)](#Client+bundles)
        * [.bundle(opts)](#Client+bundle) ⇒ [Bundle](#Bundle)
        * [.tr(opts)](#Client+tr) ⇒ [TranslationRequest](#TranslationRequest)
        * [.docTr(opts)](#Client+docTr) ⇒ [DocumentTranslationRequest](#DocumentTranslationRequest)
        * [.trs([opts], cb)](#Client+trs)
        * [.docTrs([opts], cb)](#Client+docTrs)
        * [.MarkdownDocument(id)](#Client+MarkdownDocument) ⇒
        * [.HTMLDocument(id)](#Client+HTMLDocument) ⇒
        * [.getMdDocumentList()](#Client+getMdDocumentList) ⇒
        * [.getHTMLDocumentList()](#Client+getHTMLDocumentList)
    * _inner_
        * [~supportedTranslationsCallback](#Client..supportedTranslationsCallback) : function
        * [~serviceInfoCallback](#Client..serviceInfoCallback) : function
        * [~serviceInstanceInfoCallback](#Client..serviceInstanceInfoCallback) : function
        * [~listUsersCallback](#Client..listUsersCallback) : function
        * [~listBundlesCallback](#Client..listBundlesCallback) : function

### client.version
Version number of the REST service used. Currently 'V2'.

**Kind**: instance property of [Client](#Client)

### client.url ⇒ String
Return the URL used for this client.

**Kind**: instance property of [Client](#Client)
**Returns**: String - - the URL

### client.supportedTranslations([opts], cb)
This function returns a map from source language(s) to target language(s).
Example: `{ en: ['de', 'ja']}` meaning English translates to German and Japanese.

**Kind**: instance method of [Client](#Client)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [opts] | object | {} | ignored |
| cb | [supportedTranslationsCallback](#Client..supportedTranslationsCallback) |  | (err, map-of-languages) |

### client.getServiceInfo([opts], cb)
Get global information about this service, not specific to one service instance.

**Kind**: instance method of [Client](#Client)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [opts] | object | {} | ignored argument |
| cb | [serviceInfoCallback](#Client..serviceInfoCallback) |  |  |

### client.getServiceInstanceInfo([opts], cb)
Get information about our specific service instance.

**Kind**: instance method of [Client](#Client)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [opts] | object | {} | options |
| [opts.serviceInstance] | string |  | request a specific service instance's info |
| cb | [serviceInstanceInfoCallback](#Client..serviceInstanceInfoCallback) |  |  |

### client.ping(args, cb)
Verify that there is access to the server. An error result
will be returned if there is a problem. On success, the data returned
can be ignored. (Note: this is a synonym for getServiceInfo())

**Kind**: instance method of [Client](#Client)

| Param | Type | Description |
| --- | --- | --- |
| args | object | (ignored) |
| cb | [basicCallback](#basicCallback) |  |

### client.createUser(opts, cb)
Create a user

**Kind**: instance method of [Client](#Client)

| Param | Type | Description |
| --- | --- | --- |
| opts | object |  |
| opts.type | string | User type (ADMINISTRATOR, TRANSLATOR, or READER) |
| opts.displayName | string | Optional display name for the user. This can be any string and is displayed in the service dashboard. |
| opts.comment | string | Optional comment |
| opts.bundles | Array | set of accessible bundle ids. Use `['*']` for "all bundles" |
| opts.metadata | Object.<string, string> | optional key/value pairs for user metadata |
| opts.externalId | string | optional external user ID for your application's use |
| cb | User~getUserCallback | passed a new User object |

### client.user(id) ⇒ [User](#User)
Create a user access object.
This doesn't create the user itself,
nor query the server, but is just a handle object.
Use createUser() to create a user.

**Kind**: instance method of [Client](#Client)

| Param | Type | Description |
| --- | --- | --- |
| id | Object | String (id) or map {id: bundleId, serviceInstance: serviceInstanceId} |

### client.users([opts], cb)
List users. Callback is called with an array of
user access objects.

**Kind**: instance method of [Client](#Client)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [opts] | Object | {} | options |
| cb | [listUsersCallback](#Client..listUsersCallback) |  | callback |

### client.bundles([opts], cb)
List bundles. Callback is called with an map of
bundle access objects.

**Kind**: instance method of [Client](#Client)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [opts] | Object | {} | options |
| cb | [listBundlesCallback](#Client..listBundlesCallback) |  | given a map of Bundle objects |

### client.bundle(opts) ⇒ [Bundle](#Bundle)
Create a bundle access object.
This doesn't create the bundle itself, just a handle object.
Call create() on the bundle to create it.

**Kind**: instance method of [Client](#Client)

| Param | Type | Description |
| --- | --- | --- |
| opts | Object | String (id) or map {id: bundleId, serviceInstance: serviceInstanceId} |

### client.tr(opts) ⇒ [TranslationRequest](#TranslationRequest)
Create a Translation Request access object.
This doesn't create the TR itself, just a handle object.
Call create() on the translation request to create it.

**Kind**: instance method of [Client](#Client)

| Param | Type | Description |
| --- | --- | --- |
| opts | string \| Object.<string, Object> | Can be a string (id) or map with values (for a new TR). See TranslationRequest. |

### client.docTr(opts) ⇒ [DocumentTranslationRequest](#DocumentTranslationRequest)
Create a Document Translation Request access object.
This doesn't create the Doc TR itself, just a handle object.
Call create() on the translation request to create it.

**Kind**: instance method of [Client](#Client)

| Param | Type | Description |
| --- | --- | --- |
| opts | string \| Object.<string, Object> | Can be a string (id) or map with values (for a new TR). See TranslationRequest. |

### client.trs([opts], cb)
List Translation Requests. Callback is called with an map of
TR access objects.

**Kind**: instance method of [Client](#Client)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [opts] | Object | {} | optional map of options |
| cb | [getTranslationRequestsCallback](#TranslationRequest..getTranslationRequestsCallback) |  | callback yielding a map of Translation Requests |

### client.docTrs([opts], cb)
List Translation Requests. Callback is called with an map of
TR access objects.

**Kind**: instance method of [Client](#Client)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [opts] | Object | {} | optional map of options |
| cb | [getTranslationRequestsCallback](#TranslationRequest..getTranslationRequestsCallback) |  | callback yielding a map of Translation Requests |

### client.MarkdownDocument(id) ⇒
Construct a MarkdownDocument

**Kind**: instance method of [Client](#Client)
**Returns**: MarkdownDocument

| Param | Type |
| --- | --- |
| id | String \| Object |

### client.HTMLDocument(id) ⇒
Construct a HtmlDocument

**Kind**: instance method of [Client](#Client)
**Returns**: HtmlDocument

| Param | Type |
| --- | --- |
| id | String \| Object |

### client.getMdDocumentList() ⇒
get a list of Markdown documents.

**Kind**: instance method of [Client](#Client)
**Returns**: Promise

### client.getHTMLDocumentList()
get a list of Markdown documents

**Kind**: instance method of [Client](#Client)

### Client~supportedTranslationsCallback : function
Callback returned by supportedTranslations()

**Kind**: inner typedef of [Client](#Client)

| Param | Type | Description |
| --- | --- | --- |
| err | object | error, or null |
| languages | Object.<string, Array.<string>> | map from source language to array of target languages Example: `{ en: ['de', 'ja']}` meaning English translates to German and Japanese. |

### Client~serviceInfoCallback : function
Callback used by getServiceInfo()

**Kind**: inner typedef of [Client](#Client)

| Param | Type | Description |
| --- | --- | --- |
| err | object | error, or null |
| info | Object | detailed information about the service |
| info.supportedTranslation | Object.<string, Array.<string>> | map from source language to array of target languages Example: `{ en: ['de', 'ja']}` meaning English translates to German and Japanese. |
| info.supportedHumanTranslation | Object.<string, Array.<string>> | map from source language to array of target languages supported for human translation. Example: `{ en: ['de', 'ja']}` meaning English translates to German and Japanese. |
| info.externalServices | [Array.<ExternalService>](#ExternalService) | info about external services available |

### Client~serviceInstanceInfoCallback : function
Callback returned by getServiceInstanceInfo()

**Kind**: inner typedef of [Client](#Client)

| Param | Type | Description |
| --- | --- | --- |
| err | object | error, or null |
| instanceInfo | object | Additional information about the service instance |
| instanceInfo.updatedBy | string | information about how our service instance was updated |
| instanceInfo.updatedAt | date | when the instance was last updated |
| instanceInfo.region | string | the Bluemix region name |
| instanceInfo.cfServiceInstanceId | string | the CloudFoundry service instance ID |
| instanceInfo.serviceId | string | this is equivalent to the service instance ID |
| instanceInfo.orgId | string | this is the Bluemix organization ID |
| instanceInfo.spaceId | string | this is the Bluemix space ID |
| instanceInfo.planId | string | this is the Bluemix plan ID |
| instanceInfo.htServiceEnabled | boolean | true if the Human Translation service is enabled |
| instanceInfo.usage | object | usage information |
| instanceInfo.usage.size | number | the size of resource data used by the Globalization Pipeline instance in bytes |
| instanceInfo.disabled | boolean | true if this service has been set as disabled by Bluemix |

### Client~listUsersCallback : function
Called by users()

**Kind**: inner typedef of [Client](#Client)
**See**: User

| Param | Type | Description |
| --- | --- | --- |
| err | object | error, or null |
| users | Object.<string, User> | map from user ID to User object |

### Client~listBundlesCallback : function
Bundle list callback

**Kind**: inner typedef of [Client](#Client)

| Param | Type | Description |
| --- | --- | --- |
| err | object | error, or null |
| bundles | Object.<string, Bundle> | map from bundle ID to Bundle object |

## DocumentTranslationRequest
Document Translation Request.

**Kind**: global class

* [DocumentTranslationRequest](#DocumentTranslationRequest)
    * [.type](#DocumentTranslationRequest+type)
    * [.create([opts])](#DocumentTranslationRequest+create) ⇒ [Promise.<DocumentTranslationRequest>](#DocumentTranslationRequest)
    * [.getInfo()](#DocumentTranslationRequest+getInfo) ⇒ [Promise.<DocumentTranslationRequest>](#DocumentTranslationRequest)
    * [.update()](#DocumentTranslationRequest+update) ⇒ Promise

### documentTranslationRequest.type
Get the type of this request.
'doc' for document requests.

**Kind**: instance property of [DocumentTranslationRequest](#DocumentTranslationRequest)

### documentTranslationRequest.create([opts]) ⇒ [Promise.<DocumentTranslationRequest>](#DocumentTranslationRequest)
Create this TR on the server.

**Kind**: instance method of [DocumentTranslationRequest](#DocumentTranslationRequest)
**Returns**: [Promise.<DocumentTranslationRequest>](#DocumentTranslationRequest) - updated object including TR ID

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [opts] | Object | {} | additional fields to set |

### documentTranslationRequest.getInfo() ⇒ [Promise.<DocumentTranslationRequest>](#DocumentTranslationRequest)
Fetch the TR's data from the server.

**Kind**: instance method of [DocumentTranslationRequest](#DocumentTranslationRequest)
**Returns**: [Promise.<DocumentTranslationRequest>](#DocumentTranslationRequest) - The updated TR data

### documentTranslationRequest.update() ⇒ Promise
Update the TR's data on the server.

**Kind**: instance method of [DocumentTranslationRequest](#DocumentTranslationRequest)

## Cli
Command line interface to the Globalization Pipeline.
Example usage:
```js
const Cli = require('g11n-pipeline/lib/gpcli');
new Cli(Cli.parseArgs(process.argv)).run().then(…);
```

**Kind**: global class

* [Cli](#Cli)
    * [new Cli(argv)](#new_Cli_new)
    * _instance_
        * [.filter()](#Cli+filter)
        * [.run()](#Cli+run) ⇒ Promise.<Object>
        * [.getCredentials(argv)](#Cli+getCredentials) ⇒ Object
    * _static_
        * [.parseOpts](#Cli.parseOpts)
        * [.parseArgs(argv)](#Cli.parseArgs)

### new Cli(argv)
To use from a script: `new Cli(Cli.parseArgs(process.argv))`

| Param | Type | Description |
| --- | --- | --- |
| argv | Object | a minimist-compatible argv array (i.e. { "config": "config.json", "_": [ "list" ] }) |
| argv._ | Array.<String> | array of non-option arguments (i.e. 'list', 'ping', etc.) |

### cli.filter()
Filter the result according to the --outputFormat option.
Use:  `cli.run().then((result) => cli.filter(result))`

**Kind**: instance method of [Cli](#Cli)

### cli.run() ⇒ Promise.<Object>
Run the verb, returning a Promise with the result.
If you call this multiple times, it will run multiple times.

**Kind**: instance method of [Cli](#Cli)
**Returns**: Promise.<Object> - the result (verb dependent)

### cli.getCredentials(argv) ⇒ Object
**Kind**: instance method of [Cli](#Cli)
**Returns**: Object - credentials

| Param | Type | Description |
| --- | --- | --- |
| argv | Object | args |

### Cli.parseOpts
Options to be used with minimist.
See https://www.npmjs.com/package/minimist#var-argv--parseargsargs-opts

**Kind**: static property of [Cli](#Cli)

### Cli.parseArgs(argv)
Parse the args with miminist

**Kind**: static method of [Cli](#Cli)

| Param | Type | Description |
| --- | --- | --- |
| argv | Object | argv from process.argv |

## HTMLDocument
HTML Document

**Kind**: global class

* [HTMLDocument](#HTMLDocument)
    * [new HTMLDocument(opts, gp)](#new_HTMLDocument_new)
    * [.serviceInstanceId](#HTMLDocument+serviceInstanceId)
    * [.documentId](#HTMLDocument+documentId)
    * [.documentId](#HTMLDocument+documentId)
    * [.delete()](#HTMLDocument+delete) ⇒ Promise
    * [.create(body)](#HTMLDocument+create) ⇒ Promise
    * [.upload()](#HTMLDocument+upload)
    * [.update(body)](#HTMLDocument+update) ⇒ Promise
    * [.getInfo()](#HTMLDocument+getInfo) ⇒ [Promise.<HTMLDocument>](#HTMLDocument)
    * [.download(opts)](#HTMLDocument+download) ⇒ Promise.<string>

### new HTMLDocument(opts, gp)
Normally this c'tor is not called directly, but client.MarkdownDocument() is used.

| Param | Type | Description |
| --- | --- | --- |
| opts | Object | options |
| gp | [Client](#Client) | backpointer to the client object |

### htmlDocument.serviceInstanceId
Gets the service instance ID

**Kind**: instance property of [HTMLDocument](#HTMLDocument)

### htmlDocument.documentId
Get the document's identifier

**Kind**: instance property of [HTMLDocument](#HTMLDocument)

### htmlDocument.documentId
Set the document's identifier

**Kind**: instance property of [HTMLDocument](#HTMLDocument)

### htmlDocument.delete() ⇒ Promise
Delete this document.

**Kind**: instance method of [HTMLDocument](#HTMLDocument)

### htmlDocument.create(body) ⇒ Promise
Create a new HTML document on the server

**Kind**: instance method of [HTMLDocument](#HTMLDocument)

| Param | Type |
| --- | --- |
| body | Object |

### htmlDocument.upload()
Update the HTML document's content

**Kind**: instance method of [HTMLDocument](#HTMLDocument)

| Param | Type | Description |
| --- | --- | --- |
| opts.languageId | String | language ID to upload. |
| opts.body | String | Updated content |

### htmlDocument.update(body) ⇒ Promise
Update the document's configuration.

**Kind**: instance method of [HTMLDocument](#HTMLDocument)

| Param | Type | Description |
| --- | --- | --- |
| body | Object | values to update |

### htmlDocument.getInfo() ⇒ [Promise.<HTMLDocument>](#HTMLDocument)
Fetch the document's data from the server

**Kind**: instance method of [HTMLDocument](#HTMLDocument)
**Returns**: [Promise.<HTMLDocument>](#HTMLDocument) - new updated object with current values

### htmlDocument.download(opts) ⇒ Promise.<string>
Download document

**Kind**: instance method of [HTMLDocument](#HTMLDocument)
**Returns**: Promise.<string> - the document content

| Param | Type | Description |
| --- | --- | --- |
| opts | String \| Object | (if String, treated as languageId) |
| opts.languageId | String | language to download |

## MarkdownDocument
Markdown Document

**Kind**: global class

* [MarkdownDocument](#MarkdownDocument)
    * [new MarkdownDocument(opts, gp)](#new_MarkdownDocument_new)
    * [.serviceInstanceId](#MarkdownDocument+serviceInstanceId)
    * [.documentId](#MarkdownDocument+documentId)
    * [.documentId](#MarkdownDocument+documentId)
    * [.delete()](#MarkdownDocument+delete) ⇒ Promise
    * [.getInfo()](#MarkdownDocument+getInfo) ⇒ [Promise.<MarkdownDocument>](#MarkdownDocument)
    * [.update(opts)](#MarkdownDocument+update) ⇒ Promise
    * [.download(opts)](#MarkdownDocument+download) ⇒ Promise.<string>
    * [.create(body)](#MarkdownDocument+create) ⇒ Promise
    * [.upload()](#MarkdownDocument+upload) ⇒ Promise

### new MarkdownDocument(opts, gp)
Normally this c'tor is not called directly, but client.MarkdownDocument() is used.

| Param | Type | Description |
| --- | --- | --- |
| opts | Object | options |
| gp | [Client](#Client) | backpointer to the client object |

### markdownDocument.serviceInstanceId
Gets the service instance ID

**Kind**: instance property of [MarkdownDocument](#MarkdownDocument)

### markdownDocument.documentId
Get the document's identifier

**Kind**: instance property of [MarkdownDocument](#MarkdownDocument)

### markdownDocument.documentId
Set the document's identifier

**Kind**: instance property of [MarkdownDocument](#MarkdownDocument)

### markdownDocument.delete() ⇒ Promise
Delete this document.

**Kind**: instance method of [MarkdownDocument](#MarkdownDocument)

### markdownDocument.getInfo() ⇒ [Promise.<MarkdownDocument>](#MarkdownDocument)
Fetch the document's data from the server.

**Kind**: instance method of [MarkdownDocument](#MarkdownDocument)
**Returns**: [Promise.<MarkdownDocument>](#MarkdownDocument) - The updated document data

### markdownDocument.update(opts) ⇒ Promise
Update the document's configuration.

**Kind**: instance method of [MarkdownDocument](#MarkdownDocument)

| Param | Type | Description |
| --- | --- | --- |
| opts | Object | values to update |

### markdownDocument.download(opts) ⇒ Promise.<string>
Download document

**Kind**: instance method of [MarkdownDocument](#MarkdownDocument)
**Returns**: Promise.<string> - the document content

| Param | Type | Description |
| --- | --- | --- |
| opts | String \| Object | (if String, treated as languageId) |
| opts.languageId | String | language to download |

### markdownDocument.create(body) ⇒ Promise
Create a new Markdown document on the server

**Kind**: instance method of [MarkdownDocument](#MarkdownDocument)

| Param | Type |
| --- | --- |
| body | Object |

### markdownDocument.upload() ⇒ Promise
Upload a Markdown document's content

**Kind**: instance method of [MarkdownDocument](#MarkdownDocument)

| Param | Type | Description |
| --- | --- | --- |
| opts.languageId | String | language ID to upload. |
| opts.body | String | Updated content |

## ResourceEntry
Globalization Pipeline individual resource entry accessor

**Kind**: global class
**See**: Bundle~entries
**Properties**

| Name | Type | Description |
| --- | --- | --- |
| resourceKey | String | key for the resource |
| updatedBy | string | the user which last updated this entry |
| updatedAt | Date | when this entry was updated |
| value | string | the translated value of this entry |
| sourceValue | string | the source value of this entry |
| reviewed | boolean | indicator of whether this entry has been reviewed |
| translationStatus | string | status of this translation: `source_language`, `translated`, `in_progress`, or `failed` |
| entry.metadata | Object.<string, string> | user metadata for this entry |
| partnerStatus | string | status of partner integration |
| sequenceNumber | number | relative sequence of this entry |
| notes | Array.<string> | optional notes to translator |

* [ResourceEntry](#ResourceEntry)
    * _instance_
        * [.getInfo([opts], cb)](#ResourceEntry+getInfo)
        * [.update()](#ResourceEntry+update)
    * _inner_
        * [~getInfoCallback](#ResourceEntry..getInfoCallback) : function

### resourceEntry.getInfo([opts], cb)
Load this entry's information. Callback is given
another ResourceEntry but one with all current data filled in.

**Kind**: instance method of [ResourceEntry](#ResourceEntry)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [opts] | Object | {} | options |
| cb | [getInfoCallback](#ResourceEntry..getInfoCallback) |  | callback (err, ResourceEntry) |

### resourceEntry.update()
Update this resource entry's fields.

**Kind**: instance method of [ResourceEntry](#ResourceEntry)

| Param | Type | Description |
| --- | --- | --- |
| opts.value | string | string value to update |
| opts.reviewed | boolean | optional boolean indicating if value was reviewed |
| opts.metadata | object | optional metadata to update |
| opts.notes | Array.<string> | optional notes to translator |
| opts.partnerStatus | string | translation status maintained by partner |
| opts.sequenceNumber | string | sequence number of the entry (only for the source language) |

### ResourceEntry~getInfoCallback : function
Callback called by ResourceEntry~getInfo()

**Kind**: inner typedef of [ResourceEntry](#ResourceEntry)

| Param | Type | Description |
| --- | --- | --- |
| err | object | error, or null |
| entry | [ResourceEntry](#ResourceEntry) | On success, the new or updated ResourceEntry object. |

## TranslationRequest
**Kind**: global class
**Properties**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| id | string |  | Translation Request ID |
| serviceInstance | string |  | the Service Instance that this Translation Request belongs to |
| partner | string |  | the three letter Partner ID to be used. Use 'IBM' for the Professional Plan |
| name | string |  | descriptive title for this translation request |
| targetLanguagesByBundle | Object.<String, Array.<String>> |  | map from Bundle ID to array of target languages |
| emails | Array.<String> |  | array of email addresses for the requester |
| domains | [Array.<TranslationDomain>](#TranslationDomain) |  | A list of applicable translation domains. |
| status | [TranslationRequestStatus](#TranslationRequestStatus) |  | Status of this TR. |
| wordCountsByBundle | Object.<String, WordCountsInfo> |  | map of bundle IDs to word count data |
| updatedBy | string |  | last updated user ID |
| updatedAt | Date |  | date when the TR was updated |
| createdAt | Date |  | date when the TR was first submitted |
| estimatedCompletion | Date |  | date when the TR is expected to be complete |
| startedAt | Date |  | date when the TR was accepted for processing |
| translatedAt | Date |  | date when the TR had completed translation review |
| mergedAt | Date |  | date when the TR was merged back into the target bundles |
| [notes] | Array.<String> | [] | optional array of notes to the translators |
| metadata | Object.<string, string> |  | array of user-defined metadata |

* [TranslationRequest](#TranslationRequest)
    * [new TranslationRequest(gp, props)](#new_TranslationRequest_new)
    * _instance_
        * [.getInfo([opts], cb)](#TranslationRequest+getInfo)
        * [.delete([opts], cb)](#TranslationRequest+delete)
        * [.create([opts], cb)](#TranslationRequest+create)
        * [.update(opts, cb)](#TranslationRequest+update)
    * _inner_
        * [~getTranslationRequestsCallback](#TranslationRequest..getTranslationRequestsCallback) : function
        * [~getTranslationRequestCallback](#TranslationRequest..getTranslationRequestCallback) : function

### new TranslationRequest(gp, props)
This class represents a request for professional editing of machine-translated content.
Note: this constructor is not usually called directly, use Client.tr(id) or Client.tr({fields…})

| Param | Type | Description |
| --- | --- | --- |
| gp | [Client](#Client) | parent g11n-pipeline client object |
| props | Object | properties to inherit |

### translationRequest.getInfo([opts], cb)
Fetch the full record for this translation request.
Example:  `client.tr('1dec633b').getInfo((err, tr) => { console.log(tr.status); });`

**Kind**: instance method of [TranslationRequest](#TranslationRequest)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [opts] | Object | {} | Options object - if present, overrides values in `this` |
| cb | [getTranslationRequestCallback](#TranslationRequest..getTranslationRequestCallback) |  |  |

### translationRequest.delete([opts], cb)
Delete this translation request.

**Kind**: instance method of [TranslationRequest](#TranslationRequest)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [opts] | Object | {} | Options object - if present, overrides values in `this` |
| cb | BasicCallBack |  |  |

### translationRequest.create([opts], cb)
Create a translation request with the specified options. The callback returns a new TranslationRequest object
with the `id` and other fields populated.
Example:  `client.tr({ status: 'SUBMITTED', ... }).create((err, tr) => { console.log(tr.id); });`

**Kind**: instance method of [TranslationRequest](#TranslationRequest)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [opts] | Object | {} | Options object - if present, overrides values in `this` |
| cb | [getTranslationRequestCallback](#TranslationRequest..getTranslationRequestCallback) |  |  |

### translationRequest.update(opts, cb)
Update a translation request with the specified values.
If any property of `opts` is missing, that value will not be updated.

**Kind**: instance method of [TranslationRequest](#TranslationRequest)

| Param | Type | Description |
| --- | --- | --- |
| opts | Object | Options object - contains fields to update |
| [opts.partner] | String | optional: update partner. |
| [opts.name] | String | optional: update name |
| [opts.targetLanguagesByBundle] | Object.<String, Array.<String>> | optional: update target bundle/language list |
| [opts.emails] | Array.<String> | optional: update email list |
| [opts.domains] | [Array.<TranslationDomain>](#TranslationDomain) | optional: update domain list |
| [opts.status] | [TranslationRequestStatus](#TranslationRequestStatus) | optional: update TR status. May only change from `DRAFT` to `SUBMITTED` here. |
| [opts.metadata] | Object.<String, String> | optional: update metadata |
| cb | [basicCallback](#basicCallback) | callback with update status |

### TranslationRequest~getTranslationRequestsCallback : function
Callback returned by trs()

**Kind**: inner typedef of [TranslationRequest](#TranslationRequest)

| Param | Type | Description |
| --- | --- | --- |
| err | Object | error, or null |
| trs | Object.<string, TranslationRequest> | map from translation request ID to TranslationRequest Example: `{ 1dec633b: {…}}` if there was just one TR, id `1dec633b` |

### TranslationRequest~getTranslationRequestCallback : function
Callback returned by getInfo and create

**Kind**: inner typedef of [TranslationRequest](#TranslationRequest)

| Param | Type | Description |
| --- | --- | --- |
| err | Object | error, or null |
| tr | [TranslationRequest](#TranslationRequest) | the returned TranslationRequest |

## User
Globalization Pipeline user access object

**Kind**: global class
**Properties**

| Name | Type | Description |
| --- | --- | --- |
| id | String | the userid |
| updatedBy | String | gives information about which user updated this user last |
| updatedAt | Date | the date when the item was updated |
| type | String | `ADMINISTRATOR`, `TRANSLATOR`, or `READER` |
| displayName | String | optional human friendly name |
| metadata | Object.<string, string> | optional user-defined data |
| serviceManaged | Boolean | if true, the GP service is managing this user |
| password | String | user password |
| comment | String | optional user comment |
| externalId | String | optional User ID used by another system associated with this user |
| bundles | Array.<string> | list of bundles managed by this user |

* [User](#User)
    * [new User(gp, props)](#new_User_new)
    * [.update(opts, cb)](#User+update)
    * [.delete([opts], cb)](#User+delete)
    * [.getInfo(opts, cb)](#User+getInfo)

### new User(gp, props)
Note: this constructor is not usually called directly, use Client.user(id)

| Param | Type | Description |
| --- | --- | --- |
| gp | [Client](#Client) | parent Client object |
| props | Object | properties to inherit |

### user.update(opts, cb)
Update this user.
All fields of opts are optional. For strings, falsy = no change, empty string `''` = deletion.

**Kind**: instance method of [User](#User)

| Param | Type | Description |
| --- | --- | --- |
| opts | object | options |
| opts.displayName | string | User's display name - falsy = no change, empty string `''` = deletion. |
| opts.comment | string | optional comment - falsy = no change, empty string '' = deletion. |
| opts.bundles | Array.<string> | Accessible bundle IDs. |
| opts.metadata | object.<string, string> | User defined user metadata containg key/value pairs. Data will be merged in. Pass in `{}` to erase all metadata. |
| opts.externalId | string | User ID used by another system associated with this user - falsy = no change, empty string '' = deletion. |
| cb | [basicCallback](#basicCallback) | callback with success or failure |

### user.delete([opts], cb)
Delete this user.
Note that the service managed user
(the initial users created by the service) may not be
 deleted.

**Kind**: instance method of [User](#User)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [opts] | Object | {} | options |
| cb | [basicCallback](#basicCallback) |  | callback with success or failure |

### user.getInfo(opts, cb)
Fetch user info.
The callback is given a new User instance, with
all properties filled in.

**Kind**: instance method of [User](#User)

| Param | Type | Description |
| --- | --- | --- |
| opts | Object | optional, ignored |
| cb | User~getUserCallback | called with updated info |

## serviceRegex
a Regex for matching the service.
Usage: `var credentials = require('cfEnv')
     .getAppEnv().getServiceCreds(gp.serviceRegex);`
(except that it needs to match by label)

**Kind**: global variable
**Properties**

| Name |
| --- |
| serviceRegex |

## exampleCredentials
Example credentials such as for documentation.

**Kind**: global variable
**Properties**

| Name |
| --- |
| exampleCredentials |

## exampleCredentialsString
Example credentials string

**Kind**: global variable
**Properties**

| Name |
| --- |
| exampleCredentialsString |

## version
Current version

**Kind**: global variable

## TranslationRequestStatus : enum
Possible status values for Translation Requests

**Kind**: global enum
**Properties**

| Name | Type | Description |
| --- | --- | --- |
| DRAFT | string | The translation request has not been submitted for processing. It may modified or cancelled. |
| SUBMITTED | string | The translation request has been submitted for processing, but has not been accepted by the partner yet. |
| STARTED | string | Work has started on the translation request. |
| TRANSLATED | string | All work has been completed on the translation request. It has not been merged into the target resource data yet. |
| MERGED | string | The translation results have been merged into the original resource bundles. |

## TranslationDomain : enum
Possible translation domains. These provide hints as to the type of translation expected.

**Kind**: global enum
**Properties**

| Name | Type | Default |
| --- | --- | --- |
| AEROMIL | string | "Aerospace and the military-industrial complex" |
| CNSTRCT | string | "Construction" |
| GDSSVCS | string | "Goods and service" |
| EDUCATN | string | "Education" |
| FINSVCS | string | "Financial Services" |
| GOVPUBL | string | "Government and public sector" |
| HEALTHC | string | "Healthcare and social services" |
| INDSTMF | string | "Industrial manufacturing" |
| TELECOM | string | "Telecommunication" |
| DMEDENT | string | "Digital media and entertainment" |
| INFTECH | string | "Information technology" |
| TRVLTRS | string | "Travel and transportation" |
| INSURNC | string | "Insurance" |
| ENGYUTL | string | "Energy and utilities" |
| AGRICLT | string | "Agriculture" |

## getClient(params) ⇒ [Client](#Client)
Construct a g11n-pipeline client.
params.credentials is required unless params.appEnv is supplied.

**Kind**: global function

| Param | Type | Description |
| --- | --- | --- |
| params | Object | configuration params |
| params.appEnv | Object | pass the result of cfEnv.getAppEnv(). Ignored if params.credentials is supplied. |
| params.credentials | Object.<string, string> | Bound credentials as from the CF service broker (overrides appEnv) |
| params.credentials.url | string | service URL. (should end in '/translate') |
| params.credentials.userId | string | service API key. |
| params.credentials.password | string | service API key. |
| params.credentials.instanceId | string | instance ID |

## readJson(filename) ⇒ Promise.<Object>
Read a file, return promise to parsed obj

**Kind**: global function

| Param | Type | Description |
| --- | --- | --- |
| filename | String | path to file |

## basicCallback : function
Basic Callback used throughout the SDK

**Kind**: global typedef

| Param | Type | Description |
| --- | --- | --- |
| err | Object | error, or null |
| data | Object | Returned data |

## ExternalService : Object
info about external services available

**Kind**: global typedef
**Properties**

| Name | Type | Description |
| --- | --- | --- |
| type | string | The type of the service, such as MT for Machine Translation |
| name | string | The name of the service |
| id | string | The id of the service |
| supportedTranslation | Object.<string, Array.<string>> | map from source language to array of target languages Example: `{ en: ['de', 'ja']}` meaning English translates to German and Japanese. |

## WordCountsInfo : object
**Kind**: global typedef
**Properties**

| Name | Type | Description |
| --- | --- | --- |
| sourceLanguage | string | bcp47 id of the source language, such as 'en' |
| counts | object.<string, number> | map from target language to word count |

*docs autogenerated via [jsdoc2md](https://github.com/jsdoc2md/jsdoc-to-markdown)*

Community
===
* View or file GitHub [Issues](https://github.com/IBM-Cloud/gp-js-client/issues)
* Connect with the open source community on [developerWorks Open](https://developer.ibm.com/open/ibm-bluemix-globalization-pipeline/node-js-sdk/)

Contributing
===
See [CONTRIBUTING.md](CONTRIBUTING.md).

License
===
Apache 2.0. See [LICENSE.txt](LICENSE.txt)

> Licensed under the Apache License, Version 2.0 (the "License");
> you may not use this file except in compliance with the License.
> You may obtain a copy of the License at
>
> http://www.apache.org/licenses/LICENSE-2.0
>
> Unless required by applicable law or agreed to in writing, software
> distributed under the License is distributed on an "AS IS" BASIS,
> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
> See the License for the specific language governing permissions and
> limitations under the License.


text:
"""
@file
@brief Helpers around images.
"""
import os
import glob
import numpy

def zoom_img(img, factor=1., max_dim=None, out_file=None, fLOG=None):
    """
    Zooms an image.

    :param img: image or filename or pattern
    :param factor: multiplies the image by this factor if not None
    :param max_dim: modifies the image, the highest dimension
        should below this number
    :param out_file: stores the image into this file if not None
    :param fLOG: logging function
    :return: image
    """
    if isinstance(img, str):
        if '*' in img:
            found = glob.glob(img)
            res = []
            for im in found:
                if out_file is None:
                    i = zoom_img(im, factor=factor, max_dim=max_dim, fLOG=fLOG)
                else:
                    of = out_file.format(os.path.split(im)[-1])
                    i = zoom_img(im, factor=factor, max_dim=max_dim,
                                 out_file=of, fLOG=fLOG)
                res.append(i)
            if len(res) == 0:
                raise FileNotFoundError(  # pragma: no cover
                    f"Unable to find anything in '{img}'.")
            return res
        from PIL import Image
        obj = Image.open(img)
    elif hasattr(img, 'size'):
        obj = img
    else:
        raise TypeError(  # pragma: no cover
            f"Image should be a string or an image not {type(img)}.")
    dx, dy = obj.size
    if max_dim is not None:
        if not isinstance(max_dim, int):
            max_dim = int(max_dim)
        facx = max_dim * 1. / max(dx, 1)
        facy = max_dim * 1. / max(dy, 1)
        factor = min(facx, facy)
    if factor is not None:
        if not isinstance(factor, float):
            factor = int(factor)
        dx = int(dx * factor + 0.5)
        dy = int(dy * factor + 0.5)
        obj = obj.resize((dx, dy))
    if out_file is not None:
        if fLOG is not None:
            fLOG(f"Writing '{out_file}' dim=({dx},{dy}).")
        obj.save(out_file)
    return obj

def white_to_transparency(img, out_file=None):
    """
    Sets white color as transparency color.

    @param      img         image (:epkg:`Pillow`)
    @param      out_file    stores the image into this file if not None
    @return                 image (:epkg:`Pillow`)

    Code taken from `Using PIL to make all white pixels transparent?
    <https://stackoverflow.com/questions/765736/
    using-pil-to-make-all-white-pixels-transparent>`_.
    """
    from PIL import Image
    if isinstance(img, str):
        img = Image.open(img)
    x = numpy.asarray(img.convert('RGBA')).copy()

    x[:, :, 3] = (255 * (x[:, :, :3] != 255).any(axis=2)).astype(numpy.uint8)

    obj = Image.fromarray(x)
    if out_file is not None:
        obj.save(out_file)
    return obj

def _optimization_criterion(target, data, weight_above=10, weight_below=1):
    sizes = {}
    for row, width in data:
        if row not in sizes:
            sizes[row] = 0
        sizes[row] += width
    loss = 0
    for row, size in sizes.items():
        if size < target:
            loss += weight_below * (target - size)
        else:
            loss += weight_above * (size - target)
        if row > 0 and sizes.get(row, 0) == 0:
            loss += weight_below * target
    return loss

def _optimization_histogram_order(target, data, weight_above=10,
                                  weight_below=1):
    if len(data) < 6:
        # we try all permutation
        rows = [0 for d in data]
        best_loss = None
        best_rows = rows.copy()
        while rows[0] == 0:
            loss = _optimization_criterion(
                target, zip(rows, data),
                weight_above=weight_above,
                weight_below=weight_below)
            if best_loss is None or loss < best_loss:
                best_loss = loss
                best_rows = rows.copy()
            i = len(rows) - 1
            rows[i] += 1
            while i > 0 and rows[i] >= len(data):
                rows[i] = 0
                i -= 1
                rows[i] += 1
        return best_rows

    # generic case
    data_pos = [0 for i in data]
    current_row = 0
    size = data[0]
    for i in range(1, len(data)):
        if size + data[i] > target:
            current_row += 1
            size = data[i]
        else:
            size += data[i]
        data_pos[i] = current_row

    return data_pos

def concat_images(imgs, height=200, width=800,
                  weight_above=10, weight_below=1,
                  background=(0, 0, 0), out_file=None):
    """
    Concatenates images into an image with several
    rows of images.

    :param imgs: filename or Images (:epkg:`Pillow`)
    :param height: height of each row (pixels)
    :param width: width of each row (pixels)
    :param weight_above: loss when a line is too long
    :param weight_below: loss when a line is too short
    :param background: background color
    :param out_file: stores the image into this file if not None
    :return: Image (:epkg:`Pillow`)
    """
    from PIL import Image
    images = []
    for img in imgs:
        if isinstance(img, str):
            images.append(Image.open(img))
        else:
            images.append(img)

    # zoom
    images = [zoom_img(img, factor=height * 1.0 / img.size[1])
              for img in images]

    # optimization
    data = [img.size[0] for img in images]
    pos = _optimization_histogram_order(
        width, data, weight_above=weight_above, weight_below=weight_below)

    # concat
    n_rows = max(pos) + 1
    img_height = n_rows * height

    new_image = Image.new('RGB', (width, img_height), background)
    x_row = {}
    for row, img in zip(pos, images):
        if row not in x_row:
            x_row[row] = 0
        w = x_row[row]
        new_image.paste(img, (w, row * height))
        x_row[row] += img.size[0]
    if out_file is not None:
        new_image.save(out_file)
    return new_image

redpajama_set_name: RedPajamaGithub


text:
/**
 * @fileoverview This file contains various functions for taking a screenshot
 */

tdl.provide('tdl.screenshot');

tdl.require('tdl.io');
tdl.require('tdl.log');

/**
 * takes a screenshot of a canvas. Sends it to the server to be saved.
 */
tdl.screenshot.takeScreenshot = function(canvas) {
  tdl.io.sendJSON(
      this.url,
      {cmd: 'screenshot', dataURL: canvas.toDataURL()},
      function() {});
};


text:
import React, { Component, PropTypes, View, Text, TouchableNativeFeedback } from 'react-native';
import { default as PolyfillRipple } from './polyfill/Ripple';
import { isCompatible } from './helpers';

export default class Ripple extends Component {

    static propTypes = {
        color: PropTypes.string,
        onPress: PropTypes.func,
        onLongPress: PropTypes.func,
        children: PropTypes.node.isRequired
    };

    static defaultProps = {
        color: 'rgba(0,0,0,.2)'
    };

    render() {
        const { color, onPress, onLongPress, children, ...other } = this.props;

        if (!isCompatible('TouchableNativeFeedback')) {
            return (
                <PolyfillRipple
                    rippleColor={color}
                    onPress={onPress}
                    onLongPress={onLongPress}
                    {...other}
                >
                    {/* Stops fatal crash with out of bounds animation */}
                    <View style={{ marginHorizontal: .2 }}>
                        {children}
                    </View>
                </PolyfillRipple>
            )
        }

        return (
            <TouchableNativeFeedback
                background={TouchableNativeFeedback.Ripple(color)}
                onPress={onPress}
                onLongPress={onLongPress}
            >
                <View {...other}>
                    {children}
                </View>
            </TouchableNativeFeedback>
        );
    }

}


text:
// /* tslint:disable:no-unused-variable */
//
// import { TestBed } from '@angular/core/testing';
// import { NO_ERRORS_SCHEMA } from '@angular/core';
// import { ActivatedRoute, Router } from '@angular/router';
// import { Observable } from 'rxjs/Observable';
// import 'rxjs/add/observable/from';
//
// import { AdminBlogListComponent } from './admin-blog-list.component';
// import { AuthService } from '../user/auth.service';
// import { BlogService } from '../blog/blog.service';
//
// const blogListStub = [{
//   title: 'Test blog entry',
//   content: 'Test content',
//   created: new Date(),
//   _id: 'objectid',
//   user: {
//     profile: {
//       name: 'Test User'
//     },
//     _id: 'objectid'
//   }
// }];
// let fixture;
// let component;
//
// describe('AdminBlogListComponent', () => {
//   beforeEach(() => {
//     TestBed.configureTestingModule({
//       declarations: [
//         AdminBlogListComponent
//       ],
//       providers: [
//         {
//           provide: Router,
//           useValue: {navigate: function() {}}
//         },
//         {
//           provide: ActivatedRoute,
//           useValue: {
//             queryParams: Observable.from([1]),
//             snapshot: {
//               data: {resolveData: {blogEntries: blogListStub}},
//               queryParams: {limit: 10, sort: '-created', skip: 0}
//             }
//           }
//         },
//         {
//           provide: AuthService,
//           useValue: {}
//         },
//         {
//           provide: BlogService,
//           useValue: {
//             deleteBlogEntry: entry => Observable.from([entry])
//           }
//         }
//       ],
//       schemas: [NO_ERRORS_SCHEMA]
//     });
//     TestBed.compileComponents();
//     fixture = TestBed.createComponent(AdminBlogListComponent);
//     component = fixture.debugElement.componentInstance;
//     component.ngOnDestroy = function() {};
//   });
//
//   it('loads the admin blog list component', () => {
//     expect(component).toBeTruthy();
//   });
//
//   describe('deleteBlogEntry()', () => {
//     it('calls deleteBlogEntry service method', () => {
//       const blogService = TestBed.get(BlogService);
//       spyOn(blogService, 'deleteBlogEntry').and.callThrough();
//       component.deleteBlogEntry(blogListStub[0]);
//       expect(blogService.deleteBlogEntry).toHaveBeenCalledWith(blogListStub[0]);
//     });
//   });
// });


text:
	<TITLE>3rd Party ROBOTC Drivers</TITLE>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

    3rd Party ROBOTC Drivers

            [Home] [Download] [Submit a bug/suggestion]  [ROBOTC Forums] [Blog] [Support this project]

holitdata-motormux-test1.c

#pragma config(Sensor, S1,     HDMMUX,              sensorI2CCustom)
//*!!Code automatically generated by 'ROBOTC' configuration wizard               !!*//

/*
 * $Id: holitdata-motormux-test1.c 123 2012-11-02 16:35:15Z xander $
 */

/**
 * holitdata-motormux.h provides an API for the Holit Data Systems Motor MUX. This program
 * demonstrates how to use that API to control the motors attached to the MUX.
 *
 * Changelog:
 * - 0.1: Initial release
 * - 0.2: Removed common.h from list of includes
 *
 * Credits:
 * - Big thanks to Holit Data Systems for providing me with the hardware necessary to write and test this.
 *
 * License: You may use this code as you wish, provided you give credit where it's due.
 *
 * THIS CODE WILL ONLY WORK WITH ROBOTC VERSION 3.54 AND HIGHER.
 * Xander Soldaat (xander_at_botbench.com)
 * 14 February 2011
 * version 0.2
 */

#include "drivers/holitdata-motormux.h"

task main () {
  long encA  = 0;
  long encB  = 0;
  long encC  = 0;

  ubyte motorStatus = 0;
  string motorAstatus;
  string motorBstatus;
  string motorCstatus;

  eraseDisplay();

  // Initialise all the internal variables
  HDMMUXinit();

  // Reset the encoders.  This can be done individually or all at once.
  // You should do this at the start of your program.
  HDMMotorEncoderResetAll(HDMMUX);

  // You can specify the type of braking that should be used when the motors
  // are sent the stop command.  The default is to use brake.
  HDMMotorSetBrake(mmotor_S1_1);
  HDMMotorSetFloat(mmotor_S1_2);
  HDMMotorSetFloat(mmotor_S1_3);

  // Specify a target for the motors to run to.  This can be number of
  // rotations, seconds or degrees (encoder count).  Rotations and seconds
  // may be specified in increments of 0.01.
  HDMMotorSetRotationTarget(mmotor_S1_1, 4.50);
  HDMMotorSetTimeTarget(mmotor_S1_2, 2.50);
  HDMMotorSetEncoderTarget(mmotor_S1_3, 1000);

  // Tell the motors to start moving.
  HDMMotor(mmotor_S1_1, 50);
  HDMMotor(mmotor_S1_2, 50);
  HDMMotor(mmotor_S1_3, 50);

  while (true) {
    // Retrieve the motor-MUX's status info and encoder counts
                HDMMUXreadStatus(HDMMUX, motorStatus, encA, encB, encC);

                // Use the HDMMotorBusy() function to see if a motor is busy or idle.
                motorAstatus = HDMMotorBusy(mmotor_S1_1) ? "busy" : "idle";
          motorBstatus = HDMMotorBusy(mmotor_S1_2) ? "busy" : "idle";
                motorCstatus = HDMMotorBusy(mmotor_S1_3) ? "busy" : "idle";

                // Display the info.
                nxtDisplayTextLine(5, "A: %5d (%s)", encA, motorAstatus);
                nxtDisplayTextLine(6, "B: %5d (%s)", encB, motorBstatus);
                nxtDisplayTextLine(7, "C: %5d (%s)", encC, motorCstatus);
    wait1Msec(5);
  }
}

/*
 * $Id: holitdata-motormux-test1.c 123 2012-11-02 16:35:15Z xander $
 */

<address class="footer">Generated on Fri Nov 2 2012 17:45:51 for ROBOTC Drivers by

 1.7.2 </address>


text:
package org.sagebionetworks.repo.model.dbo.ses;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.time.Instant;
import java.util.Optional;
import java.util.UUID;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.sagebionetworks.repo.model.principal.EmailQuarantineReason;
import org.sagebionetworks.repo.model.ses.QuarantinedEmail;
import org.sagebionetworks.repo.model.ses.QuarantinedEmailBatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = { "classpath:jdomodels-test-context.xml" })
public class EmailQuarantineDaoImplTest {

	@Autowired
	private EmailQuarantineDao dao;

	private String testEmail = "testemail@test.com";
	private String sesMessageId = UUID.randomUUID().toString();
	private Long defaultTimeout = 60 * 1000L;

	@BeforeEach
	public void before() {
		dao.clearAll();
	}

	@AfterEach
	public void after() {
		dao.clearAll();
	}

	@Test
	public void addToQuarantineBatchEmpty() {
		// Call under test
		dao.addToQuarantine(QuarantinedEmailBatch.EMPTY_BATCH);
	}

	@Test
	public void addToQuarantineBatchWithNoExpiration() {
		QuarantinedEmailBatch batch = new QuarantinedEmailBatch()
				.add(new QuarantinedEmail(testEmail, EmailQuarantineReason.PERMANENT_BOUNCE));

		// Call under test
		dao.addToQuarantine(batch);

		QuarantinedEmail result = dao.getQuarantinedEmail(testEmail).get();

		QuarantinedEmail expected = batch.get(0);

		expected.withCreatedOn(result.getCreatedOn());
		expected.withUpdatedOn(result.getUpdatedOn());

		assertEquals(expected, result);
	}

	@Test
	public void addToQuarantineWithReasonDetails() {
		QuarantinedEmail expected = getTestQuarantinedEmail()
				.withReasonDetails("Some details");

		QuarantinedEmailBatch batch = new QuarantinedEmailBatch()
				.add(expected);

		// Call under test
		dao.addToQuarantine(batch);

		QuarantinedEmail result = dao.getQuarantinedEmail(testEmail).get();

		expected.withCreatedOn(result.getCreatedOn());
		expected.withUpdatedOn(result.getUpdatedOn());

		assertEquals(expected, result);
	}

	@Test
	public void addToQuarantineWithoutMessageId() {
		QuarantinedEmail expected = getTestQuarantinedEmail()
				.withSesMessageId(null);

		QuarantinedEmailBatch batch = new QuarantinedEmailBatch()
				.add(expected);

		// Call under test
		dao.addToQuarantine(batch);

		QuarantinedEmail result = dao.getQuarantinedEmail(testEmail).get();

		expected.withCreatedOn(result.getCreatedOn());
		expected.withUpdatedOn(result.getUpdatedOn());

		assertEquals(expected, result);
	}

	@Test
	public void addToQuarantineBatchWithExpiration() {
		QuarantinedEmailBatch batch = new QuarantinedEmailBatch()
				.withExpirationTimeout(defaultTimeout)
				.add(new QuarantinedEmail(testEmail, EmailQuarantineReason.PERMANENT_BOUNCE));

		// Call under test
		dao.addToQuarantine(batch);

		QuarantinedEmail result = dao.getQuarantinedEmail(testEmail).get();

		QuarantinedEmail expected = batch.get(0);

		expected.withCreatedOn(result.getCreatedOn());
		expected.withUpdatedOn(result.getUpdatedOn());
		expected.withExpiresOn(result.getUpdatedOn().plusMillis(defaultTimeout));

		assertEquals(expected, result);
	}

	@Test
	public void addToQuarantineBatchRemovingExpiration() {

		QuarantinedEmailBatch batch = new QuarantinedEmailBatch()
				.withExpirationTimeout(defaultTimeout)
				.add(getTestQuarantinedEmail());

		dao.addToQuarantine(batch);

		batch.withExpirationTimeout(null);

		// Call under test
		dao.addToQuarantine(batch);

		QuarantinedEmail result = dao.getQuarantinedEmail(testEmail).get();

		QuarantinedEmail expected = batch.get(0);

		expected.withCreatedOn(result.getCreatedOn());
		expected.withUpdatedOn(result.getUpdatedOn());
		expected.withExpiresOn(null);

		assertEquals(expected, result);
	}

	@Test
	public void addToQuarantineBatchRefreshingUpdatedOn() throws Exception {

		QuarantinedEmailBatch batch = new QuarantinedEmailBatch()
				.withExpirationTimeout(defaultTimeout)
				.add(getTestQuarantinedEmail());

		dao.addToQuarantine(batch);

		QuarantinedEmail quarantinedEmail = dao.getQuarantinedEmail(testEmail).get();

		Instant createdOn = quarantinedEmail.getCreatedOn();
		Instant updatedOn = quarantinedEmail.getUpdatedOn();

		Thread.sleep(100);

		// Call under test
		dao.addToQuarantine(batch);

		QuarantinedEmail result = dao.getQuarantinedEmail(testEmail).get();

		assertEquals(createdOn, result.getCreatedOn());
		assertTrue(result.getUpdatedOn().isAfter(updatedOn));
	}

	@Test
	public void addToQuarantineBatchMultiple() {
		QuarantinedEmailBatch batch = new QuarantinedEmailBatch();

		String email1 = testEmail;
		String email2 = UUID.randomUUID() + testEmail;
		EmailQuarantineReason reason = EmailQuarantineReason.PERMANENT_BOUNCE;

		batch.add(getTestQuarantinedEmail(email1, reason));
		batch.add(getTestQuarantinedEmail(email2, reason));

		// Call under test
		dao.addToQuarantine(batch);

		assertTrue(dao.getQuarantinedEmail(email1).isPresent());
		assertTrue(dao.getQuarantinedEmail(email2).isPresent());
	}

	@Test
	public void testRemoveFromQuarantineWithInvalidInput() {
		Assertions.assertThrows(IllegalArgumentException.class, () -> {
			String testEmail = null;
			// Call under test
			dao.removeFromQuarantine(testEmail);
		});
		Assertions.assertThrows(IllegalArgumentException.class, () -> {
			String testEmail = "";
			// Call under test
			dao.removeFromQuarantine(testEmail);
		});
		Assertions.assertThrows(IllegalArgumentException.class, () -> {
			String testEmail = "    ";
			// Call under test
			dao.removeFromQuarantine(testEmail);
		});
	}

	@Test
	public void testRemoveFromQuarantineWithNonExisting() {

		// Call under test
		boolean result = dao.removeFromQuarantine(testEmail);

		assertFalse(result);
		assertFalse(dao.getQuarantinedEmail(testEmail).isPresent());
	}

	@Test
	public void testRemoveFromQuarantineWithExisting() {
		String toKeepEmail = System.currentTimeMillis() + testEmail;

		QuarantinedEmailBatch batch = new QuarantinedEmailBatch()
				.withExpirationTimeout(defaultTimeout)
				.add(getTestQuarantinedEmail())
				.add(getTestQuarantinedEmail(toKeepEmail, EmailQuarantineReason.OTHER));

		dao.addToQuarantine(batch);

		// Call under test
		boolean result = dao.removeFromQuarantine(testEmail);

		assertTrue(result);
		assertFalse(dao.getQuarantinedEmail(testEmail).isPresent());
		assertTrue(dao.getQuarantinedEmail(toKeepEmail).isPresent());
	}

	@Test
	public void testGetQuarantinedEmailWithInvalidInput() {
		Assertions.assertThrows(IllegalArgumentException.class, () -> {
			String testEmail = null;
			// Call under test
			dao.getQuarantinedEmail(testEmail);
		});
		Assertions.assertThrows(IllegalArgumentException.class, () -> {
			String testEmail = "";
			// Call under test
			dao.getQuarantinedEmail(testEmail);
		});
		Assertions.assertThrows(IllegalArgumentException.class, () -> {
			String testEmail = "    ";
			// Call under test
			dao.getQuarantinedEmail(testEmail);
		});
	}

	@Test
	public void testGetQuarantineEmailWithExisting() {

		QuarantinedEmail expected = getTestQuarantinedEmail();
		QuarantinedEmail other = getTestQuarantinedEmail(System.currentTimeMillis() + testEmail, EmailQuarantineReason.OTHER);

		QuarantinedEmailBatch batch = new QuarantinedEmailBatch()
				.withExpirationTimeout(defaultTimeout);

		batch.add(expected);
		batch.add(other);

		dao.addToQuarantine(batch);

		// Call under test
		QuarantinedEmail result = dao.getQuarantinedEmail(testEmail).get();

		expected.withCreatedOn(result.getCreatedOn());
		expected.withUpdatedOn(result.getUpdatedOn());
		expected.withExpiresOn(result.getExpiresOn());

		assertEquals(expected, result);

	}

	@Test
	public void testGetQuarantineEmailWithExpired() throws Exception {
		Long timeout = 50L;

		QuarantinedEmailBatch batch = new QuarantinedEmailBatch()
				.withExpirationTimeout(timeout)
				.add(getTestQuarantinedEmail());

		dao.addToQuarantine(batch);

		Thread.sleep(timeout * 2);

		// Call under test
		Optional<QuarantinedEmail> result = dao.getQuarantinedEmail(testEmail);

		assertFalse(result.isPresent());
	}

	@Test
	public void testGetQuarantineEmailWithNoExpiration() throws Exception {
		QuarantinedEmail expected = getTestQuarantinedEmail();

		QuarantinedEmailBatch batch = new QuarantinedEmailBatch()
				.add(getTestQuarantinedEmail());

		dao.addToQuarantine(batch);

		// Call under test
		QuarantinedEmail result = dao.getQuarantinedEmail(testEmail).get();

		expected.withCreatedOn(result.getCreatedOn());
		expected.withUpdatedOn(result.getUpdatedOn());
		expected.withExpiresOn(result.getExpiresOn());

		assertEquals(expected, result);
	}

	@Test
	public void testGetQuarantineEmailWithoutExpirationCheck() throws Exception {
		QuarantinedEmail expected = getTestQuarantinedEmail();
		Long timeout = 50L;

		QuarantinedEmailBatch batch = new QuarantinedEmailBatch()
				.withExpirationTimeout(timeout)
				.add(getTestQuarantinedEmail());

		dao.addToQuarantine(batch);

		Thread.sleep(timeout * 2);

		// Call under test
		QuarantinedEmail result = dao.getQuarantinedEmail(testEmail, false).get();

		expected.withCreatedOn(result.getCreatedOn());
		expected.withUpdatedOn(result.getUpdatedOn());
		expected.withExpiresOn(result.getExpiresOn());

		assertEquals(expected, result);
	}

	@Test
	public void testIsQuarantinedWithoutExpiration() {
		QuarantinedEmailBatch batch = new QuarantinedEmailBatch()
				.add(getTestQuarantinedEmail());

		dao.addToQuarantine(batch);

		// Call under test

		assertTrue(dao.isQuarantined(testEmail));
	}

	@Test
	public void testIsQuarantinedWithExpiration() {
		QuarantinedEmailBatch batch = new QuarantinedEmailBatch()
				.withExpirationTimeout(defaultTimeout)
				.add(getTestQuarantinedEmail());

		dao.addToQuarantine(batch);

		// Call under test

		assertTrue(dao.isQuarantined(testEmail));
	}

	@Test
	public void testIsQuarantinedWithExpirationExpired() throws Exception {
		Long timeout = 50L;

		QuarantinedEmailBatch batch = new QuarantinedEmailBatch()
				.withExpirationTimeout(timeout)
				.add(getTestQuarantinedEmail());

		dao.addToQuarantine(batch);

		Thread.sleep(timeout * 2);

		// Call under test

		assertFalse(dao.isQuarantined(testEmail));
	}

	private QuarantinedEmail getTestQuarantinedEmail() {
		return getTestQuarantinedEmail(testEmail, EmailQuarantineReason.PERMANENT_BOUNCE);
	}

	private QuarantinedEmail getTestQuarantinedEmail(String email, EmailQuarantineReason reason) {
		return new QuarantinedEmail(email, reason)
				.withSesMessageId(sesMessageId);
	}

}


text:
package com.mob.thor.rpc.common.utils;

public class Holder<T> {

    private volatile T value;

    public void set(T value) {
        this.value = value;
    }

    public T get() {
        return value;
    }
}


text:
# MergeImages

Create a new image merged from the images with PHP.

By cabenitez <cabenitez83@gmail.com>

### Features
  - Suport JPEG, PNG, GIF and remote images.
  - Easy installation.
  - Display on the screen.
  - Allows you to save the result to a file.
  - Get result in base64 encoded for use in  element.
  - Create an new PNG image with transparent background.

### Graphic explanation

 **+**
 **+**
 **=**

### Requirements

- PHP 5+
- GD library

### Installation
Download and extract the [latest release](https://github.com/MergeImages).

### Usage

```php
<?php
// include mergeImages.php file
require_once 'mergeImages/mergeImages.php';

// instance Class
$mergeimages = new MergeImages;

// Images to be merged
$images = ['image1.jpg', 'image2.jpg', 'image3.png'];

// call to main process
$mergeimages->process($images);

```

### Methods

```php
<?php
/*
@param: $images (Array | Images to be merged).
@param: $save (Boolean | Indicate whether to save the result on the screen).
@param: $path (String | Path to save merged image).
@param: $filename (String | Filename for merged image).
@param: $output (String | Indicate whether you want to display the result on the screen, get the base64 code or none, the allowed values are "none", "screen" or "base64").
@return Image merged.
*/
$mergeimages->process($images, $save, $path, $filename, $output);

/*
@param: $images (Array | Images to be merged).
@return None.
*/
$mergeimages->setItems($images);

/*
@param: None.
@return Array of images added.
*/
$mergeimages->getItems();

/*
@param: None.
@return None.
*/
$mergeimages->mergeItems();

/*
@param: $path (String | Path to save merged image).
@param: $filename (String | Filename for merged image).
@return Image merged.
*/
$mergeimages->saveImage($path, $filename);

/*
@param: None.
@return Merged image.
*/
$mergeimages->showImage();

/*
@param: None.
@return Merged image encoded with MIME base64.
*/
$src = $mergeimages->getImage();
<img src="<?=$src?>" alt="Merged Image">

```
### Todos

 - Process base64 encoded images

### License

MIT


text:
using System;
using System.Drawing;

using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.CoreGraphics;
using MonoMac.OpenGL;

namespace NeHeLesson9
{
	public class Texture
	{
		int texId;
		int pboId;
		byte[] data;
		int width, height;

		private Texture () : base()
		{
		}

		public Texture (string path) : base()
		{
			GetImagaDataFromPath (path);
			LoadTexture ();
		}

		void GetImagaDataFromPath (string path)
		{
			NSImage src;
			CGImage image;
			CGContext context = null;

			src = new NSImage (path);

			image = src.AsCGImage (RectangleF.Empty, null, null);
			width = image.Width;
			height = image.Height;

			data = new byte[width * height * 4];

			CGImageAlphaInfo ai = CGImageAlphaInfo.PremultipliedLast;

			context = new CGBitmapContext (data, width, height, 8, 4 * width, image.ColorSpace, ai);

			// Core Graphics referential is upside-down compared to OpenGL referential
			// Flip the Core Graphics context here
			// An alternative is to use flipped OpenGL texture coordinates when drawing textures
			context.TranslateCTM (0, height);
			context.ScaleCTM (1, -1);

			// Set the blend mode to copy before drawing since the previous contents of memory aren't used.
			// This avoids unnecessary blending.
			context.SetBlendMode (CGBlendMode.Copy);

			context.DrawImage (new RectangleF (0, 0, width, height), image);
		}

		void LoadTexture ()
		{
			GL.GenTextures (1, out texId);
			GL.GenBuffers (1, out pboId);

			// Bind the texture
			GL.BindTexture (TextureTarget.Texture2D, texId);

			// Bind the PBO
			GL.BindBuffer (BufferTarget.PixelUnpackBuffer, pboId);

			// Upload the texture data to the PBO
			GL.BufferData (BufferTarget.PixelUnpackBuffer, new IntPtr (width * height * 4 * sizeof(byte)), data, BufferUsageHint.StaticDraw);

			// Setup texture parameters
			GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear);
			GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear);

			GL.PixelStore (PixelStoreParameter.UnpackRowLength, 0);

			// OpenGL likes the GL_BGRA + GL_UNSIGNED_INT_8_8_8_8_REV combination
			// Use offset instead of pointer to indictate that we want to use data copied from a PBO
			GL.TexImage2D (TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, width, height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero);
			data = null;

			GL.BindTexture (TextureTarget.Texture2D, 0);
			GL.BindBuffer (BufferTarget.PixelUnpackBuffer, 0);
		}

		public int TextureName {
			get { return texId; }
		}
	}
}


text:
@ECHO OFF
::===============================================================================
::    Copyright 2017 Geoscience Australia
::
::    Licensed under the Apache License, Version 2.0 (the "License");
::    you may not use this file except in compliance with the License.
::    You may obtain a copy of the License at
::
::        http://www.apache.org/licenses/LICENSE-2.0
::
::    Unless required by applicable law or agreed to in writing, software
::    distributed under the License is distributed on an "AS IS" BASIS,
::    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
::    See the License for the specific language governing permissions and
::    limitations under the License.
::===============================================================================
:: Batch file to invoke _csw_utils Python script in MS-Windows
:: Written by Written by Alex Ip & Andrew Turner 27/2/2017
:: Example invocation: csw_find -k "NCI, AU, grid, potassium" -b 148.996,-35.48,149.399,-35.124

python -m geophys_utils.csw_find  %*


text:
@protocol PFAccountViewControllerDelegate <NSObject>

- (void)PFAccountViewController:(id)sender viewPicture:(NSString *)link;
- (void)PFAccountViewControllerBack;
- (void)Tutorial;

@end

@interface PFAccountViewController : UIViewController < UITextViewDelegate >

@property (strong, nonatomic) DCManager *Demoapi;
@property (assign, nonatomic) id <PFAccountViewControllerDelegate> delegate;

@property (strong, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) IBOutlet UIView *headerView;
@property (strong, nonatomic) IBOutlet UIView *bgEditView;
@property (strong, nonatomic) IBOutlet UIView *footerView;

@property (strong, nonatomic) NSDictionary *obj;

@property (strong, nonatomic) NSString *rowCount;

@property (strong, nonatomic) IBOutlet UIView *waitView;
@property (strong, nonatomic) IBOutlet UIView *popupwaitView;

@property (strong, nonatomic) IBOutlet UIView *bgnewsView;
@property (strong, nonatomic) IBOutlet UIView *bgmessageView;

@property (strong, nonatomic) IBOutlet AsyncImageView *thumUser;
@property (strong, nonatomic) IBOutlet UITextField *display_name;

@property (strong, nonatomic) IBOutlet UIButton *logoutButton;

- (IBAction)editProfile:(id)sender;

- (IBAction)switchNewsonoff:(id)sender;
- (IBAction)switchMessageonoff:(id)sender;

@property (strong, nonatomic) IBOutlet UISwitch *switchNews;
@property (strong, nonatomic) IBOutlet UISwitch *switchMessage;

- (IBAction)logoutTapped:(id)sender;

#pragma mark - tut

@property (strong, nonatomic) IBOutlet UIView *tutorialMainView;
@property (strong, nonatomic) IBOutlet UIScrollView *tutorialScrollView;
@property (strong, nonatomic) IBOutlet UIView *tutorialDetailView;

@property (strong, nonatomic) IBOutlet UITextField *testcode;
@property (strong, nonatomic) IBOutlet UITextField *appkey;
@property (strong, nonatomic) IBOutlet UIButton *tutorialButton;
@property (strong, nonatomic) IBOutlet UIButton *nexttutorialButton;

@property (strong, nonatomic) IBOutlet UIPageControl *pageControl;

- (IBAction)tutorialTapped:(id)sender;
- (IBAction)nexttutorialTapped:(id)sender;

- (IBAction)appkeyTextTutorial:(id)sender;
- (IBAction)testcodeTextTutorial:(id)sender;

- (IBAction)appstoreTutorial:(id)sender;
- (IBAction)linkTutorial:(id)sender;
- (IBAction)newappkeyTutorial:(id)sender;
- (IBAction)newtestcodeTutorial:(id)sender;

@end


text:
package index

import (
	"os"
	"path/filepath"
)

func (d *FileSystemDirectory) remove(kind string, id uint64) error {
	segmentPath := filepath.Join(d.path, d.fileName(kind, id))
	segmentFile, err := d.openExclusive(segmentPath, os.O_CREATE|os.O_RDWR, d.newFilePerm)
	if err != nil {
		return err
	}
	defer func() {
		_ = segmentFile.Close()
	}()

	return os.Remove(segmentPath)
}


text:
package com.intellij.dvcs.push.ui;

import com.intellij.ui.CheckboxTree;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.SimpleColoredComponent;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.util.ObjectUtils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.MouseEvent;

public class PushLogTreeUtil {
  @NonNls
  public static final String EDIT_MODE_PROP = "tree.edit.mode";

  @Nullable
  public static Object getTagAtForRenderer(CheckboxTree.CheckboxTreeCellRenderer renderer, MouseEvent e) {
    JTree tree = (JTree)e.getSource();
    Object tag = null;
    final TreePath path = tree.getPathForLocation(e.getX(), e.getY());
    if (path != null) {
      final Rectangle rectangle = tree.getPathBounds(path);
      assert rectangle != null;
      int dx = e.getX() - rectangle.x;
      final TreeNode treeNode = (TreeNode)path.getLastPathComponent();
      final int row = tree.getRowForLocation(e.getX(), e.getY());
      tree.getCellRenderer().getTreeCellRendererComponent(tree, treeNode, false, false, true, row, true);
      if (treeNode instanceof RepositoryNode) {
        RepositoryNode repositoryNode = (RepositoryNode)treeNode;
        int checkBoxWidth = repositoryNode.isCheckboxVisible() ? renderer.getCheckbox().getWidth() : 0;
        tag = renderer.getTextRenderer().getFragmentTagAt(dx - checkBoxWidth);
      }
      else {
        tag = renderer.getTextRenderer().getFragmentTagAt(dx);
      }
    }
    return tag;
  }

  public static SimpleTextAttributes addTransparencyIfNeeded(@NotNull SimpleColoredComponent component,
                                                             @NotNull SimpleTextAttributes baseStyle,
                                                             boolean isActive) {
    if (isActive) return baseStyle;
    Color color = ObjectUtils.chooseNotNull(baseStyle.getFgColor(), component.getForeground());
    return new SimpleTextAttributes(baseStyle.getStyle(), ColorUtil.toAlpha(color, 85));
  }
}


text:
package org.jspare.core;

import org.jspare.core.helpers.FooResource;
import org.junit.Assert;
import org.junit.Test;

import static org.jspare.core.Environment.my;

public class ResourceTest {

  @Test
  public void resourceInjectionTest() {

    Environment.release();

    FooResource foo = my(FooResource.class);

    // Test injection
    Assert.assertNotNull(foo);

    // Test default value of helpers data
    Assert.assertEquals(FooResource.DEFAULT, foo.getDefaultName());

    foo.setDefaultName("test");

    // Test reference retention
    Assert.assertEquals("test", my(FooResource.class).getDefaultName());

    // Test factory instantiation
    Assert.assertEquals(FooResource.DEFAULT, Environment.provide(FooResource.class).getDefaultName());

    // Test original reference retention
    Assert.assertEquals("test", my(FooResource.class).getDefaultName());
  }
}


text:
class CreateProperties < ActiveRecord::Migration
  def self.up
    create_table :properties do |t|
      t.string :key
      t.string :value

      t.timestamps
    end
  end
end


text:
import json

from django.forms import widgets
from django.forms.fields import CharField, BooleanField
from django.db.models.fields.related import ManyToOneRel
from django.contrib.admin import StackedInline
from django.core.exceptions import ValidationError
from django.utils.html import strip_tags, strip_spaces_between_tags
from django.utils.safestring import mark_safe
from django.utils.translation import ngettext_lazy, gettext_lazy as _
from filer.fields.image import FilerImageField, AdminImageFormField
from filer.settings import settings as filer_settings
from filer.utils.loader import load_model
from cms.plugin_pool import plugin_pool
from djangocms_text_ckeditor.fields import HTMLFormField

from cmsplugin_cascade import app_settings
from cmsplugin_cascade.fields import HiddenDictField, SizeField, MultiSizeField
from cmsplugin_cascade.forms import CascadeModelForm, CascadeModelFormMixin
from cmsplugin_cascade.image import ImagePropertyMixin
from cmsplugin_cascade.mixins import WithInlineElementsMixin
from cmsplugin_cascade.models import InlineCascadeElement
from cmsplugin_cascade.plugin_base import CascadePluginBase, create_proxy_model
from cmsplugin_cascade.utils import compute_aspect_ratio, get_image_size, parse_responsive_length

Image = load_model(filer_settings.FILER_IMAGE_MODEL)

class MarkerModelMixin:
    @property
    def data(self):
        return mark_safe(json.dumps(self.glossary))

class MarkerForm(CascadeModelForm):
    title = CharField(
        label=_("Marker Title"),
        widget=widgets.TextInput(attrs={'size': 60}),
        help_text=_("Please choose a title, then go to the map to set a marker pin.")
    )

    use_icon = BooleanField(
        label=_("Use customized marker icon"),
        initial=False,
        required=False,
    )

    marker_image = AdminImageFormField(
        ManyToOneRel(FilerImageField, Image, 'file_ptr'),
        Image.objects.all(),
        label=_("Icon"),
        required=False,
        to_field_name='image_file',
    )

    marker_width = SizeField(
        label=_("Icon Width"),
        allowed_units=['px'],
        required=False,
        help_text=_("Width of the marker icon in pixels."),
    )

    marker_anchor = MultiSizeField(
        ['left', 'top'],
        label=_("Marker Anchor"),
        sublabels=[_("Left"), _("Top")],
        allowed_units=['px', '%'],
        required=False,
        help_text=_("Coordinates of the icon's anchor relative to its top left corner."),
    )

    popup_text = HTMLFormField(
        required=False,
        help_text=_("Text to display in popup."),
    )

    position = HiddenDictField()

    address_lookup = CharField(
        label=_("Address lookup"),
        required=False,
        help_text=_("Search for an address"),
        widget=widgets.TextInput(attrs={'size': 100}),
    )

    class Meta:
        entangled_fields = {'glossary': ['title', 'use_icon', 'marker_image', 'marker_width', 'marker_anchor',
                                         'popup_text', 'position']}

    def clean(self):
        cleaned_data = super().clean()
        try:
            position = cleaned_data['position']
            if isinstance(position, str):
                position = json.loads(position)
            elif not isinstance(position, dict):
                raise ValueError
        except (ValueError, KeyError):
            raise ValidationError("Invalid internal position data. Check your Javascript imports.")
        else:
            if 'lat' not in position or 'lng' not in position:
                # place the marker in the center of the current map
                position = {k: v for k, v in self.instance.cascade_element.glossary['map_position'].items()
                            if k in ['lat', 'lng']}
                cleaned_data['position'] = position

        popup_text = cleaned_data.pop('popup_text', '')
        if strip_tags(popup_text):
            cleaned_data['popup_text'] = strip_spaces_between_tags(popup_text)
        return cleaned_data

class MarkerInline(StackedInline):
    model = InlineCascadeElement
    form = MarkerForm
    raw_id_fields = ['marker_image']
    verbose_name = _("Marker")
    verbose_name_plural = _("Markers")
    extra = 0

class LeafletFormMixin(CascadeModelFormMixin):
    map_width = SizeField(
        label=_("Map Width"),
        allowed_units=['px', '%'],
        initial='100%',
        help_text=_("Set the map width in percent relative to containing element."),
    )

    map_height = SizeField(
        label=_("Adapt Map Height"),
        allowed_units=['px', '%'],
        initial='400px',
        help_text=_("Set a fixed height in pixels, or percent relative to the map width."),
    )

    map_min_height = SizeField(
        label=_("Adapt Map Minimum Height"),
        allowed_units=['px'],
        required=False,
        help_text=_("Optional, set a minimum height in pixels."),
    )

    scroll_wheel_zoom = BooleanField(
        label=_("Zoom by scrolling wheel"),
        initial=True,
        required=False,
        help_text=_("Zoom into map on mouse over by scrolling wheel."),
    )

    map_position = HiddenDictField(
        initial=app_settings.CMSPLUGIN_CASCADE['leaflet']['default_position'],
    )

    class Meta:
        entangled_fields = {'glossary': ['map_width', 'map_height', 'map_position', 'map_min_height',
                                         'scroll_wheel_zoom']}

    def clean(self):
        cleaned_data = super().clean()
        try:
            if isinstance(cleaned_data['map_position'], str):
                cleaned_data['map_position'] = json.loads(cleaned_data['map_position'])
            elif not isinstance(cleaned_data['map_position'], dict):
                raise ValueError
        except (ValueError, KeyError):
            raise ValidationError("Invalid internal position data. Check your Javascript imports.")
        return cleaned_data

class LeafletModelMixin:
    @property
    def map_position(self):
        return mark_safe(json.dumps(self.glossary.get('map_position', {})))

class LeafletPlugin(WithInlineElementsMixin, CascadePluginBase):
    name = _("Map")
    parent_classes = None
    require_parent = False
    allow_children = False
    change_form_template = 'cascade/admin/leaflet_plugin_change_form.html'
    ring_plugin = 'LeafletPlugin'
    form = LeafletFormMixin
    admin_preview = False
    render_template = 'cascade/plugins/leaflet.html'
    inlines = [MarkerInline]
    model_mixins = (LeafletModelMixin,)
    settings = mark_safe(json.dumps(app_settings.CMSPLUGIN_CASCADE['leaflet']))

    class Media:
        css = {'all': [
            'node_modules/leaflet/dist/leaflet.css',
            'node_modules/leaflet-easybutton/src/easy-button.css',
            'cascade/css/admin/leafletplugin.css',
        ]}
        js = [
            'node_modules/leaflet/dist/leaflet.js',
            'node_modules/leaflet-easybutton/src/easy-button.js',
            'admin/js/jquery.init.js',
            'cascade/js/admin/leafletplugin.js',
        ]

    def add_view(self, request, form_url='', extra_context=None):
        extra_context = dict(extra_context or {}, settings=self.settings)
        return super().add_view(request, form_url, extra_context)

    def change_view(self, request, object_id, form_url='', extra_context=None):
        extra_context = dict(extra_context or {}, settings=self.settings)
        return super().change_view(request, object_id, form_url, extra_context)

    def render(self, context, instance, placeholder):
        marker_instances = []
        for inline_element in instance.inline_elements.all():
            try:
                ProxyModel = create_proxy_model('LeafletMarker',
                                                (ImagePropertyMixin, MarkerModelMixin),
                                                InlineCascadeElement,
                                                module=__name__)
                marker = ProxyModel(id=inline_element.id, glossary=inline_element.glossary)
                try:
                    aspect_ratio = compute_aspect_ratio(marker.image)
                    width = parse_responsive_length(marker.glossary.get('marker_width') or '25px')
                    marker.size = list(get_image_size(width[0], (None, None), aspect_ratio))
                    marker.size2x = 2 * marker.size[0], 2 * marker.size[1]
                except Exception:
                    # if accessing the image file fails, skip size computations
                    pass
                else:
                    try:
                        marker_anchor = marker.glossary['marker_anchor']
                        top = parse_responsive_length(marker_anchor['top'])
                        left = parse_responsive_length(marker_anchor['left'])
                        if top[0] is None or left[0] is None:
                            left = width[0] * left[1]
                            top = width[0] * aspect_ratio * top[1]
                        else:
                            left, top = left[0], top[0]
                        marker.anchor = [left, top]
                    except Exception:
                        pass
                marker_instances.append(marker)
            except (KeyError, AttributeError):
                pass

        context.update(dict(instance=instance,
                            placeholder=placeholder,
                            settings=self.settings,
                            config=app_settings.CMSPLUGIN_CASCADE['leaflet'],
                            markers=marker_instances))
        return context

    @classmethod
    def get_css_classes(cls, obj):
        css_classes = cls.super(LeafletPlugin, cls).get_css_classes(obj)
        css_class = obj.glossary.get('css_class')
        if css_class:
            css_classes.append(css_class)
        return css_classes

    @classmethod
    def get_identifier(cls, obj):
        num_elems = obj.inline_elements.count()
        content = ngettext_lazy("with {0} marker", "with {0} markers", num_elems).format(num_elems)
        return mark_safe(content)

    @classmethod
    def get_data_representation(cls, instance):
        data = super().get_data_representation(instance)
        data.update(inlines=[ie.glossary for ie in instance.inline_elements.all()])
        return data

plugin_pool.register_plugin(LeafletPlugin)


text:
class Comment < ActiveRecord::Base
  belongs_to :author, class_name: 'User', foreign_key: 'author_id'
end


text:
describe("Weather", function() {
  var weather;

  beforeEach(function() {
    weather = new Weather();
    math = {
      random: function() {
      }
    };
  });

  it("could be stormy", function() {
    spyOn(math, "random").and.returnValue(0.9);
    expect(weather.stormy()).toEqual(true);
  });

});