text:
copyright:
 years: 2015, 2016

---

# Installing the Cordova Push plug-in
{: #cordova_install}

Install and use the client Push plug-in to further develop your Cordova applications. This also installs the Cordova Core plug-in, which initializes your connection to Bluemix.

### Before you begin

1. Download the latest Android Studio SDK and Xcode versions.
1. Set up your emulator. For Android Studio, use an emulator that supports Google Play API.
1. Install the Git command-line tool. For Windows, make sure you select the **Run Git from the Window Command Prompt** option. For information about how to download and install this tool, see [Git](https://git-scm.com/downloads).

1. Install the Node.js and Node Package Manager (NPM) tool. The NPM command-line tool is bundled with Node.js. For information about how to download and install Node.js, see [Node.js](https://nodejs.org/en/download/).
1. From the command line, install the Cordova command-line tools by using the **npm install -g cordova** command. This is required to use the Cordova Push plug-in. For information about how to install Cordova and set up your Cordova app, see [Cordova Apache](https://cordova.apache.org/#getstarted).

	**Note**: To view the Cordova Push plug-in readme file, go to [https://github.com/ibm-bluemix-mobile-services/bms-clientsdk-cordova-plugin-push](https://github.com/ibm-bluemix-mobile-services/bms-clientsdk-cordova-plugin-push)

## Installing the Cordova Push plug-in
1. Change to the folder that you want to create your Cordova app in and run the following command to create a Cordova application. If you have an existing Cordova app, go to step 3.

```
cordova create your_app_name
cd your_app_name
```
1. Optional: (Optional) Edit the **config.xml** file and change the application name in the <name> element to one that you choose, rather than the default HelloCordova name.

	**Note**: Make sure you specify the correct Bundle ID. If you do not, the following error messages are displayed in Xcode.
	* The executable was signed with invalid entitlements.
	* The entitlements specified in your application's Code Signing Entitlements file do not match those specified in your provisioning profile.

	To fix this issue, specify the correct Bundle ID in Xcode or in your Cordova app **config.xml**  file.

1. Add the minimum supported API or the deployment target declaration to the config.xml file for your Cordova application. The minSdkVersion value must be higher than 15. The targetSdkVersion value must always reflect the latest Android SDK that is available from Google.
	* **Android** - With your editor, open the config.xml file and update the
`<platform name="android">` element with minimum and target SDK versions:

	```
	<!-- add deployment target declaration -->
	<platform name="android">
			  <preference name="android-minSdkVersion" value="15" />
			  <preference name="android-targetSdkVersion" value="23" />
			</platform>
	```
   * **iOS** - Update the <platform name="ios"> element with a deployment target declaration:

	```
	<platform name="ios">
	    <preference name="deployment-target" value="8.0" />
	    <!-- other properties -->
	</ platform>
	```

1. From the Cordova command-line interface (CLI), add your platforms: iOS, Android, or both by using the following commands.

	```
	cordova platform add ios@3.9.0
	cordova platform add android
	```
1. From your Cordova application root directory, enter the following command to install the Cordova Push plug-in: **cordova plugin add ibm-mfp-push**.

	Depending on the platforms that you added, you see something similar to the following:

	```
	Installing "ibm-mfp-push" for android
	Installing "ibm-mfp-push" for ios
	```
1. From *your-app-root-folder*, verify that the Cordova Core and Push plug-in were installed successfully by using the following command: **cordova plugin list**.

	Depending on the platforms that you added, you see something similar to the following:

	```
	ibm-mfp-core 1.0.0 "MFPCore"
	ibm-mfp-push 1.0.0 "MFPPush"
	```
1. (iOS only) - Configure your iOS development environment.
	a. Open your your-app-name.xcodeproj file in *your-app-name***/platforms/ios** directory with Xcode.

	b. Add the Bridging Header. Go to **Build settings > Swift Compiler - Code Generation > Objective-C Bridging Header** and add the following path: *your-project-name***/Plugins/ibm-mfp-core/Bridging-Header.h**

	c. Add the Frameworks parameter. Go to **Build Settings > Linking > Runpath Search Paths** and add the following parameter:
	```
	@executable_path/Frameworks
	```
	d. Uncomment the following Push import statements in your bridging header. Go to *your-project-name***/Plugins/ibm-mfp-core/Bridging-Header.h**

	```
	//#import <IMFPush/IMFPush.h>
	//#import <IMFPush/IMFPushClient.h>
	//#import <IMFPush/IMFResponse+IMFPushCategory.h>
	```
	e. Build and run your application with Xcode.
1. (Android only)- Build your Android project by using the following command:
**cordova build android**.

	**Note**: Before opening your project in Android Studio, you must first build your Cordova application through the Cordova CLI. Otherwise, you will encounter build errors.

# Initializing the Cordova plug-in
{: #cordova_initialize}

Before you can use the Push Notification Service Cordova plug-in, you need to initialize it by passing the application route and application GUID. After initializing the plug-in, you can connect to the server app that you have created in the Bluemix dashboard. The Cordova plug-in is the wrapper for the Android and iOS client SDKs to enable a Cordova app to communicate with Bluemix services.

1. Initialize the BMSClient by copying and pasting the following code snippet into your main JavaScript file (typically located under the **www/js** directory).

	```
	BMSClient.initialize("https://myapp.mybluemix.net","abcd1234-abcd-1234-abcd-abcd1234abcd");
	```
1. Modify the code snippet to use your Bluemix Route and appGUID parameters. Click the **Mobile Options** link in your Bluemix Application Dashboard to get the application Route and App GUID. Use the Route and App GUID values as your parameters in your `BMSClient.initialize` code snippet.

	**Note**: If you have created a Cordova app using the Cordova CLI, for example, Cordova create app-name command, put this Javascript code in the **index.js** file, after the `app.receivedEvent` function within the `onDeviceReady: function()` function to initialize the BMS client.

```
onDeviceReady: function() {
    app.receivedEvent('deviceready');
    BMSClient.initialize("https://myapp.mybluemix.net","abcd1234-abcd-1234-abcd-abcd1234abcd");
    },
```

# Registering devices

{: #cordova_register}

To register a device with the Push Notification Service, call the register method.

Copy and paste the following code snippet into your Cordova application to register a device.

```
	var success = function(message) { console.log("Success: " + message); };
	var failure = function(message) { console.log("Error: " + message); };
	MFPPush.registerDevice({}, success, failure);
```

## Android
{: #cordova_register_android}
Android does not use of the settings parameter. If you are only building an Android app, pass an empty object; for example:

```
	MFPPush.registerDevice({}, success, failure);
	MFPPush.unregisterDevice(success, failure);
```

##	iOS
{: #cordova_register_ios}
If you want to customize the alert, badge, and sound properties, add the following JavaScript code snippet to the web part of your Cordova application.

```
	var settings = {
	   ios: {
	       alert: true,
	       badge: true,
	       sound: true
	   }
	}
	MFPPush.registerDevice(settings, success, failure);
```

##JavaScript
{: #cordova_register_js}

```
MFPPush.registerDevice({}, success, failure);
```

You can access the contents of the success response parameter in Javascript using JSON.parse:
**var token = JSON.parse(response).token**

Available keys are as follows: `token`, `userId`, and `deviceId`.

The following JavaScript code snippet shows how to initialize your Bluemix Mobile Services client SDK, register a device with the Push Notification Service, and listen to push notifications. You put this code in your Javascript file.

```
//Register device token with Bluemix Push Notification Service
funcapplication(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData){
  CDVMFPPush.sharedInstance().didRegisterForRemoteNotifications(deviceToken)
}
```

```
//Handle error when failed to register device token with APNs
funcapplication(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSErrorPointer){
CDVMFPPush.sharedInstance().didFailToRegisterForRemoteNotifications(error)
}
```

within the **onDeviceReady: function()**.

```
onDeviceReady: function() {
     app.receivedEvent('deviceready');
     BMSClient.initialize("https://http://myroute_mybluemix.net","my_appGuid");
     var success = function(message) { console.log("Success: " + message); };
     var failure = function(message) { console.log("Error: " + message); };
     var settings = {
         ios: {
             alert: true,
             badge: true,
             sound: true
         }
     };
     MFPPush.registerDevice(settings, success, failure);
     var notification = function(notif){
         alert (notif.message);
     };
     MFPPush.registerNotificationsCallback(notification);

 }
```

## Objective-C
{: #cordova_register_objective}
Add the following Objective-C code snippet to your application delegate class

```
	// Register the device token with Bluemix Push Notification Service
	- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
	  [[CDVMFPPush sharedInstance] didRegisterForRemoteNotifications:deviceToken];
	}
	// Handle error when failed to register device token with APNs
	- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
	   [[CDVMFPPush sharedInstance] didFailToRegisterForRemoteNotificationsWithError:error];
	}
```

##Swift
{: #cordova_register_swift}
Add the following Swift code snippet to your application delegate class.

```
funcapplication(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData){
   CDVMFPPush.sharedInstance().didRegisterForRemoteNotifications(deviceToken)
}
// Handle error when failed to register device token with APNs
funcapplication(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSErrorPointer){
   CDVMFPPush.sharedInstance().didFailToRegisterForRemoteNotifications(error)
}
```

##Next Steps

{: #cordova_register_next}

1. Build your project and then run your project by using the following commands:

	* Android - **cordova build android** and then **cordova run android**

	* iOS - **cordova build ios** and then **cordova run ios**

# Receiving push notifications on devices
{: #cordova_receive}

Copy and paste the following code snippets to receive push notifications on devices.

##JavaScript

Add the following JavaScript code snippet to the web part of your Cordova application.

```
var notification = function(notification){
    // notification is a JSON object.
    alert(notification.message);
};
MFPPush.registerNotificationsCallback(notification);
```

##Android notification properties

The following section lists the Android notification properties:

* message - Push notification message
* payload - JSON object containing a notification payload

##iOS notification properties

The following section lists the iOS notification properties:

* message - Push notification message
* payload - JSON object containing a notification payload
action-loc-key - The string is used as a key to get a localized string in the current localization to use for the right button's title instead of "View".
* badge - The number to display as the badge of the app icon. If this property is absent, the badge is not changed. To remove the badge, set the value of this property to 0.
* sound - The name of a sound file in the app bundle or in the Library/Sounds folder of the app data container.

##Objective-C

Add the following Objective-C code snippets to your application delegate class.

```
// Handle receiving a remote notification
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

 [[CDVMFPPush sharedInstance] didReceiveRemoteNotification:userInfo];
}
```

```
// Handle receiving a remote notification on launch
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions

    [[CDVMFPPush sharedInstance] didReceiveRemoteNotificationOnLaunch:launchOptions];
}
```

##Swift

Add the following Swift code snippets to your application delegate class.

```
// Handle receiving a remote notification
funcapplication(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: ){

    CDVMFPPush.sharedInstance().didReceiveRemoteNotification(userInfo)
}
```

```
// Handle receiving a remote notification on launch
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    CDVMFPPush.sharedInstance().didReceiveRemoteNotificationOnLaunch(launchOptions)
}

```

# Sending basic push notifications
{: #push-send-notifications}

After you have developed your applications, you can send basic push notifications (without using tags, badges, additional payloads, or sound files).

Send basic push notifications.

1. In **Choose the Audience**, select one of the following audiences: **All Devices**, or by platform: **Only iOS devices** or **Only Anroid devices**.

	**Note**: When you select the **All Devices** option, all the devices that have subscribed to push notifications receive your notification.

	![Notifications screen](images/tag_notification.jpg)

2. In the **Create your Notification**, enter your message and then click **Send**.
3. Verify that your devices have received your notification.

	The following screen shot shows an alert box handling a push
notification in the foreground on a Android and iOS device.

	![Foreground push notification on Android](images/Android_Screenshot.jpg)

	![Foreground push notification on iOS](images/iOS_Screenshot.jpg)

	The following following screen shot shows a push notification in the background for Android.
	![Background push notification on Android](images/background.jpg)

# Next steps
{: #next_steps_tags}

After you have successfully set up basic notifications, you can configure configure tag-based notifications and advanced options.

Add these Push Notifications Service features to your app.
To use tag-based notifications, see [Tag-based Notifications](c_tag_basednotifications.html).
To use advanced notifications options, see [Advanced push notifications](t_advance_notifications.html).


text:
{{ site.data[page.hl].CoC.Title }}

{{ site.data[page.hl].CoC.Intro }}

{{ site.data[page.hl].ReadMoreAboutThis }}

redpajama_set_name: RedPajamaGithub


text:
{% extends "shop/print/base.html" %}
{% load i18n %}

{% block email-thead %}
	{{ block.super }}
	{% block email-title %}{% trans "Order confirmation for" %} {{ data.get_number }}{% endblock %}
{% endblock %}

{% block content %}
	<h4>{% trans "Delivery Note" %}: {{ order.get_number }}</h4>
	{% include "shop/print/order.html" %}
{% endblock %}


text:
title: Café Barbera
tagline: Café Barbera Platform
type: Everything
platform: IOS, Android, Web
status: released
technologies:
  - React
  - React Native
  - NodeJS
  - HTML
  - CSS
  - Redis
  - MongoDB
roles: Project Manager, Developer, UI/UX Designer

header_image_small: url(./assets/projects/CafeBarberaHeader.jpg)
header_image_big: url(./assets/projects/CafeBarberaHeader.jpg)
header_background_color: '#000300'
header_background_size: cover
---

-------

Café Barbera is a mobile application created to improve the brand awareness of Café Barbera, an international coffee house franchise.
It encourages consumer loyalty with rewards, special offers and indirect marketing promotions.

It's currently used in production by all the shops of the Café Barbera franchise.

I built the whole infrastructure starting from scratch using mainly __Javascript__
and a little bit of Native Code.

The Mobile Application has been made using __React Native__ while the backend has been created using __React__. This allows partial code recycling and helps avoid code repetition through the creation of modules with unique functionalities.
To maintain these modules, I use a private __Sinopia__ server.

## Server-side

One of the main challenges in building an app used worldwide is scalability
and handling usage peaks without causing any interruption.

Café Barbera has 600 shops worldwide with an average of 500-1000 customers per day.
It seems obvious that a cloud implementation is more than necessary.

### API
The API is the heart of the system. It has been implemented using __NodeJS__, __MongoDB__ and __Redis__ and is deployed on __Amazon AWS__.

### Content delivery network
In order to be highly performant, the API doesn't handle any static content.
Static files are delivered by a specialized CDN.

### Administration Backend
The app has been created using __React__, that can be rendered both on client and server (Isomorphism).
I used __Alt__ as __Flux__ implementation and __Material UI__ to provide nice and interesting components that can make the view pleasant to use.

## Mobile App

The app has been created using __React Native__, which simplifies the porting on both __Android__ and __IOS__.

### User interface
I started the creation of the UI with the idea that the app should be immediate and
hassle free, serving the user while in the shop and providing useful information
and push notifications while outside.

The app is composed by three views: Home, ShopList and ShopDetail.
The UI must be clean and straightforward and everything must provide the expected feedback.

__Home__ is where the user receives Messages, Offers and Rewards created specifically for him
(or for the cluster of users with similar 'interests').

__Shoplist__ contains the list of the shops sorted by distance from the user. If the user already collected points from a shop, the shop appears bigger and shows the points.

__ShopDetail__ is the customized page for the shop that contains offers, messages and rewards created by the shop administrator.
The sections in this view are dynamic. They disappear if the section is empty in order to avoid any visual impediment and help the user to browse all the information.

When clicking on a card, a modal window is displayed, showing the related actions.


text:
from typing import Set

from pydantic import BaseModel, DSN, BaseSettings, PyObject

class SubModel(BaseModel):
    foo = 'bar'
    apple = 1

class Settings(BaseSettings):
    redis_host = 'localhost'
    redis_port = 6379
    redis_database = 0
    redis_password: str = None

    auth_key: str = ...

    invoicing_cls: PyObject = 'path.to.Invoice'

    db_name = 'foobar'
    db_user = 'postgres'
    db_password: str = None
    db_host = 'localhost'
    db_port = '5432'
    db_driver = 'postgres'
    db_query: dict = None
    dsn: DSN = None

    # to override domains:
    # export MY_PREFIX_DOMAINS = '["foo.com", "bar.com"]'
    domains: Set[str] = set()

    # to override more_settings:
    # export MY_PREFIX_MORE_SETTINGS = '{"foo": "x", "apple": 1}'
    more_settings: SubModel = SubModel()

    class Config:
        env_prefix = 'MY_PREFIX_'  # defaults to 'APP_'
        fields = {
            'auth_key': {
                'alias': 'my_api_key'
            }
        }


text:
package io.fabric8.commands;

import io.fabric8.api.Container;
import io.fabric8.api.FabricService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;
import org.apache.felix.gogo.commands.Option;
import org.apache.karaf.shell.console.AbstractAction;

@Command(name = ContainerResolverSet.FUNCTION_VALUE, scope = ContainerResolverSet.SCOPE_VALUE, description = ContainerResolverSet.DESCRIPTION, detailedDescription = "classpath:containerResolverSet.txt")
public class ContainerResolverSetAction extends AbstractAction {

    @Option(name = "--all", description = "Apply the resolver policy to all containers in the fabric.")
    private boolean all;

    @Option(name = "--container", required = false, multiValued = true, description = "Apply the resolver policy to the specified container. To specify multiple containers, use this flag multiple times.")
    private List<String> containerIds;

    @Argument(index = 0, required = true, multiValued = false, name = "resolver", description = "The resolver policy to set on the specified container(s). Possible values are: localip, localhostname, publicip, publichostname, manualip.")
    private String resolver;

    private final FabricService fabricService;

    ContainerResolverSetAction(FabricService fabricService) {
        this.fabricService = fabricService;
    }

    @Override
    protected Object doExecute() throws Exception {

        if (containerIds == null || containerIds.isEmpty()) {
            if (all) {
                containerIds = new ArrayList<String>();
                for (Container container : fabricService.getContainers()) {
                    containerIds.add(container.getId());
                }
            } else {
                System.out.println("No container has been specified. Assuming the current container.");
                containerIds = Arrays.asList(fabricService.getCurrentContainer().getId());
            }
        } else {
            if (all) {
                throw new IllegalArgumentException("Can not use --all with a list of containers simultaneously.");
            }
        }

        for (String containerId : containerIds) {
            Container container = fabricService.getContainer(containerId);
            container.setResolver(resolver);
        }
        return null;
    }
}


text:
{{profile.displayName}}

{{profile.name}}

                        Home Address
                        {{profile.address}}

                        Email
                        {{profile.email}}

                        Phone Number
                        {{profile.phone}}

                  Edit your profile
                  My orders

      <app-edit-profile [isEditable]="isEditable" (onCancel)="isEditable = $event"></app-edit-profile>

There are no orders.

My Orders

                Sort by:
                <select class="selectpicker" (change)="onChange($event.target.value)">
                    <option>Pending</option>
                    <option>Delivered</option>
                </select>

                                Order number
                                Date of order
                                Date of delivery
                                Products
                                Total amount
                                Status

                                {{order.$key}}
                                {{order.dateOfOrder | date: 'medium'}}
                                {{order.dateOfDelivery | date: 'medium'}}
                                products
                                {{order.totalPrice}} lv.
                                Pending
                                Delivered

            <pagination-controls (pageChange)="page = $event" id="1"
                            maxSize="6"
                            directionLinks="true"
                            autoHide="true"
                            style="text-align: center; cursor: pointer; font-size: 1.5em;">
                        </pagination-controls>
            <app-user-modal [client]="client"></app-user-modal>

                    <button type="button" class="close" (click)="lgModal.hide()" aria-label="Close">
                    ×
                    </button>

Product list

                            Name
                            Quantity
                            Price

                            {{product.name}}
                            {{product.units}}
                            {{product.price}} lv.

                    <button type="button" class="btn btn-alert" data-dismiss="modal" (click)="lgModal.hide()">Close</button>


text:
'use strict';

var ono  = require('ono'),
    $Ref = require('./ref'),
    url  = require('./util/url');

module.exports = $Refs;

/**
 * This class is a map of JSON references and their resolved values.
 */
function $Refs() {
  /**
   * Indicates whether the schema contains any circular references.
   *
   * @type {boolean}
   */
  this.circular = false;

  /**
   * A map of paths/urls to {@link $Ref} objects
   *
   * @type {object}
   * @protected
   */
  this._$refs = {};

  /**
   * The {@link $Ref} object that is the root of the JSON schema.
   *
   * @type {$Ref}
   * @protected
   */
  this._root$Ref = null;
}

/**
 * Returns the paths of all the files/URLs that are referenced by the JSON schema,
 * including the schema itself.
 *
 * @param {...string|string[]} [types] - Only return paths of the given types ("file", "http", etc.)
 * @returns {string[]}
 */
$Refs.prototype.paths = function(types) {
  var paths = getPaths(this._$refs, arguments);
  return paths.map(function(path) {
    return path.decoded;
  });
};

/**
 * Returns the map of JSON references and their resolved values.
 *
 * @param {...string|string[]} [types] - Only return references of the given types ("file", "http", etc.)
 * @returns {object}
 */
$Refs.prototype.values = function(types) {
  var $refs = this._$refs;
  var paths = getPaths($refs, arguments);
  return paths.reduce(function(obj, path) {
    obj[path.decoded] = $refs[path.encoded].value;
    return obj;
  }, {});
};

/**
 * Returns a POJO (plain old JavaScript object) for serialization as JSON.
 *
 * @returns {object}
 */
$Refs.prototype.toJSON = $Refs.prototype.values;

/**
 * Determines whether the given JSON reference exists.
 *
 * @param {string} path - The path being resolved, optionally with a JSON pointer in the hash
 * @param {$RefParserOptions} [options]
 * @returns {boolean}
 */
$Refs.prototype.exists = function(path, options) {
  try {
    this._resolve(path, options);
    return true;
  }
  catch (e) {
    return false;
  }
};

/**
 * Resolves the given JSON reference and returns the resolved value.
 *
 * @param {string} path - The path being resolved, with a JSON pointer in the hash
 * @param {$RefParserOptions} [options]
 * @returns {*} - Returns the resolved value
 */
$Refs.prototype.get = function(path, options) {
  return this._resolve(path, options).value;
};

/**
 * Sets the value of a nested property within this {@link $Ref#value}.
 * If the property, or any of its parents don't exist, they will be created.
 *
 * @param {string} path - The path of the property to set, optionally with a JSON pointer in the hash
 * @param {*} value - The value to assign
 */
$Refs.prototype.set = function(path, value) {
  path = url.resolve(this._root$Ref.path, path);
  var withoutHash = url.stripHash(path);
  var $ref = this._$refs[withoutHash];

  if (!$ref) {
    throw ono('Error resolving $ref pointer "%s". \n"%s" not found.', path, withoutHash);
  }

  $ref.set(path, value);
};

/**
 * Creates a new {@link $Ref} object and adds it to this {@link $Refs} object.
 *
 * @param {string} path  - The file path or URL of the referenced file
 * @param {*} [value] - Optional. The value of the $ref.
 */
$Refs.prototype._add = function(path, value) {
  var withoutHash = url.stripHash(path);

  var $ref = new $Ref();
  $ref.path = withoutHash;
  $ref.value = value;
  $ref.$refs = this;

  this._$refs[withoutHash] = $ref;
  this._root$Ref = this._root$Ref || $ref;

  return $ref;
};

/**
 * Resolves the given JSON reference.
 *
 * @param {string} path - The path being resolved, optionally with a JSON pointer in the hash
 * @param {$RefParserOptions} [options]
 * @returns {Pointer}
 * @protected
 */
$Refs.prototype._resolve = function(path, options) {
  path = url.resolve(this._root$Ref.path, path);
  var withoutHash = url.stripHash(path);
  var $ref = this._$refs[withoutHash];

  if (!$ref) {
    throw ono('Error resolving $ref pointer "%s". \n"%s" not found.', path, withoutHash);
  }

  return $ref.resolve(path, options);
};

/**
 * Returns the specified {@link $Ref} object, or undefined.
 *
 * @param {string} path - The path being resolved, optionally with a JSON pointer in the hash
 * @returns {$Ref|undefined}
 * @protected
 */
$Refs.prototype._get$Ref = function(path) {
  path = url.resolve(this._root$Ref.path, path);
  var withoutHash = url.stripHash(path);
  return this._$refs[withoutHash];
};

/**
 * Returns the encoded and decoded paths keys of the given object.
 *
 * @param {object} $refs - The object whose keys are URL-encoded paths
 * @param {...string|string[]} [types] - Only return paths of the given types ("file", "http", etc.)
 * @returns {object[]}
 */
function getPaths($refs, types) {
  var paths = Object.keys($refs);

  // Filter the paths by type
  types = Array.isArray(types[0]) ? types[0] : Array.prototype.slice.call(types);
  if (types.length > 0 && types[0]) {
    paths = paths.filter(function(key) {
      return types.indexOf($refs[key].pathType) !== -1;
    });
  }

  // Decode local filesystem paths
  return paths.map(function(path) {
    return {
      encoded: path,
      decoded: $refs[path].pathType === 'file' ? url.toFileSystemPath(path, true) : path
    };
  });
}


text:
namespace _01.Odd_Or_Even_Number
{
    using System;

    public class OddOrEven
    {
        static void Main()
        {
            short number = short.Parse(Console.ReadLine());

            if (number % 2 == 0)
            {
                Console.WriteLine("even {0}", number);
            }
            else
            {
                Console.WriteLine("odd {0}", number);
            }
        }
    }
}


text:
package com.consol.citrus.ftp.config.annotation;

import com.consol.citrus.annotations.CitrusEndpointConfig;

import java.lang.annotation.*;

/**
 * @author Christoph Deppisch
 * @since 2.5
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD })
@CitrusEndpointConfig(qualifier = "endpoint.parser.ftp.client")
public @interface FtpClientConfig {

    /**
     * Host.
     * @return
     */
    String host() default "localhost";

    /**
     * Server port.
     * @return
     */
    int port() default 22222;

    /**
     * Username
     * @return
     */
    String username() default "";

    /**
     * Password
     * @return
     */
    String password() default "";

    /**
     * Message correlator.
     * @return
     */
    String correlator() default "";

    /**
     * Polling interval.
     * @return
     */
    int pollingInterval() default 500;

    /**
     * Timeout.
     * @return
     */
    long timeout() default 5000L;

    /**
     * Test actor.
     * @return
     */
    String actor() default "";
}


text:
#include <geos/operation/union/CascadedPolygonUnion.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Polygon.h>
#include <geos/geom/MultiPolygon.h>
#include <geos/geom/util/GeometryCombiner.h>
#include <geos/geom/util/PolygonExtracter.h>
#include <geos/index/strtree/STRtree.h>
// std
#include <cassert>
#include <cstddef>
#include <memory>
#include <vector>

namespace geos {
namespace operation { // geos.operation
namespace geounion {  // geos.operation.geounion

///////////////////////////////////////////////////////////////////////////////
void GeometryListHolder::deleteItem(geom::Geometry* item)
{
    delete item;
}

///////////////////////////////////////////////////////////////////////////////
geom::Geometry* CascadedPolygonUnion::Union(std::vector<geom::Polygon*>* polys)
{
    CascadedPolygonUnion op (polys);
    return op.Union();
}

geom::Geometry* CascadedPolygonUnion::Union(const geom::MultiPolygon* multipoly)
{
    std::vector<geom::Polygon*> polys;

    typedef geom::MultiPolygon::const_iterator iterator;
    iterator end = multipoly->end();
    for (iterator i = multipoly->begin(); i != end; ++i)
        polys.push_back(dynamic_cast<geom::Polygon*>(*i));

    CascadedPolygonUnion op (&polys);
    return op.Union();
}

geom::Geometry* CascadedPolygonUnion::Union()
{
    if (inputPolys->empty())
        return NULL;

    geomFactory = inputPolys->front()->getFactory();

    /**
     * A spatial index to organize the collection
     * into groups of close geometries.
     * This makes unioning more efficient, since vertices are more likely
     * to be eliminated on each round.
     */
    index::strtree::STRtree index(STRTREE_NODE_CAPACITY);

    typedef std::vector<geom::Polygon*>::iterator iterator_type;
    iterator_type end = inputPolys->end();
    for (iterator_type i = inputPolys->begin(); i != end; ++i) {
        geom::Geometry* g = dynamic_cast<geom::Geometry*>(*i);
        index.insert(g->getEnvelopeInternal(), g);
    }

    std::auto_ptr<index::strtree::ItemsList> itemTree (index.itemsTree());

    return unionTree(itemTree.get());
}

geom::Geometry* CascadedPolygonUnion::unionTree(
    index::strtree::ItemsList* geomTree)
{
    /**
     * Recursively unions all subtrees in the list into single geometries.
     * The result is a list of Geometry's only
     */
    std::auto_ptr<GeometryListHolder> geoms(reduceToGeometries(geomTree));
    return binaryUnion(geoms.get());
}

geom::Geometry* CascadedPolygonUnion::binaryUnion(GeometryListHolder* geoms)
{
    return binaryUnion(geoms, 0, geoms->size());
}

geom::Geometry* CascadedPolygonUnion::binaryUnion(GeometryListHolder* geoms,
    std::size_t start, std::size_t end)
{
    if (end - start <= 1) {
        return unionSafe(geoms->getGeometry(start), NULL);
    }
    else if (end - start == 2) {
        return unionSafe(geoms->getGeometry(start), geoms->getGeometry(start + 1));
    }
    else {
        // recurse on both halves of the list
        std::size_t mid = (end + start) / 2;
        std::auto_ptr<geom::Geometry> g0 (binaryUnion(geoms, start, mid));
        std::auto_ptr<geom::Geometry> g1 (binaryUnion(geoms, mid, end));
        return unionSafe(g0.get(), g1.get());
    }
}

GeometryListHolder*
CascadedPolygonUnion::reduceToGeometries(index::strtree::ItemsList* geomTree)
{
    std::auto_ptr<GeometryListHolder> geoms (new GeometryListHolder());

    typedef index::strtree::ItemsList::iterator iterator_type;
    iterator_type end = geomTree->end();
    for (iterator_type i = geomTree->begin(); i != end; ++i) {
        if ((*i).get_type() == index::strtree::ItemsListItem::item_is_list) {
            std::auto_ptr<geom::Geometry> geom (unionTree((*i).get_itemslist()));
            geoms->push_back_owned(geom.get());
            geom.release();
        }
        else if ((*i).get_type() == index::strtree::ItemsListItem::item_is_geometry) {
            geoms->push_back(reinterpret_cast<geom::Geometry*>((*i).get_geometry()));
        }
        else {
            assert(!"should never be reached");
        }
    }

    return geoms.release();
}

geom::Geometry*
CascadedPolygonUnion::unionSafe(geom::Geometry* g0, geom::Geometry* g1)
{
    if (g0 == NULL && g1 == NULL)
        return NULL;

    if (g0 == NULL)
        return g1->clone();
    if (g1 == NULL)
        return g0->clone();

    return unionOptimized(g0, g1);
}

geom::Geometry*
CascadedPolygonUnion::unionOptimized(geom::Geometry* g0, geom::Geometry* g1)
{
    geom::Envelope const* g0Env = g0->getEnvelopeInternal();
    geom::Envelope const* g1Env = g1->getEnvelopeInternal();

    if (!g0Env->intersects(g1Env))
        return geom::util::GeometryCombiner::combine(g0, g1);

    if (g0->getNumGeometries() <= 1 && g1->getNumGeometries() <= 1)
        return unionActual(g0, g1);

    geom::Envelope commonEnv;
    g0Env->intersection(*g1Env, commonEnv);
    return unionUsingEnvelopeIntersection(g0, g1, commonEnv);
}

geom::Geometry*
CascadedPolygonUnion::unionUsingEnvelopeIntersection(geom::Geometry* g0,
    geom::Geometry* g1, geom::Envelope const& common)
{
    std::vector<geom::Geometry*> disjointPolys;

    std::auto_ptr<geom::Geometry> g0Int(extractByEnvelope(common, g0, disjointPolys));
    std::auto_ptr<geom::Geometry> g1Int(extractByEnvelope(common, g1, disjointPolys));

    std::auto_ptr<geom::Geometry> u(unionActual(g0Int.get(), g1Int.get()));
    disjointPolys.push_back(u.get());

    return geom::util::GeometryCombiner::combine(disjointPolys);
}

geom::Geometry*
CascadedPolygonUnion::extractByEnvelope(geom::Envelope const& env,
    geom::Geometry* geom, std::vector<geom::Geometry*>& disjointGeoms)
{
    std::vector<geom::Geometry*> intersectingGeoms;

    for (std::size_t i = 0; i < geom->getNumGeometries(); i++) {
        geom::Geometry* elem = const_cast<geom::Geometry*>(geom->getGeometryN(i));
        if (elem->getEnvelopeInternal()->intersects(env))
            intersectingGeoms.push_back(elem);
        else
            disjointGeoms.push_back(elem);
    }

    return geomFactory->buildGeometry(intersectingGeoms);
}

geom::Geometry*
CascadedPolygonUnion::unionActual(geom::Geometry* g0, geom::Geometry* g1)
{
    return restrictToPolygons(std::auto_ptr<geom::Geometry>(g0->Union(g1))).release();
}

std::auto_ptr<geom::Geometry>
CascadedPolygonUnion::restrictToPolygons(std::auto_ptr<geom::Geometry> g)
{
    using namespace geom;
    using namespace std;

    if ( dynamic_cast<Polygonal*>(g.get()) ) {
      return g;
    }

    Polygon::ConstVect polygons;
    util::PolygonExtracter::getPolygons(*g, polygons);

    if (polygons.size() == 1)
      return std::auto_ptr<Geometry>(polygons[0]->clone());

    typedef vector<Geometry *> GeomVect;

    Polygon::ConstVect::size_type n = polygons.size();
    GeomVect* newpolys = new GeomVect(n);
    for (Polygon::ConstVect::size_type i=0; i<n; ++i) {
        (*newpolys)[i] = polygons[i]->clone();
    }
    return auto_ptr<Geometry>(
      g->getFactory()->createMultiPolygon(newpolys)
    );

}

} // namespace geos.operation.union
} // namespace geos.operation
} // namespace geos


text:
//package ch.uzh.ddis.katts.query.source;
//
//import java.util.ArrayList;
//import java.util.List;
//
//import javax.xml.bind.annotation.XmlAccessType;
//import javax.xml.bind.annotation.XmlAccessorType;
//import javax.xml.bind.annotation.XmlAttribute;
//import javax.xml.bind.annotation.XmlElement;
//import javax.xml.bind.annotation.XmlElementWrapper;
//import javax.xml.bind.annotation.XmlRootElement;
//import javax.xml.bind.annotation.XmlTransient;
//
//import backtype.storm.topology.IRichBolt;
//import backtype.storm.topology.IRichSpout;
//import ch.uzh.ddis.katts.bolts.source.CachedFileTripleReader;
//import ch.uzh.ddis.katts.bolts.source.FileTripleReaderConfiguration;
//
///**
// * The BachedFileSource does basically the same as the FileSource bolt with the following differences:
// *

// *
It reads the whole file into main memory at boot time and does not read from disk during the runs. This is useful
// * for preventing disk lag from influencing time measurements.

// *
It supports parallelism by allowing the user to specify a blockSize variable. Each instance of the reader will
// * read #blockSize# number of lines before skipping #blockSize * parallelism# lines (other task instances read these
// * blocks). The offset (at which block each instance should start readin) will be computed during runtime.

// *

// *
// * @author "Lorenz Fischer" <lfischer@ifi.uzh.ch>
// *
// */
//@XmlRootElement(name="cachedFileSource")
//@XmlAccessorType(XmlAccessType.FIELD)
//public class CachedFileSourceConfiguration extends AbstractSource implements FileTripleReaderConfiguration {
//
//	/**
//	 * The number of tasks that should be instantiated for this bolt.
//	 */
//	@XmlAttribute(required = true)
//	private int parallelism;
//
//	/**
//	 * The block size is the number of lines that each task instance should read, before skipping #parallelism *
//	 * blockSize# lines, so other task instances can read these blocks.
//	 */
//	@XmlAttribute(required = true)
//	private int blockSize;
//
//	@XmlElementWrapper(name = "files")
//	@XmlElement(name = "file")
//	private List<File> files = new ArrayList<File>();
//
//	@Override
//	public IRichSpout getSpout() {
//		CachedFileTripleReader reader = new CachedFileTripleReader();
//		reader.setConfiguration(this);
//		return reader;
//	}
//
//	@Override
//	public boolean validate() {
//		return true;
//	}
//
//	public List<File> getFiles() {
//		return files;
//	}
//
//	public void setFiles(List<File> files) {
//		this.files = files;
//	}
//
//	/**
//	 * {@link CachedFileSourceConfiguration#parallelism}
//	 *
//	 * @return the parallelism
//	 */
//	public int getParallelism() {
//		return parallelism;
//	}
//
//	/**
//	 * {@link CachedFileSourceConfiguration#parallelism}
//	 *
//	 * @param parallelism
//	 *            the parallelism to set
//	 */
//	public void setParallelism(int parallelism) {
//		this.parallelism = parallelism;
//	}
//
//	/**
//	 * {@link CachedFileSourceConfiguration#blockSize}
//	 *
//	 * @return the blockSize
//	 */
//	public int getBlockSize() {
//		return blockSize;
//	}
//
//	/**
//	 * {@link CachedFileSourceConfiguration#blockSize}
//	 *
//	 * @param blockSize
//	 *            the blockSize to set
//	 */
//	public void setBlockSize(int blockSize) {
//		this.blockSize = blockSize;
//	}
//
//}


text:
package mil.nga.giat.geowave.adapter.vector.query;

import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.UUID;

import org.geotools.data.DataStore;
import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.FeatureWriter;
import org.geotools.data.Transaction;
import org.geotools.feature.SchemaException;
import org.geotools.filter.text.cql2.CQLException;
import org.junit.Before;
import org.junit.Test;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.PrecisionModel;

import mil.nga.giat.geowave.adapter.vector.BaseDataStoreTest;
import mil.nga.giat.geowave.adapter.vector.plugin.GeoWavePluginException;
import mil.nga.giat.geowave.adapter.vector.stats.FeatureTimeRangeStatistics;
import mil.nga.giat.geowave.adapter.vector.utils.DateUtilities;
import mil.nga.giat.geowave.core.geotime.store.query.TemporalRange;
import mil.nga.giat.geowave.core.index.ByteArrayId;

public class TemporalRangeTest extends
		BaseDataStoreTest
{
	DataStore dataStore;
	SimpleFeatureType type;
	GeometryFactory factory = new GeometryFactory(
			new PrecisionModel(
					PrecisionModel.FIXED));

	@Before
	public void setup()
			throws SchemaException,
			CQLException,
			IOException,
			GeoWavePluginException {
		dataStore = createDataStore();
		type = DataUtilities.createType(
				"geostuff",
				"geometry:Geometry:srid=4326,pop:java.lang.Long,pid:String,when:Date");

		dataStore.createSchema(type);
	}

	@Test
	public void test()
			throws ParseException,
			IOException {
		final Calendar gmt = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
		final Calendar local = Calendar.getInstance(TimeZone.getTimeZone("EDT"));
		local.setTimeInMillis(gmt.getTimeInMillis());
		final TemporalRange rGmt = new TemporalRange(
				gmt.getTime(),
				gmt.getTime());
		final TemporalRange rLocal = new TemporalRange(
				local.getTime(),
				local.getTime());
		rGmt.fromBinary(rGmt.toBinary());
		assertEquals(
				gmt.getTime(),
				rGmt.getEndTime());
		assertEquals(
				rLocal.getEndTime(),
				rGmt.getEndTime());
		assertEquals(
				rLocal.getEndTime().getTime(),
				rGmt.getEndTime().getTime());

		final Transaction transaction1 = new DefaultTransaction();

		final FeatureWriter<SimpleFeatureType, SimpleFeature> writer = dataStore.getFeatureWriter(
				type.getTypeName(),
				transaction1);
		final SimpleFeature newFeature = writer.next();
		newFeature.setAttribute(
				"pop",
				Long.valueOf(77));
		newFeature.setAttribute(
				"pid",
				UUID.randomUUID().toString());
		newFeature.setAttribute(
				"when",
				DateUtilities.parseISO("2005-05-19T19:32:56-04:00"));
		newFeature.setAttribute(
				"geometry",
				factory.createPoint(new Coordinate(
						43.454,
						28.232)));

		final FeatureTimeRangeStatistics stats = new FeatureTimeRangeStatistics(
				new ByteArrayId(
						"a"),
				"when");
		stats.entryIngested(
				null,
				newFeature);

		assertEquals(
				DateUtilities.parseISO("2005-05-19T23:32:56Z"),
				stats.asTemporalRange().getStartTime());
	}

}


text:
from .basic_operations import BasicOperations
from .primitive_operations import PrimitiveOperations
from .array_operations import ArrayOperations
from .dictionary_operations import DictionaryOperations
from .inheritance_operations import InheritanceOperations
from .polymorphism_operations import PolymorphismOperations
from .polymorphicrecursive_operations import PolymorphicrecursiveOperations
from .readonlyproperty_operations import ReadonlypropertyOperations

__all__ = [
    'BasicOperations',
    'PrimitiveOperations',
    'ArrayOperations',
    'DictionaryOperations',
    'InheritanceOperations',
    'PolymorphismOperations',
    'PolymorphicrecursiveOperations',
    'ReadonlypropertyOperations',
]


text:
<?php

namespace GulDmitry\Algorithms\Sorting;

/**
 * O(n log n)
 */
class MergeSort
{
    public function sort(array $raw, bool $ascDirection = true): array
    {
        $initialSize = count($raw);
        if ($initialSize === 1) {
            return $raw;
        }
        $mid = $initialSize / 2;
        $left = array_slice($raw, 0, $mid);
        $right = array_slice($raw, $mid);

        $leftMerged = $this->sort($left, $ascDirection);
        $rightMerged = $this->sort($right, $ascDirection);

        return $this->merge($leftMerged, $rightMerged, $ascDirection);
    }

    private function merge(array $left, array $right, bool $ascDirection = true): array
    {
        $sortedArray = [];

        while (count($left) > 0 && count($right) > 0) {
            if ($left[0] > $right[0]) {
                if ($ascDirection) {
                    $sortedArray[] = array_shift($right);
                } else {
                    $sortedArray[] = array_shift($left);
                }
            } elseif ($ascDirection) {
                $sortedArray[] = array_shift($left);
            } else {
                $sortedArray[] = array_shift($right);
            }
        }
        while (count($left) > 0) {
            $sortedArray[] = array_shift($left);
        }
        while (count($right) > 0) {
            $sortedArray[] = array_shift($right);
        }

        return $sortedArray;
    }
}


text:
package com.microsoft.applicationinsights.sample;

import com.microsoft.applicationinsights.TelemetryClient;
import com.microsoft.applicationinsights.TelemetryConfiguration;
import com.microsoft.applicationinsights.sample.plugins.GitBuildInfoContextInitializer;

import java.io.IOException;

/**
 * Created by gupele on 7/15/2015.
 */
public class AiCustomContextInitializer {
    public static void main(String[] args) throws IOException {
        System.out.println("This program sends application insights telemetry event using custom context initializer.");

        TelemetryClient appInsights = new TelemetryClient();

        if (args.length > 0) {
            appInsights.getContext().setInstrumentationKey(args[0]);
        }
        appInsights.getContext().setInstrumentationKey("2ab4ffa8-5d7d-4bb0-bf14-33d9c556be96");

        String iKey = appInsights.getContext().getInstrumentationKey();
        if (iKey == null) {
            System.out.println("Error: no iKey set in ApplicationInsights.xml or as a parameter for this program.");
            return;
        }

        GitBuildInfoContextInitializer customContextInitializer = new GitBuildInfoContextInitializer();
        TelemetryConfiguration.getActive().getContextInitializers().add(customContextInitializer);
        System.out.println("Custom context initializer added to configuration");

        // Trace telemetry
        appInsights.trackTrace("Things seem to be going well");
        System.out.println("[3] Trace                 -- text=\"Things seem to be going well\"");

        System.out.println();
        System.out.println("Press any key to exit");
        System.in.read();
    }

    // endregion Core
}


text:
package io.restassured.module.mockmvc.internal;

import io.restassured.config.LogConfig;
import io.restassured.internal.RestAssuredResponseOptionsImpl;
import io.restassured.internal.common.assertion.AssertParameter;
import io.restassured.internal.log.LogRepository;
import io.restassured.module.mockmvc.response.MockMvcResponse;
import io.restassured.module.mockmvc.response.ValidatableMockMvcResponse;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;

public class MockMvcRestAssuredResponseImpl extends RestAssuredResponseOptionsImpl<MockMvcResponse> implements MockMvcResponse {

    private final ResultActions resultActions;
    private final LogRepository logRepository;

    public MockMvcRestAssuredResponseImpl(ResultActions resultActions, LogRepository logRepository) {
        AssertParameter.notNull(resultActions, ResultActions.class);
        AssertParameter.notNull(logRepository, LogRepository.class);
        this.resultActions = resultActions;
        this.logRepository = logRepository;
    }

    public ValidatableMockMvcResponse then() {
        ValidatableMockMvcResponseImpl response = new ValidatableMockMvcResponseImpl(resultActions, getContentType(), getRpr(), getConfig(), this, this, logRepository);
        LogConfig logConfig = getConfig().getLogConfig();
        if (logConfig.isLoggingOfRequestAndResponseIfValidationFailsEnabled()) {
            response.log().ifValidationFails(logConfig.logDetailOfRequestAndResponseIfValidationFails(), logConfig.isPrettyPrintingEnabled());
        }
        return response;
    }

    public MvcResult mvcResult() {
        return resultActions.andReturn();
    }

    public MvcResult getMvcResult() {
        return mvcResult();
    }

    public MockHttpServletResponse mockHttpServletResponse() {
        return mvcResult().getResponse();
    }

    public MockHttpServletResponse getMockHttpServletResponse() {
        return mockHttpServletResponse();
    }
}


text:
ALTER TABLE secret ADD COLUMN "type" text;

UPDATE secret SET "type" = 'deprecated';

ALTER TABLE secret ALTER COLUMN "type" SET NOT NULL;


text:
/**
 * @file
 * @author zdying
 */
var Compiler = require('./Compiler');
var _global = require('../global');

program
    .option('-o, --open [open]', 'open in browser, one of: chrome|firefox|safari|opera', /^(chrome|firefox|safari|opera)$/)
    .option('-p, --port <port>', 'service port', 8800)
    .option('-r, --registry <registry>', 'npm registry address')
    .option('-d, --debug', 'print debug log')
    .option('-s, --sync-conf <syncConf>', 'custom sync config')
    //TODO add this next version
    // .option('-U, --uglify', 'uglify javascript')
    //TODO add this next version
    // .option('-e, --extract-css', 'extract css from javascript')
    .option('-D, --detail', 'print debug and error detail log')
    // .option('-w, --workspace <workspace>', 'workspace', process.cwd())
    .option('-x, --proxy', 'start the proxy server')
    .option('-t, --type <type>', 'project type: one of react|react-redux|es6|vue|normal|empty', /^(react|react-redux|es6|vue|normal|empty)$/, 'normal')
    .option('--no-color', 'disable log color')
    .option('--no-hot-reload', 'disable hot reload')
    .option('--log-time', 'display log time')
    .option('--https', 'start https server')
    .option('--ssl-key <sslKey>', 'ssl key file')
    .option('--ssl-cert <sslCert>', 'ssl cert file');

program.parse(process.argv);

var compiler = null;

var publish = function(data){
    process.send({
        action: 'hmr',
        data: data
    })
};

function compile(conf){
    // projectName, root, env
    if(!compiler){
        compiler = new Compiler(conf.project, conf.root, conf.env, publish);
    }else{
    }

    // compiler.compileDLL(false, conf, function(err){
    //     log.info('[' + process.pid + ']', 'dll compile finish', err);
    //     compiler.compile(conf, function(err, stat){
    //         log.info('[' + process.pid + ']', 'compile finish', err, stat);
    //         process.send({action: 'compiler-finish', cbkId: conf.cbk})
    //     })
    // });
    compiler.compile(conf, function(err, stat){
        log.info('[' + process.pid + ']', 'compile finish', err, stat);
        process.send({action: 'compiler-finish', cbkId: conf.cbk})
    })
}

process.on('message', function(conf){
    var now = Date.now();

    __hii__.originCwd = conf.originCwd;

    log.debug('[' + process.pid + ']', 'child process receive message', now, 'delay:', now - conf.date);

    compile(conf);
});


text:
"""Problem 43
09 May 2003

Find the sum of all pandigital numbers with an unusual sub-string
divisibility property.

The number, 1406357289, is a 0 to 9 pandigital number because it is
made up of each of the digits 0 to 9 in some order, but it also has
a rather interesting sub-string divisibility property.

Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this
way, we note the following:

d2d3d4=406 is divisible by 2
d3d4d5=063 is divisible by 3
d4d5d6=635 is divisible by 5
d5d6d7=357 is divisible by 7
d6d7d8=572 is divisible by 11
d7d8d9=728 is divisible by 13
d8d9d10=289 is divisible by 17

Find the sum of all 0 to 9 pandigital numbers with this property.
"""

from eulerlib import generateStringPermutations, timedRun

# NOT_TO_DO: maybe create a permutations generator, and test 1 by 1
# to avoid using so much memory???
# INSTEAD: check euler43b =D

def euler43():
    """Very slow solution for problem 43 of Project Euler."""
    print("Generating permutations...", end="")
    pandigitals = generateStringPermutations("0123456789")
    print("done")
    divisors = [1, 2, 3, 5, 7, 11, 13, 17]

    total = 0
    for p in pandigitals:
        ok = True
        for i in range(0, 8):
            num = int(p[i:i+3])
            if num % divisors[i] != 0:
                ok = False
                break
        if ok:
            total += int(p)
            print(p)
    print("Total =", total)

#Another possibility is:
#  to generate only the multiples of 17 with 3 digits
#  then generate only the multiples of 13 with 3 digits and with the
#    the last 2 digits = first 2 digits of the 17 multiples
#  ...
#  generate all multiples of 2 that have
#    the last 2 digits = first 2 digits of the remaining 3 multiples

def genMultiplesStr(factor):
    """Generate a list with all multiples of factor up to 1000 normalized
    to 3 digit strings."""
    multiples = []
    for n in range(factor, 1000, factor):
        s = ("00" + str(n))[-3:]
        multiples.append(s)
        n += factor
    return multiples

def mergeMultiples(oldlist, newlist):
    """Creates a new list only with members of oldist whose first 2 digits
    match with the last 2 digits of the newlist."""
    candidates = {}
    for old in oldlist:
        for new in newlist:
            if old[:2] == new[-2:]:
                s = new[0] + old
                candidates[s] = 1
    return list(candidates.keys())

def isPandigital10(s):
    """Check if number is pandigital from 0-9, i.e. that it has all digits
    from 0 to 9."""
    if len(s) != 10:
        return False
    for i in range(0, 10):
        if s.find(str(i)) == -1:
            return False
    return True

def euler43b():
    """A better solution for problem 43 of Project Euler"""
    # Generates numbers only with valid multiples
    candidates = genMultiplesStr(17)
    # TODO: The time consuming part is for factor = 1
    # Should find a way to take the list generated after factor = 2,
    # remove all the numbers with repeating factors,
    # add the remaining digit to the number in the remaining list
    # voilà!
    # Guess this would take less than a second
    for factor in [13, 11, 7, 5, 3, 2, 1]:
        newlist = genMultiplesStr(factor)
        candidates = mergeMultiples(candidates, newlist)
    # Sum only the pandigitals 0-9
    total = 0
    for c in candidates:
        if isPandigital10(c):
            total += int(c)
    print("Total =", total)

if __name__ == "__main__":
    timedRun(euler43b)


text:
// Code generated by go-swagger; DO NOT EDIT.

package cluster

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"context"
	"net/http"
	"time"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/runtime"
	cr "github.com/go-openapi/runtime/client"
	"github.com/go-openapi/strfmt"
	"github.com/go-openapi/swag"
)

// NewClusterNtpKeysCollectionGetParams creates a new ClusterNtpKeysCollectionGetParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewClusterNtpKeysCollectionGetParams() *ClusterNtpKeysCollectionGetParams {
	return &ClusterNtpKeysCollectionGetParams{
		timeout: cr.DefaultTimeout,
	}
}

// NewClusterNtpKeysCollectionGetParamsWithTimeout creates a new ClusterNtpKeysCollectionGetParams object
// with the ability to set a timeout on a request.
func NewClusterNtpKeysCollectionGetParamsWithTimeout(timeout time.Duration) *ClusterNtpKeysCollectionGetParams {
	return &ClusterNtpKeysCollectionGetParams{
		timeout: timeout,
	}
}

// NewClusterNtpKeysCollectionGetParamsWithContext creates a new ClusterNtpKeysCollectionGetParams object
// with the ability to set a context for a request.
func NewClusterNtpKeysCollectionGetParamsWithContext(ctx context.Context) *ClusterNtpKeysCollectionGetParams {
	return &ClusterNtpKeysCollectionGetParams{
		Context: ctx,
	}
}

// NewClusterNtpKeysCollectionGetParamsWithHTTPClient creates a new ClusterNtpKeysCollectionGetParams object
// with the ability to set a custom HTTPClient for a request.
func NewClusterNtpKeysCollectionGetParamsWithHTTPClient(client *http.Client) *ClusterNtpKeysCollectionGetParams {
	return &ClusterNtpKeysCollectionGetParams{
		HTTPClient: client,
	}
}

/*
ClusterNtpKeysCollectionGetParams contains all the parameters to send to the API endpoint

	for the cluster ntp keys collection get operation.

	Typically these are written to a http.Request.
*/
type ClusterNtpKeysCollectionGetParams struct {

	/* DigestType.

	   Filter by digest_type
	*/
	DigestTypeQueryParameter *string

	/* Fields.

	   Specify the fields to return.
	*/
	FieldsQueryParameter []string

	/* ID.

	   Filter by id
	*/
	IDQueryParameter *int64

	/* MaxRecords.

	   Limit the number of records returned.
	*/
	MaxRecordsQueryParameter *int64

	/* OrderBy.

	   Order results by specified fields and optional [asc|desc] direction. Default direction is 'asc' for ascending.
	*/
	OrderByQueryParameter []string

	/* ReturnRecords.

	   The default is true for GET calls.  When set to false, only the number of records is returned.

	   Default: true
	*/
	ReturnRecordsQueryParameter *bool

	/* ReturnTimeout.

	   The number of seconds to allow the call to execute before returning.  When iterating over a collection, the default is 15 seconds.  ONTAP returns earlier if either max records or the end of the collection is reached.

	   Default: 15
	*/
	ReturnTimeoutQueryParameter *int64

	/* Value.

	   Filter by value
	*/
	ValueQueryParameter *string

	timeout    time.Duration
	Context    context.Context
	HTTPClient *http.Client
}

// WithDefaults hydrates default values in the cluster ntp keys collection get params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *ClusterNtpKeysCollectionGetParams) WithDefaults() *ClusterNtpKeysCollectionGetParams {
	o.SetDefaults()
	return o
}

// SetDefaults hydrates default values in the cluster ntp keys collection get params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *ClusterNtpKeysCollectionGetParams) SetDefaults() {
	var (
		returnRecordsQueryParameterDefault = bool(true)

		returnTimeoutQueryParameterDefault = int64(15)
	)

	val := ClusterNtpKeysCollectionGetParams{
		ReturnRecordsQueryParameter: &returnRecordsQueryParameterDefault,
		ReturnTimeoutQueryParameter: &returnTimeoutQueryParameterDefault,
	}

	val.timeout = o.timeout
	val.Context = o.Context
	val.HTTPClient = o.HTTPClient
	*o = val
}

// WithTimeout adds the timeout to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) WithTimeout(timeout time.Duration) *ClusterNtpKeysCollectionGetParams {
	o.SetTimeout(timeout)
	return o
}

// SetTimeout adds the timeout to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) SetTimeout(timeout time.Duration) {
	o.timeout = timeout
}

// WithContext adds the context to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) WithContext(ctx context.Context) *ClusterNtpKeysCollectionGetParams {
	o.SetContext(ctx)
	return o
}

// SetContext adds the context to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) SetContext(ctx context.Context) {
	o.Context = ctx
}

// WithHTTPClient adds the HTTPClient to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) WithHTTPClient(client *http.Client) *ClusterNtpKeysCollectionGetParams {
	o.SetHTTPClient(client)
	return o
}

// SetHTTPClient adds the HTTPClient to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) SetHTTPClient(client *http.Client) {
	o.HTTPClient = client
}

// WithDigestTypeQueryParameter adds the digestType to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) WithDigestTypeQueryParameter(digestType *string) *ClusterNtpKeysCollectionGetParams {
	o.SetDigestTypeQueryParameter(digestType)
	return o
}

// SetDigestTypeQueryParameter adds the digestType to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) SetDigestTypeQueryParameter(digestType *string) {
	o.DigestTypeQueryParameter = digestType
}

// WithFieldsQueryParameter adds the fields to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) WithFieldsQueryParameter(fields []string) *ClusterNtpKeysCollectionGetParams {
	o.SetFieldsQueryParameter(fields)
	return o
}

// SetFieldsQueryParameter adds the fields to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) SetFieldsQueryParameter(fields []string) {
	o.FieldsQueryParameter = fields
}

// WithIDQueryParameter adds the id to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) WithIDQueryParameter(id *int64) *ClusterNtpKeysCollectionGetParams {
	o.SetIDQueryParameter(id)
	return o
}

// SetIDQueryParameter adds the id to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) SetIDQueryParameter(id *int64) {
	o.IDQueryParameter = id
}

// WithMaxRecordsQueryParameter adds the maxRecords to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) WithMaxRecordsQueryParameter(maxRecords *int64) *ClusterNtpKeysCollectionGetParams {
	o.SetMaxRecordsQueryParameter(maxRecords)
	return o
}

// SetMaxRecordsQueryParameter adds the maxRecords to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) SetMaxRecordsQueryParameter(maxRecords *int64) {
	o.MaxRecordsQueryParameter = maxRecords
}

// WithOrderByQueryParameter adds the orderBy to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) WithOrderByQueryParameter(orderBy []string) *ClusterNtpKeysCollectionGetParams {
	o.SetOrderByQueryParameter(orderBy)
	return o
}

// SetOrderByQueryParameter adds the orderBy to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) SetOrderByQueryParameter(orderBy []string) {
	o.OrderByQueryParameter = orderBy
}

// WithReturnRecordsQueryParameter adds the returnRecords to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) WithReturnRecordsQueryParameter(returnRecords *bool) *ClusterNtpKeysCollectionGetParams {
	o.SetReturnRecordsQueryParameter(returnRecords)
	return o
}

// SetReturnRecordsQueryParameter adds the returnRecords to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) SetReturnRecordsQueryParameter(returnRecords *bool) {
	o.ReturnRecordsQueryParameter = returnRecords
}

// WithReturnTimeoutQueryParameter adds the returnTimeout to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) WithReturnTimeoutQueryParameter(returnTimeout *int64) *ClusterNtpKeysCollectionGetParams {
	o.SetReturnTimeoutQueryParameter(returnTimeout)
	return o
}

// SetReturnTimeoutQueryParameter adds the returnTimeout to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) SetReturnTimeoutQueryParameter(returnTimeout *int64) {
	o.ReturnTimeoutQueryParameter = returnTimeout
}

// WithValueQueryParameter adds the value to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) WithValueQueryParameter(value *string) *ClusterNtpKeysCollectionGetParams {
	o.SetValueQueryParameter(value)
	return o
}

// SetValueQueryParameter adds the value to the cluster ntp keys collection get params
func (o *ClusterNtpKeysCollectionGetParams) SetValueQueryParameter(value *string) {
	o.ValueQueryParameter = value
}

// WriteToRequest writes these params to a swagger request
func (o *ClusterNtpKeysCollectionGetParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {

	if err := r.SetTimeout(o.timeout); err != nil {
		return err
	}
	var res []error

	if o.DigestTypeQueryParameter != nil {

		// query param digest_type
		var qrDigestType string

		if o.DigestTypeQueryParameter != nil {
			qrDigestType = *o.DigestTypeQueryParameter
		}
		qDigestType := qrDigestType
		if qDigestType != "" {

			if err := r.SetQueryParam("digest_type", qDigestType); err != nil {
				return err
			}
		}
	}

	if o.FieldsQueryParameter != nil {

		// binding items for fields
		joinedFields := o.bindParamFields(reg)

		// query array param fields
		if err := r.SetQueryParam("fields", joinedFields...); err != nil {
			return err
		}
	}

	if o.IDQueryParameter != nil {

		// query param id
		var qrID int64

		if o.IDQueryParameter != nil {
			qrID = *o.IDQueryParameter
		}
		qID := swag.FormatInt64(qrID)
		if qID != "" {

			if err := r.SetQueryParam("id", qID); err != nil {
				return err
			}
		}
	}

	if o.MaxRecordsQueryParameter != nil {

		// query param max_records
		var qrMaxRecords int64

		if o.MaxRecordsQueryParameter != nil {
			qrMaxRecords = *o.MaxRecordsQueryParameter
		}
		qMaxRecords := swag.FormatInt64(qrMaxRecords)
		if qMaxRecords != "" {

			if err := r.SetQueryParam("max_records", qMaxRecords); err != nil {
				return err
			}
		}
	}

	if o.OrderByQueryParameter != nil {

		// binding items for order_by
		joinedOrderBy := o.bindParamOrderBy(reg)

		// query array param order_by
		if err := r.SetQueryParam("order_by", joinedOrderBy...); err != nil {
			return err
		}
	}

	if o.ReturnRecordsQueryParameter != nil {

		// query param return_records
		var qrReturnRecords bool

		if o.ReturnRecordsQueryParameter != nil {
			qrReturnRecords = *o.ReturnRecordsQueryParameter
		}
		qReturnRecords := swag.FormatBool(qrReturnRecords)
		if qReturnRecords != "" {

			if err := r.SetQueryParam("return_records", qReturnRecords); err != nil {
				return err
			}
		}
	}

	if o.ReturnTimeoutQueryParameter != nil {

		// query param return_timeout
		var qrReturnTimeout int64

		if o.ReturnTimeoutQueryParameter != nil {
			qrReturnTimeout = *o.ReturnTimeoutQueryParameter
		}
		qReturnTimeout := swag.FormatInt64(qrReturnTimeout)
		if qReturnTimeout != "" {

			if err := r.SetQueryParam("return_timeout", qReturnTimeout); err != nil {
				return err
			}
		}
	}

	if o.ValueQueryParameter != nil {

		// query param value
		var qrValue string

		if o.ValueQueryParameter != nil {
			qrValue = *o.ValueQueryParameter
		}
		qValue := qrValue
		if qValue != "" {

			if err := r.SetQueryParam("value", qValue); err != nil {
				return err
			}
		}
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

// bindParamClusterNtpKeysCollectionGet binds the parameter fields
func (o *ClusterNtpKeysCollectionGetParams) bindParamFields(formats strfmt.Registry) []string {
	fieldsIR := o.FieldsQueryParameter

	var fieldsIC []string
	for _, fieldsIIR := range fieldsIR { // explode []string

		fieldsIIV := fieldsIIR // string as string
		fieldsIC = append(fieldsIC, fieldsIIV)
	}

	// items.CollectionFormat: "csv"
	fieldsIS := swag.JoinByFormat(fieldsIC, "csv")

	return fieldsIS
}

// bindParamClusterNtpKeysCollectionGet binds the parameter order_by
func (o *ClusterNtpKeysCollectionGetParams) bindParamOrderBy(formats strfmt.Registry) []string {
	orderByIR := o.OrderByQueryParameter

	var orderByIC []string
	for _, orderByIIR := range orderByIR { // explode []string

		orderByIIV := orderByIIR // string as string
		orderByIC = append(orderByIC, orderByIIV)
	}

	// items.CollectionFormat: "csv"
	orderByIS := swag.JoinByFormat(orderByIC, "csv")

	return orderByIS
}


text:
package com.lethalskillzz.baker.utils;

import com.lethalskillzz.bakingapp.BuildConfig;

import timber.log.Timber;

/**
 * Created by ibrahimabdulkadir on 20/06/2017.
 */

public class AppLogger {

    public static void init() {
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }
    }

    public static void d(String s, Object... objects) {
        Timber.d(s, objects);
    }

    public static void d(Throwable throwable, String s, Object... objects) {
        Timber.d(throwable, s, objects);
    }

    public static void i(String s, Object... objects) {
        Timber.i(s, objects);
    }

    public static void i(Throwable throwable, String s, Object... objects) {
        Timber.i(throwable, s, objects);
    }

    public static void w(String s, Object... objects) {
        Timber.w(s, objects);
    }

    public static void w(Throwable throwable, String s, Object... objects) {
        Timber.w(throwable, s, objects);
    }

    public static void e(String s, Object... objects) {
        Timber.e(s, objects);
    }

    public static void e(Throwable throwable, String s, Object... objects) {
        Timber.e(throwable, s, objects);
    }

}


text:
const c = function(...args: any[]) {console.log.apply(console,arguments)};
import * as fs from 'fs'
import * as _ from 'lodash'
import Bluebird = require('bluebird');
var Promise = Bluebird.Promise;
import uuid = require('node-uuid');
const fS = Promise.promisifyAll(fs);
import path = require('path');
// const base = "../../lua/world_admin/";

// import * as leibniz from '../constants/admin_interfaces_001'
// let interfaces = {}
// _.assign(interfaces, leibniz);
// const i = interfaces;
// import * as aM from  '../constants/admin_methods.ts';

// let zz = fs.readFileSync(path.resolve(__dirname, '../../lua/test.lua'));q
// c('zz', zz.toString());

var api__000 =  function (message: any, Orange: any) {
    // if this works do them all like this in the sense of trying to get all the protocols standardised
    // single source of truth way.
    // Orange.defineCommand('test', {
    //     lua: fs.readFileSync(path.resolve(__dirname, '../../lua/test.lua'))
    // });
    // Orange.defineCommand(aM.consumate_game, {
    //     lua: fs.readFileSync(path.resolve(__dirname, '../../lua/world_admin/consumate_game.lua'))
    // });
    Orange.defineCommand('consumate_game', {
        lua: fs.readFileSync(path.resolve(__dirname, '../../lua/world_admin/consumate_game.lua'))
    });
    Orange.defineCommand('init_game', {
        lua: fs.readFileSync(path.resolve(__dirname, '../../lua/world_admin/init_game_003.lua'))
    });
    Orange.defineCommand('init_season', {
        lua: fs.readFileSync(path.resolve(__dirname, '../../lua/world_admin/init_season_003.lua'))
    });
    Orange.defineCommand('init_team', {
        lua: fs.readFileSync(path.resolve(__dirname, '../../lua/world_admin/init_team.lua'))
    });
    Orange.defineCommand('init_league', {
        lua: fs.readFileSync(path.resolve(__dirname, '../../lua/world_admin/init_league_003.lua'))
    });
    return Orange;
};

var sunspot = function (rangeYellow, event_wrapper_func) {

    const consumate_game_005 = function (ticket, cb) {
        let str_payload = JSON.stringify(_.assign(ticket, event_wrapper_func('consumate_game'));
        rangeYellow.consumate_game(1, str_payload)
        .then((res)=> {
            cb(res);
        })
        .error((err) => {
            cb(err);
        })
    };

    const init_game_005 = function (ticket, cb) {
        let temp_000 = _.assign(ticket, event_wrapper_func('init_game'));
        // if lodash docs say can chain objects into the assign
        // call then can get rid of the temp var above and just
        // assign twice to ticket in the same call.
        let str_payload = JSON.stringify(_.assign(temp_000, {
            gameZ: uuid.v4()
        }));
        rangeYellow.init_game(1, str_payload)
        .then((res) => {
            cb(JSON.parse(res));
        })
        .error((err) => {
            cb(err);
        })
    };

    const init_season_005 = function(ticket, cb) {
        let str_payload = JSON.stringify(_.assign(ticket, {
            seasonZ: uuid.v4()
        }));
        rangeYellow.init_season(1, str_payload)
        .then((res)=> {
            let res2 = JSON.parse(res);
            cb(res2);
        })
        .error((err)=>{
            cb(err);
        })
    };

    const init_team_005 = function(ticket, cb) {
        let str_payload = JSON.stringify(_.assign(ticket, {
            timestamp: Date.now(),
            teamZ: uuid.v4()
        }));
        rangeYellow.init_team(1, str_payload)
        .then((res)=> {
            let res2 = JSON.parse(res);
            cb(res2);
        })
        .error((err)=>{
            cb(err);
        })
    };

    // because we generate the leagueZ here in this layer
    const init_league_005 = function (ticket, cb) {
        let str_payload = JSON.stringify(_.assign(ticket, {
            event_type: 'init_league',
            eventZ: uuid.v4(), // why not? might be useful
            time_stamp: Date.now(),
            leagueZ: uuid.v4()
        }));
        rangeYellow.init_league(1, str_payload)
        .then((res)=> {
            let res2 = JSON.parse(res);
            cb(res2);
        })
        .error((err) => {
            cb(err);
        })
    };

    return {
        consumate_game: consumate_game_005,
        init_game: init_game_005,
        init_season: init_season_005,
        init_team: init_team_005,
        init_league: init_league_005,
    }
};

export default function (message: any, Orange: any) {
    const event_wrapper_obj_000 = function (event_type: string) {
        return {
            event_type: event_type,
            eventZ: uuid.v4(),
            time_stamp: Date.now()
        }
    };
    var rangeYellow = Promise.promisifyAll(api__000("magnanimity", Orange));
    return sunspot(rangeYellow, event_wrapper_obj_000);
};


text:
/*
 * Created on Jun 3, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package org.tolweb.tapestry;

import java.util.Arrays;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

import org.apache.hivemind.util.PropertyUtils;
import org.apache.tapestry.IPage;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.PageRedirectException;
import org.apache.tapestry.components.Block;
import org.apache.tapestry.event.PageBeginRenderListener;
import org.apache.tapestry.event.PageEvent;
import org.tolweb.hibernate.MappedAccessoryPage;
import org.tolweb.hibernate.MappedNode;
import org.tolweb.hibernate.MappedPage;
import org.tolweb.hibernate.Portfolio;
import org.tolweb.hibernate.PortfolioPage;
import org.tolweb.hibernate.PortfolioSection;
import org.tolweb.misc.ReorderHelper;
import org.tolweb.misc.URLBuilder;
import org.tolweb.tapestry.injections.MiscInjectable;
import org.tolweb.tapestry.injections.PageInjectable;
import org.tolweb.treegrow.main.NodeImage;

/**
 * @author dmandel
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public abstract class TreehouseEditPortfolio extends AbstractTreehouseEditingPage implements PageBeginRenderListener,
		PageInjectable, MiscInjectable {
    public abstract Integer getNumNewFields();
    public abstract void setNumNewFields(Integer value);
    public abstract PortfolioSection getCurrentSection();
    public abstract PortfolioPage getCurrentPage();
    public abstract int getSectionIndex();
    public abstract int getPageIndex();
    public abstract String getMoveUpPageIndex();
    public abstract String getMoveDownPageIndex();
    public abstract String getDeletePageIndex();
    public abstract Integer getMoveUpSectionIndex();
    public abstract Integer getMoveDownSectionIndex();
    public abstract Integer getDeleteSectionIndex();
    public abstract PortfolioSection getSectionToAddPageTo();
    public abstract void setSectionToAddPageTo(PortfolioSection section);
    public abstract PortfolioSection getSavedSection();
    public abstract void setSavedSection(PortfolioSection section);
    public abstract PortfolioPage getPageToAddImageTo();
    public abstract void setPageToAddImageTo(PortfolioPage value);
    public abstract PortfolioPage getPageToDeleteImageFrom();
    public abstract PortfolioPage getSavedPage();
    public abstract void setSavedPage(PortfolioPage value);

    public static final String PROGRESS_PROPERTY = "portfolioProgress";
    private static final String SEPARATOR = ",";
    private static final int MOVE_UP = 0;
    private static final int MOVE_DOWN = 1;
    private static final int DELETE = 2;

    public int getStepNumber() {
        if (getIsTeacherResource() && !getIsOther()) {
            return 7;
        } else {
            return 6;
        }
    }

	public String getProgressMethodPropertyName() {
	    return PROGRESS_PROPERTY;
	}

	@SuppressWarnings("unchecked")
	public boolean doAdditionalFormProcessing(IRequestCycle cycle) {
	    if (getNumNewFields() != null) {
	        // Go ahead and create a few new sections.
		    ReorderHelper helper = getReorderHelper();
		    SortedSet sections = getTreehouse().getPortfolio().getSections();
		    int currentSize = sections.size();
		    int numSections = getNumNewFields().intValue();
		    for (int i = 0; i < numSections; i++) {
		        PortfolioSection newSection = constructNewSection();
		        helper.addToSet(sections, newSection);
		    }
		    String anchorName = getSectionAnchorName(currentSize);
		    setSelectedAnchor(anchorName);
		    setNumNewFields(null);
	    } else if (getMoveUpPageIndex() != null) {
	        movePageUp();
	    } else if (getMoveDownPageIndex() != null) {
	        movePageDown();
	    } else if (getDeletePageIndex() != null) {
	        deletePage();
	    } else if (getMoveUpSectionIndex() != null) {
	        moveSectionUp();
	    } else if (getMoveDownSectionIndex() != null) {
	        moveSectionDown();
	    } else if (getDeleteSectionIndex() != null) {
	        deleteSection();
	    } else if (getSectionToAddPageTo() != null) {
	        setSavedSection(getSectionToAddPageTo());
	        setOtherEditPageName("TreehousePortfolioSearchPage");
	    } else if (getPageToAddImageTo() != null) {
	        setSavedPage(getPageToAddImageTo());
            IPage searchPage = cycle.getPage("PortfolioPageImageSearch");
            PropertyUtils.write(searchPage, "returnPageName", getPageName());
            throw new PageRedirectException(searchPage);
        } else if (getPageToDeleteImageFrom() != null) {
            PortfolioPage page = getPageToDeleteImageFrom();
            page.setImageId(null);
        }
	    return true;
	}

	@SuppressWarnings("unchecked")
	public void doSave() {
	    if (getPortfolio() != null) {
		    // create a new set to force a delete followed by a save -- hibernate issue
		    getPortfolio().setSections(new TreeSet(getPortfolio().getSections()));
		    // set all the page collections to new instances to do the same for the portfolio pages
		    for (Iterator iter = getPortfolio().getSections().iterator(); iter.hasNext();) {
	            PortfolioSection section = (PortfolioSection) iter.next();
	            section.setPages(new TreeSet(section.getPages()));
	        }
	    }
	    super.doSave();
	}

	protected void goToOtherEditPageName(IRequestCycle cycle) {
	    if (getOtherEditPageName() != null && getOtherEditPageName().equals("TreehousePortfolioSearchPage")) {
	        TreehousePortfolioSearchPage searchPage = (TreehousePortfolioSearchPage) cycle.getPage("TreehousePortfolioSearchPage");
	        searchPage.setReturnPageName(getPageName());
	        searchPage.setDontCheckPermissions(!getCheckPermissionsForSearch());
	        searchPage.setEditedObjectType(getEditTypeName());
	        cycle.activate(searchPage);
	    } else {
	        super.goToOtherEditPageName(cycle);
	    }
	}

	protected boolean getCheckPermissionsForSearch() {
	    return true;
	}

	protected String getEditTypeName() {
	    return "Portfolio";
	}

	public String getSectionAnchorName(int index) {
	    return "linksection" + index;
	}

	public String getPageAnchorName(int sectionIndex, int pageIndex) {
	    return "section" + sectionIndex + "page" + pageIndex;
	}

	private void moveSectionUp() {
	    ReorderHelper helper = getReorderHelper();
	    int index = getMoveUpSectionIndex().intValue();
	    helper.doSwap(index, true, getPortfolio().getSections());
	    setSelectedAnchor(getSectionAnchorName(index - 1));
	}

	private void moveSectionDown() {
	    ReorderHelper helper = getReorderHelper();
	    int index = getMoveDownSectionIndex().intValue();
	    helper.doSwap(index, false, getPortfolio().getSections());
	    setSelectedAnchor(getSectionAnchorName(index + 1));
	}

	private void deleteSection() {
	    ReorderHelper helper = getReorderHelper();
	    int index = getDeleteSectionIndex().intValue();
	    helper.removeObject(index, getPortfolio().getSections());
	    setSelectedAnchor(getSectionAnchorName(index - 1));
	}

	private void movePageUp() {
	    doSectionAndPageWork(getMoveUpPageIndex(), MOVE_UP);
	}

	private void movePageDown() {
	    doSectionAndPageWork(getMoveDownPageIndex(), MOVE_DOWN);
	}

	private void deletePage() {
	    doSectionAndPageWork(getDeletePageIndex(), DELETE);
	}

	/**
	 * decodes the index to locate the correct section and page to work on
	 * @param index
	 * @param opType TODO
	 * @return
	 */
	private void doSectionAndPageWork(String index, int opType) {
	    String[] pieces = index.split(SEPARATOR);
	    // First index is the section index
	    int sectionIndex = Integer.parseInt(pieces[0]);
	    ReorderHelper helper = getReorderHelper();
	    PortfolioSection section = (PortfolioSection) helper.getObject(sectionIndex, getPortfolio().getSections());
	    int pageIndex = Integer.parseInt(pieces[1]);
	    String selectedAnchor = "";
	    if (opType == MOVE_UP) {
	        helper.doSwap(pageIndex, true, section.getPages());
	        pageIndex--;
	        selectedAnchor = getPageAnchorName(sectionIndex, pageIndex);
	    } else if (opType == MOVE_DOWN) {
	        helper.doSwap(pageIndex, false, section.getPages());
	        pageIndex++;
	        selectedAnchor = getPageAnchorName(sectionIndex, pageIndex);
	    } else if (opType == DELETE) {
	        helper.removeObject(pageIndex, section.getPages());
	        if (section.getPages().size() == 0) {
	            selectedAnchor = getSectionAnchorName(sectionIndex);
	        } else {
	            pageIndex = pageIndex == 0 ? 0 : pageIndex - 1;
	            selectedAnchor = getPageAnchorName(sectionIndex, pageIndex);
	        }
	    }
	    setSelectedAnchor(selectedAnchor);
	}

	private PortfolioSection constructNewSection() {
	    PortfolioSection section = new PortfolioSection();
	    section.setTitle("New portfolio section");
	    return section;
	}

    public void pageBeginRender(PageEvent event) {
        super.pageBeginRender(event);
    }

    public Portfolio getPortfolio() {
        return getTreehouse().getPortfolio();
    }

    @SuppressWarnings("unchecked")
    public boolean getHasAnyPages() {
        SortedSet sections = getPortfolio().getSections();
        return sections.size() > 1 || ((PortfolioSection) sections.first()).getPages().size() > 0;
    }

    public boolean getPageCanMoveUp() {
        return getReorderHelper().getCanMoveLeft(getCurrentSection().getPages(), getPageIndex());
    }

    public boolean getPageCanMoveDown() {
        return getReorderHelper().getCanMoveRight(getCurrentSection().getPages(), getPageIndex());
    }

    public boolean getPageCanMoveBoth() {
        return getReorderHelper().getCanMoveBoth(getCurrentSection().getPages(), getPageIndex());
    }

    public boolean getSectionCanMoveUp() {
        return getReorderHelper().getCanMoveLeft(getPortfolio().getSections(), getSectionIndex());
    }

    public boolean getSectionCanMoveDown() {
        return getReorderHelper().getCanMoveRight(getPortfolio().getSections(), getSectionIndex());
    }

    public boolean getSectionCanMoveBoth() {
        return getReorderHelper().getCanMoveBoth(getPortfolio().getSections(), getSectionIndex());
    }

    public String getSelectedPageTag() {
        return getSectionIndex() + SEPARATOR + getPageIndex();
    }

    public String getCurrentURL() {
        URLBuilder builder = getUrlBuilder();
        return builder.getURLForPortfolioPage(getCurrentPage());
    }

    public void addToPortfolio(MappedNode node, IRequestCycle cycle) {
        Long pageId = getWorkingPageDAO().getPageIdForNode(node);
        MappedPage page = getWorkingPageDAO().getPageWithId(pageId);
        PortfolioPage portPage = constructNewPortfolioPage(page.getPageId(), PortfolioPage.PAGE_DESTINATION);
        portPage.setPageTitle(node.getName());
        portPage.setPageType(node.getIsLeaf() ? "Leaf" : "Branch");
        finishAdd(portPage, cycle);
    }

    public void addToPortfolio(MappedAccessoryPage page, IRequestCycle cycle) {
        PortfolioPage portPage = constructNewPortfolioPage(Long.valueOf(page.getId()), PortfolioPage.ACC_PAGE_DESTINATION);
        portPage.setPageTitle(page.getMenu());
        portPage.setPageType(page.getTreehouseTypeString());
        finishAdd(portPage, cycle);
    }

    public void addImageToPortfolioPage(NodeImage img, IRequestCycle cycle) {
        PortfolioPage portPage = getSavedPage();
        if (portPage != null) {
            portPage.setImageId(Integer.valueOf(img.getId()));
            doSave();
        }
        setSavedPage(null);
        cycle.activate(this);
    }

    private void finishAdd(PortfolioPage portPage, IRequestCycle cycle) {
        PortfolioSection section = getSavedSection();
        if (section == null) {
            section = (PortfolioSection) getPortfolio().getSections().first();
        }
        getReorderHelper().addToSet(section.getPages(), portPage);
        doSave();
        setLastPageAnchorForSection(section);
        cycle.activate(this);
    }

    protected void setLastPageAnchorForSection(PortfolioSection section) {
        int index = Arrays.asList(getPortfolio().getSections().toArray()).indexOf(section);
        int pageIndex = section.getPages().size() - 1;
        setSelectedAnchor(getPageAnchorName(index, pageIndex));
    }

    protected PortfolioPage constructNewPortfolioPage(Long pageId, int destinationType) {
        PortfolioPage portPage = new PortfolioPage();
        portPage.setDestinationId(pageId.intValue());
        portPage.setDestinationType(destinationType);
        portPage.setComments("");
        return portPage;
    }

    public OrderedObjectConvertor getSectionConvertor() {
        return new OrderedObjectConvertor(getPortfolio().getSections());
    }

    public OrderedObjectConvertor getPageConvertor() {
        return new OrderedObjectConvertor(getCurrentSection().getPages());
    }

    public Block getHelpBlock() {
        String blockName = "";
        if (getIsPortfolio()) {
            blockName = "portfolioHelpBlock";
        } else {
            blockName = "teacherResourceHelpBlock";
        }
        return (Block) getComponents().get(blockName);
    }
}


text:
namespace llvm {

extern cl::opt<unsigned> TailDupIndirectBranchSize;

/// Utility class to perform tail duplication.
class TailDuplicator {
  const TargetInstrInfo *TII;
  const TargetRegisterInfo *TRI;
  const MachineBranchProbabilityInfo *MBPI;
  const MachineModuleInfo *MMI;
  MachineRegisterInfo *MRI;
  MachineFunction *MF;
  bool PreRegAlloc;
  bool LayoutMode;
  unsigned TailDupSize;

  // A list of virtual registers for which to update SSA form.
  SmallVector<unsigned, 16> SSAUpdateVRs;

  // For each virtual register in SSAUpdateVals keep a list of source virtual
  // registers.
  typedef std::vector<std::pair<MachineBasicBlock *, unsigned>> AvailableValsTy;

  DenseMap<unsigned, AvailableValsTy> SSAUpdateVals;

public:
  /// Prepare to run on a specific machine function.
  /// @param MF - Function that will be processed
  /// @param MBPI - Branch Probability Info. Used to propagate correct
  ///     probabilities when modifying the CFG.
  /// @param LayoutMode - When true, don't use the existing layout to make
  ///     decisions.
  /// @param TailDupSize - Maxmimum size of blocks to tail-duplicate. Zero
  ///     default implies using the command line value TailDupSize.
  void initMF(MachineFunction &MF,
              const MachineBranchProbabilityInfo *MBPI,
              bool LayoutMode, unsigned TailDupSize = 0);
  bool tailDuplicateBlocks();
  static bool isSimpleBB(MachineBasicBlock *TailBB);
  bool shouldTailDuplicate(bool IsSimple, MachineBasicBlock &TailBB);
  /// Returns true if TailBB can successfully be duplicated into PredBB
  bool canTailDuplicate(MachineBasicBlock *TailBB, MachineBasicBlock *PredBB);
  /// Tail duplicate a single basic block into its predecessors, and then clean
  /// up.
  /// If \p DuplicatePreds is not null, it will be updated to contain the list
  /// of predecessors that received a copy of \p MBB.
  /// If \p RemovalCallback is non-null. It will be called before MBB is
  /// deleted.
  bool tailDuplicateAndUpdate(
      bool IsSimple, MachineBasicBlock *MBB,
      MachineBasicBlock *ForcedLayoutPred,
      SmallVectorImpl<MachineBasicBlock*> *DuplicatedPreds = nullptr,
      llvm::function_ref<void(MachineBasicBlock *)> *RemovalCallback = nullptr);

private:
  typedef TargetInstrInfo::RegSubRegPair RegSubRegPair;

  void addSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
                         MachineBasicBlock *BB);
  void processPHI(MachineInstr *MI, MachineBasicBlock *TailBB,
                  MachineBasicBlock *PredBB,
                  DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
                  SmallVectorImpl<std::pair<unsigned, RegSubRegPair>> &Copies,
                  const DenseSet<unsigned> &UsedByPhi, bool Remove);
  void duplicateInstruction(MachineInstr *MI, MachineBasicBlock *TailBB,
                            MachineBasicBlock *PredBB,
                            DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
                            const DenseSet<unsigned> &UsedByPhi);
  void updateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
                            SmallVectorImpl<MachineBasicBlock *> &TDBBs,
                            SmallSetVector<MachineBasicBlock *, 8> &Succs);
  bool canCompletelyDuplicateBB(MachineBasicBlock &BB);
  bool duplicateSimpleBB(MachineBasicBlock *TailBB,
                         SmallVectorImpl<MachineBasicBlock *> &TDBBs,
                         const DenseSet<unsigned> &RegsUsedByPhi,
                         SmallVectorImpl<MachineInstr *> &Copies);
  bool tailDuplicate(bool IsSimple,
                     MachineBasicBlock *TailBB,
                     MachineBasicBlock *ForcedLayoutPred,
                     SmallVectorImpl<MachineBasicBlock *> &TDBBs,
                     SmallVectorImpl<MachineInstr *> &Copies);
  void appendCopies(MachineBasicBlock *MBB,
                 SmallVectorImpl<std::pair<unsigned,RegSubRegPair>> &CopyInfos,
                 SmallVectorImpl<MachineInstr *> &Copies);

  void removeDeadBlock(
      MachineBasicBlock *MBB,
      llvm::function_ref<void(MachineBasicBlock *)> *RemovalCallback = nullptr);
};

} // End llvm namespace

#endif


text: DEFAULT_CLASSES = ['open_data']


text:
package configs.testutil.instance

import configs.testutil.instance.error._
import configs.{ConfigError, ConfigWriter, Result}
import scalaprops.Gen
import scalaz.Equal

object result {

  implicit def resultGen[A: Gen]: Gen[Result[A]] =
    Gen.oneOf(
      Gen[A].map(Result.successful),
      Gen[ConfigError].map(Result.failure)
    )

  implicit def resultEqual[A: Equal]: Equal[Result[A]] =
    Equal.equal((r1, r2) =>
      (r1, r2) match {
        case (Result.Success(a1), Result.Success(a2)) => Equal[A].equal(a1, a2)
        case (Result.Failure(e1), Result.Failure(e2)) => Equal[ConfigError].equal(e1, e2)
        case _ => false
      })

  object success {

    implicit def successResultGen[A: Gen]: Gen[Result[A]] =
      Gen[A].map(Result.successful)

    implicit def successResultEqual[A: Equal]: Equal[Result[A]] =
      Equal.equalBy(_.value)

    implicit def successResultConfigWriter[A: ConfigWriter]: ConfigWriter[Result[A]] =
      ConfigWriter.by(_.value)

  }

}


text:
<?hh // strict

class :dl extends :xhp:html-element {
  category %flow;
  children (:dt+, :dd+)*;
  protected string $tagName = 'dl';
}


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

/**
 * Upgrade code for the random question type.
 * @param int $oldversion the version we are upgrading from.
 */
function xmldb_qtype_random_upgrade($oldversion) {
    global $CFG, $DB;

    $dbman = $DB->get_manager();

    // Moodle v2.2.0 release upgrade line
    // Put any upgrade step following this.

    // Moodle v2.3.0 release upgrade line
    // Put any upgrade step following this.

    // Moodle v2.4.0 release upgrade line
    // Put any upgrade step following this.

    // Moodle v2.5.0 release upgrade line.
    // Put any upgrade step following this.

    // Moodle v2.6.0 release upgrade line.
    // Put any upgrade step following this.

    // Moodle v2.7.0 release upgrade line.
    // Put any upgrade step following this.

    if ($oldversion < 2014060200) {
        $sql = "UPDATE {question}
                   SET questiontext = '0'
                 WHERE qtype = 'random'
                   AND " . $DB->sql_compare_text('questiontext') . " = ?";
        $DB->execute($sql, array(''));

        // Record that qtype_random savepoint was reached.
        upgrade_plugin_savepoint(true, 2014060200, 'qtype', 'random');
    }

    // Moodle v2.8.0 release upgrade line.
    // Put any upgrade step following this.

    // Moodle v2.9.0 release upgrade line.
    // Put any upgrade step following this.

    return true;
}


text:
package com.ibatis.common.beans;

/**
 * An abstract factory for getting Probe implementations.
 */
public class ProbeFactory {

  /** The Constant DOM. */
  private static final Probe DOM = new DomProbe();

  /** The Constant BEAN. */
  private static final Probe BEAN = new ComplexBeanProbe();

  /** The Constant GENERIC. */
  private static final Probe GENERIC = new GenericProbe();

  /**
   * Factory method for getting a Probe object.
   *
   * @return An implementation of the Probe interface
   */
  public static Probe getProbe() {
    return GENERIC;
  }

  /**
   * Factory method for getting a Probe object that is the best choice for the type of object supplied by the object
   * parameter.
   *
   * @param object
   *          The object to get a Probe for
   * @return An implementation of the Probe interface
   */
  public static Probe getProbe(Object object) {
    if (object instanceof org.w3c.dom.Document) {
      return DOM;
    } else {
      return BEAN;
    }
  }

}


text:
<?php

namespace app\models;

use app\services\Subscribe;
use cs\services\BitMask;
use yii\db\Query;

class Picture extends \cs\base\DbRecord
{
    const TABLE = 'bog_pictures';

    public function getName()
    {
        return $this->getField('name');
    }

    public function getImage($isScheme = false)
    {
        $image = $this->getField('image', '');
        if ($image == '') return '';

        return \yii\helpers\Url::to($this->getField('image'), $isScheme);
    }

}