text:
static NSString *const UseCloudSegue = @"UseiCloudSegue";
static NSString *const DontUseCloudSegue = @"DontUseiCloudSegue";

@interface CTRLSetupCloudOptionViewController ()<UIActionSheetDelegate>
@property (weak, nonatomic) IBOutlet UIView *movieView;
@property (nonatomic, strong) MPMoviePlayerController *movieController;
@property (nonatomic, strong) UIImageView *icloudFirstFrame;
@property (nonatomic, assign) BOOL awaitingStoreLoad;
@property (nonatomic, assign) BOOL useiCloud;
@property (nonatomic, assign) UITableViewCell *selectedCell;

@end

@implementation CTRLSetupCloudOptionViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSURL * resourcePath = [[NSBundle mainBundle] resourceURL];
    resourcePath = [NSURL URLWithString:@"icloudAnimation@2x.mov" relativeToURL:resourcePath];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(storeDidLoad) name:USMStoreDidChangeNotification object:nil];

    self.movieController = [[MPMoviePlayerController alloc] initWithContentURL:resourcePath];
    self.movieController.controlStyle = MPMovieControlStyleNone;
    self.movieController.shouldAutoplay = NO;
    [self.movieController prepareToPlay];
    self.movieController.view.frame = self.movieView.bounds;
    self.movieController.view.backgroundColor = [UIColor clearColor];
    self.movieController.backgroundView.frame = self.movieView.bounds;
    [self.movieController.backgroundView addSubview:[[UIImageView alloc] initWithImage:
                                                     [UIImage imageNamed:@"icloudAnimationFirstFrame"]]];
    self.movieController.backgroundView.backgroundColor = self.tableView.backgroundColor;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(firstFrameReady:) name:MPMoviePlayerReadyForDisplayDidChangeNotification object:self.movieController];

    self.icloudFirstFrame = [[UIImageView alloc] initWithImage:
                              [UIImage imageNamed:@"icloudAnimationFirstFrame"]];
    self.icloudFirstFrame.frame = self.movieController.backgroundView.bounds;

    [self.movieView addSubview:self.icloudFirstFrame];

    if (IS_FOUR_INCH_SCREEN) {
        self.navigationItem.rightBarButtonItem = nil;
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.movieController play];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];

    [self.movieController setCurrentPlaybackTime:0.0];
    [self.movieController pause];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    [self.movieController.view removeFromSuperview];
    self.movieController = nil;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - UITableViewDelegate

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    return !self.awaitingStoreLoad;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [activityIndicator startAnimating];

    cell.accessoryView = activityIndicator;
    self.selectedCell = cell;

    BOOL shouldWait = NO;

    if (indexPath.row == 0) {

        if ([CTRLDataStack sharedDataStack].useiCloud == NO) {
            shouldWait = YES;
        }
        [CTRLDataStack sharedDataStack].useiCloud = YES;
    }
    else if (indexPath.row == 1) {
        if ([CTRLDataStack sharedDataStack].useiCloud == YES) {
            shouldWait = YES;
        }
        [CTRLDataStack sharedDataStack].useiCloud = NO;
    }

    if (shouldWait) {
        [self waitForiCloudTransition];
    }
    else {
        [self attemptPushEditHouse];
    }

    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.accessoryView = nil;
}

#pragma mark - Navigation

- (IBAction)nextTapped:(UIBarButtonItem *)sender
{
    UIActionSheet *cloudActionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                  delegate:self
                                                         cancelButtonTitle:@"Cancel"
                                                    destructiveButtonTitle:@"Don't Use iCloud"
                                                         otherButtonTitles: @"Use iCloud", nil];
    [cloudActionSheet showInView:self.view];
}

- (void)waitForiCloudTransition
{
    self.awaitingStoreLoad = YES;
}

- (void)attemptPushEditHouse
{
    if (![CTRLDataStack sharedDataStack].scratchContext) {

        if (!IS_FOUR_INCH_SCREEN) {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText = @"Configuring...";

            self.navigationItem.leftBarButtonItem.enabled = NO;
            self.navigationItem.rightBarButtonItem.enabled = NO;
        }

        [self waitForiCloudTransition];
        return;
    }

    self.navigationItem.leftBarButtonItem.enabled = YES;
    self.navigationItem.rightBarButtonItem.enabled = YES;

    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    self.selectedCell.accessoryView = nil;
    self.awaitingStoreLoad = NO;

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    CTRLEditHouseViewController *destinationVC = (CTRLEditHouseViewController *)[storyboard instantiateViewControllerWithIdentifier:@"editHouseViewController"];
    destinationVC.rightButtonTappedBlock = self.setupCompletionBlock;
    destinationVC.allowPanelCreation = YES;
    destinationVC.showMyHouseAlreadyExists = [CTRLDataStack sharedDataStack].useiCloud;

    NSManagedObjectContext *moc = [[CTRLDataStack sharedDataStack] scratchContext];
    [moc reset]; //clear out any previous houses that were created in the next vc and then user comes back to this vc

    destinationVC.house = [NSEntityDescription insertNewObjectForEntityForName:@"House" inManagedObjectContext:moc];
    destinationVC.house.name = @"My House";

    [self.navigationController pushViewController:destinationVC animated:YES];
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{

    if (buttonIndex == actionSheet.destructiveButtonIndex) {
        [CTRLDataStack sharedDataStack].useiCloud = NO;
    }
    else if (buttonIndex == actionSheet.firstOtherButtonIndex) {
        if ([CTRLDataStack sharedDataStack].cloudAvailable) {
            [CTRLDataStack sharedDataStack].useiCloud = YES;
        }
        else {
            [CTRLDataStack sharedDataStack].useiCloud = NO;
            UIAlertView *iCloudAlert = [[UIAlertView alloc] initWithTitle:nil message:@"Please set up an iCloud account in the Settings App to use this feature." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [iCloudAlert show];
        }
    }
    else if (buttonIndex == actionSheet.cancelButtonIndex) {
        return;
    }

    [self attemptPushEditHouse];
}

#pragma mark - MPMoviePlayerController

- (void)firstFrameReady:(NSNotification *)note
{
    if (self.movieController.readyForDisplay) {
        [self.movieView addSubview:self.movieController.view];
    }

}

#pragma mark - UbiquityStoreManager

- (void)storeDidLoad
{
    if (self.awaitingStoreLoad) {
        self.awaitingStoreLoad = NO;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self attemptPushEditHouse];
        });
    }
}

@end


text:
class AddVenueIdToConcerts < ActiveRecord::Migration
  def change
    add_column :concerts, :venue_id, :integer
  end
end

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 */
package com.flipkart.portkey.rdbms.metadata.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import com.flipkart.portkey.common.serializer.JsonSerializer;
import com.flipkart.portkey.common.serializer.Serializer;

/**
 * @author santosh.p
 */
@Retention (RetentionPolicy.RUNTIME)
@Target (ElementType.FIELD)
public @interface RdbmsField
{
	public String columnName();

	public boolean isPrimaryKey() default false;

	public boolean isUnique() default false;

	public String defaultInsertValue() default "";

	public String defaultUpdateValue() default "";

	public Class<? extends Serializer> serializer() default JsonSerializer.class;
}


text:
package avrohugger
package format

import org.apache.avro.Schema

import java.nio.file.{Path, Paths, Files, StandardOpenOption}
import java.io.{File, FileNotFoundException, IOException}
import scala.collection.JavaConversions._

trait SourceFormat {

  // abstract members to be implemented by a subclass
  val toolName: String

  val toolShortDescription: String

  def fileExt(schema: Schema): String

  val typeMatcher: TypeMatcher

  def asDefinitionString(
  	classStore: ClassStore,
    namespace: Option[String],
    schema: Schema): String

  // concrete member takes a schema and writes the definition to a file
  def writeToFile(
    classStore: ClassStore,
    namespace: Option[String],
    schema: Schema,
    outDir: String): Unit = {

    // Custom namespaces work for simple types, but seem to fail for records within unions,
    // see http://apache-avro.679487.n3.nabble.com/Deserialize-with-different-schema-td4032782.html
    def checkCustomNamespace(namespace: Option[String]) = {
      def queryNamespaceMap(schemaNamespace: String): Option[String] = {
        typeMatcher.namespaceMap.get(schemaNamespace) match {
          case Some(customNamespace) => Some(customNamespace)
          case None => Some(schemaNamespace)
        }
      }
      namespace match {
        case Some(ns) => queryNamespaceMap(ns)
        case None => None
      }
    }

    val scalaNamespace = checkCustomNamespace(namespace)

    val codeAsString = asDefinitionString(classStore,
      scalaNamespace,
      schema)

    val folderPath: Path = Paths.get{
      if (scalaNamespace.isDefined) outDir + "/" + scalaNamespace.get.toString.replace('.','/')
      else outDir
    }

    if (!Files.exists(folderPath)) Files.createDirectories(folderPath)

    val filePath = {
      Paths.get(folderPath.toString + "/" + schema.getName + fileExt(schema))
    }
    try { // delete old and/or create new
      Files.deleteIfExists(filePath)
      Files.write(filePath, codeAsString.getBytes(), StandardOpenOption.CREATE)
      ()
    }
    catch {
      case ex: FileNotFoundException => sys.error("File not found:" + ex)
      case ex: IOException => sys.error("There was a problem using the file: " + ex)
    }
  }

}


text:
namespace MQTTnet.Client.Disconnecting
{
    public enum MqttClientDisconnectReason
    {
        NormalDisconnection = 0,
        DisconnectWithWillMessage = 4,
        UnspecifiedError = 128,
        MalformedPacket = 129,
        ProtocolError = 130,
        ImplementationSpecificError = 131,
        NotAuthorized = 135,
        ServerBusy = 137,
        ServerShuttingDown = 139,
        BadAuthenticationMethod = 140,
        KeepAliveTimeout = 141,
        SessionTakenOver = 142,
        TopicFilterInvalid = 143,
        TopicNameInvalid = 144,
        ReceiveMaximumExceeded = 147,
        TopicAliasInvalid = 148,
        PacketTooLarge = 149,
        MessageRateTooHigh = 150,
        QuotaExceeded = 151,
        AdministrativeAction = 152,
        PayloadFormatInvalid = 153,
        RetainNotSupported = 154,
        QosNotSupported = 155,
        UseAnotherServer = 156,
        ServerMoved = 157,
        SharedSubscriptionsNotSupported = 158,
        ConnectionRateExceeded = 159,
        MaximumConnectTime = 160,
        SubscriptionIdentifiersNotSupported = 161,
        WildcardSubscriptionsNotSupported = 162
    }
}


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

/* global cordova */
'use strict';

module.exports = {

    discover: function (seconds, success, failure) {
        cordova.exec(success, failure, 'RFduino', 'discover', [seconds]);
    },

    list: function (success, failure) {
        cordova.exec(success, failure, 'RFduino', 'list', []);
    },

    connect: function (uuid, success, failure) {
        cordova.exec(success, failure, 'RFduino', 'connect', [uuid]);
    },

    disconnect: function (success, failure) {
        cordova.exec(success, failure, 'RFduino', 'disconnect', []);
    },

    onData: function (success, failure) {
        cordova.exec(success, failure, 'RFduino', 'onData', []);
    },

    write: function (data, success, failure) {

        // data should be an ArrayBuffer, but handle strings for backward compatibility
        if (typeof(data) === 'string') {
            var string = data;
            var array = new Uint8Array(string.length);
            for (var i=0, len=string.length; i<len; i++) {
                array[i] = string.charCodeAt(i);
            }
            data = array.buffer;
        }

        cordova.exec(success, failure, 'RFduino', 'write', [data]);
    },

    isConnected: function (success, failure) {
        cordova.exec(success, failure, 'RFduino', 'isConnected', []);
    },

    isEnabled: function (success, failure) {
        cordova.exec(success, failure, 'RFduino', 'isEnabled', []);
    }

};


text:
import React, { Component, PropTypes } from 'react';
import FontIcon from 'material-ui/FontIcon';
import MenuItem from 'material-ui/MenuItem';
import Divider from 'material-ui/Divider';
import { Link } from 'react-router';

import pureRender from 'pure-render-decorator';

@pureRender
export default class LinkItem extends Component {
  static propTypes = {
    item: PropTypes.object.isRequired,
    onLinkTouch: PropTypes.func.isRequired,
  };

  static defaultProps = {
    item: {},
  };

  constructor(...args) {
    super(...args);

    this._onLinkClick = ::this._onLinkClick;
    this._onItemTouched = ::this._onItemTouched;
  }

  _onLinkClick(e) {
    e.preventDefault();
    e.stopPropagation();
  }

  _onItemTouched() {
    const { onLinkTouch, item } = this.props;

    onLinkTouch(item);
  }

  render() {
    const { item } = this.props;

    let container;
    if (item.internal) {
      container = <Link to={item.url} onClick={this._onLinkClick} />;
    } else {
      container = <div />;
    }

    return (
      <div>
        <MenuItem
          linkButton
          containerElement={container}
          onTouchTap={this._onItemTouched}
          disabled={item.disabled}
          leftIcon={
            <FontIcon className="material-icons">{item.icon}</FontIcon>
          }
        >
          {item.label}
        </MenuItem>
        {item.withDivider ? <Divider /> : null}
      </div>
    );
  }
}


text:
#ifndef _BRCM_CHANNEL_H_
#define _BRCM_CHANNEL_H_

/* conversion for phy txpwr calculations that use .25 dB units */
#define BRCMS_TXPWR_DB_FACTOR 4

/* bits for locale_info flags */
#define BRCMS_PEAK_CONDUCTED	0x00	/* Peak for locals */
#define BRCMS_EIRP		0x01	/* Flag for EIRP */
#define BRCMS_DFS_TPC		0x02	/* Flag for DFS TPC */
#define BRCMS_NO_OFDM		0x04	/* Flag for No OFDM */
#define BRCMS_NO_40MHZ		0x08	/* Flag for No MIMO 40MHz */
#define BRCMS_NO_MIMO		0x10	/* Flag for No MIMO, 20 or 40 MHz */
#define BRCMS_RADAR_TYPE_EU       0x20	/* Flag for EU */
#define BRCMS_DFS_FCC             BRCMS_DFS_TPC	/* Flag for DFS FCC */

#define BRCMS_DFS_EU (BRCMS_DFS_TPC | BRCMS_RADAR_TYPE_EU) /* Flag for DFS EU */

extern struct brcms_cm_info *
brcms_c_channel_mgr_attach(struct brcms_c_info *wlc);

extern void brcms_c_channel_mgr_detach(struct brcms_cm_info *wlc_cm);

extern bool brcms_c_valid_chanspec_db(struct brcms_cm_info *wlc_cm,
				      u16 chspec);

extern void brcms_c_channel_reg_limits(struct brcms_cm_info *wlc_cm,
				   u16 chanspec,
				   struct txpwr_limits *txpwr);
extern void brcms_c_channel_set_chanspec(struct brcms_cm_info *wlc_cm,
				     u16 chanspec,
				     u8 local_constraint_qdbm);
extern void brcms_c_regd_init(struct brcms_c_info *wlc);

#endif				/* _WLC_CHANNEL_H */


text:
<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE section PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY % BOOK_ENTITIES SYSTEM "cloudstack.ent">
%BOOK_ENTITIES;
]>

<!-- Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
-->

<section id="configure-vpn">
	<title>Configuring VPN</title>
	<para>To set up VPN for the cloud:</para>
	<orderedlist>
		<listitem><para>Log in to the &PRODUCT; UI as an administrator or end user. </para></listitem>
		<listitem><para>In the left navigation, click Global Settings.</para></listitem>
		<listitem><para>Set the following global configuration parameters.</para>
		<itemizedlist>
			<listitem><para>remote.access.vpn.client.ip.range – The range of IP addressess to be allocated to remote access VPN clients. The first IP in the range is used by the VPN server.</para></listitem>
			<listitem><para>remote.access.vpn.psk.length – Length of the IPSec key.</para></listitem>
			<listitem><para>remote.access.vpn.user.limit – Maximum number of VPN users per account.</para></listitem>
		</itemizedlist></listitem></orderedlist>
		<para>To enable VPN for a particular network:</para>
		<orderedlist>
			<listitem><para>Log in as a user or administrator to the &PRODUCT; UI.</para></listitem>
			<listitem><para>In the left navigation, click Network.</para></listitem>
			<listitem><para>Click the name of the network you want to work with.</para></listitem>
			<listitem><para>Click View IP Addresses.</para></listitem>
			<listitem><para>Click one of the displayed IP address names.</para></listitem>
			<listitem><para>Click the Enable VPN button <inlinemediaobject>
				<imageobject>
					<imagedata fileref="./images/vpn-icon.png" />
				</imageobject>
				<textobject><phrase>AttachDiskButton.png: button to attach a volume</phrase></textobject>
			</inlinemediaobject>.</para>
				<para>The IPsec key is displayed in a popup window.</para></listitem>
		</orderedlist>
</section>


text:
<?php
/**
 * @license MIT
 * Full license text in LICENSE file
 */

namespace Cavis\Core\Usecase\Category\Edit;
use Cavis\Core\Data;
use Cavis\Core\Tool;
use Cavis\Core\Exception;

class Submission extends Data\Category
{
    public $id;
    public $name;
    public $parent;
    private $repository;
    private $validator;

    public function __construct(Data\Category $category, Repository $repository, Tool\Validator $validator)
    {
        $this->id = $category->id;
        $this->name = $category->name;
        $this->parent = $category->parent;
        $this->repository = $repository;
        $this->validator = $validator;
    }

    public function validate()
    {
        $this->validator->setup(array(
            'id' => $this->id,
            'name' => $this->name,
            'parent_id' => $this->parent->id
        ));
        $this->validator->rule('id', 'not_empty');
        $this->validator->rule('name', 'not_empty');
        $this->validator->callback('id', array($this, 'is_an_existing_category_id'), array('id'));
        $this->validator->callback('parent_id', array($this, 'is_an_existing_category_id'), array('parent_id'));

        if ( ! $this->validator->check())
            throw new Exception\Validation($this->validator->errors());
    }

    public function is_an_existing_category_id($id)
    {
        if ($id !== NULL)
            return $this->repository->does_category_exist($id);
        else
            return TRUE;
    }

    public function update()
    {
        $this->repository->update_category($this->id, $this->name, $this->parent->id);
    }

}


text:
import {Type} from '../../interface/type';
import {getClosureSafeProperty} from '../../util/property';
import {ClassProvider, ConstructorProvider, ExistingProvider, FactoryProvider, StaticClassProvider, ValueProvider} from './provider';

/**
 * Information about how a type or `InjectionToken` interfaces with the DI system.
 *
 * At a minimum, this includes a `factory` which defines how to create the given type `T`, possibly
 * requesting injection of other types if necessary.
 *
 * Optionally, a `providedIn` parameter specifies that the given type belongs to a particular
 * `InjectorDef`, `NgModule`, or a special scope (e.g. `'root'`). A value of `null` indicates
 * that the injectable does not belong to any scope.
 *
 * NOTE: This is a private type and should not be exported
 *
 * @publicApi
 */
export interface ΔInjectableDef<T> {
  /**
   * Specifies that the given type belongs to a particular injector:
   * - `InjectorType` such as `NgModule`,
   * - `'root'` the root injector
   * - `'any'` all injectors.
   * - `null`, does not belong to any injector. Must be explicitly listed in the injector
   *   `providers`.
   */
  providedIn: InjectorType<any>|'root'|'any'|null;

  /**
   * Factory method to execute to create an instance of the injectable.
   */
  factory: () => T;

  /**
   * In a case of no explicit injector, a location where the instance of the injectable is stored.
   */
  value: T|undefined;
}

/**
 * Information about the providers to be included in an `Injector` as well as how the given type
 * which carries the information should be created by the DI system.
 *
 * An `InjectorDef` can import other types which have `InjectorDefs`, forming a deep nested
 * structure of providers with a defined priority (identically to how `NgModule`s also have
 * an import/dependency structure).
 *
 * NOTE: This is a private type and should not be exported
 *
 * @publicApi
 */
export interface ΔInjectorDef<T> {
  factory: () => T;

  // TODO(alxhub): Narrow down the type here once decorators properly change the return type of the
  // class they are decorating (to add the ngInjectableDef property for example).
  providers: (Type<any>|ValueProvider|ExistingProvider|FactoryProvider|ConstructorProvider|
              StaticClassProvider|ClassProvider|any[])[];

  imports: (InjectorType<any>|InjectorTypeWithProviders<any>)[];
}

/**
 * A `Type` which has an `InjectableDef` static field.
 *
 * `InjectableDefType`s contain their own Dependency Injection metadata and are usable in an
 * `InjectorDef`-based `StaticInjector.
 *
 * @publicApi
 */
export interface InjectableType<T> extends Type<T> {
  /**
   * Opaque type whose structure is highly version dependent. Do not rely on any properties.
   */
  ngInjectableDef: never;
}

/**
 * A type which has an `InjectorDef` static field.
 *
 * `InjectorDefTypes` can be used to configure a `StaticInjector`.
 *
 * @publicApi
 */
export interface InjectorType<T> extends Type<T> {
  /**
   * Opaque type whose structure is highly version dependent. Do not rely on any properties.
   */
  ngInjectorDef: never;
}

/**
 * Describes the `InjectorDef` equivalent of a `ModuleWithProviders`, an `InjectorDefType` with an
 * associated array of providers.
 *
 * Objects of this type can be listed in the imports section of an `InjectorDef`.
 *
 * NOTE: This is a private type and should not be exported
 */
export interface InjectorTypeWithProviders<T> {
  ngModule: InjectorType<T>;
  providers?: (Type<any>|ValueProvider|ExistingProvider|FactoryProvider|ConstructorProvider|
               StaticClassProvider|ClassProvider|any[])[];
}

/**
 * Construct an `InjectableDef` which defines how a token will be constructed by the DI system, and
 * in which injectors (if any) it will be available.
 *
 * This should be assigned to a static `ngInjectableDef` field on a type, which will then be an
 * `InjectableType`.
 *
 * Options:
 * * `providedIn` determines which injectors will include the injectable, by either associating it
 *   with an `@NgModule` or other `InjectorType`, or by specifying that this injectable should be
 *   provided in the `'root'` injector, which will be the application-level injector in most apps.
 * * `factory` gives the zero argument function which will create an instance of the injectable.
 *   The factory can call `inject` to access the `Injector` and request injection of dependencies.
 *
 * @publicApi
 */
export function ΔdefineInjectable<T>(opts: {
  providedIn?: Type<any>| 'root' | 'any' | null,
  factory: () => T,
}): never {
  return ({
    providedIn: opts.providedIn as any || null, factory: opts.factory, value: undefined,
  } as ΔInjectableDef<T>) as never;
}

/**
 * @deprecated in v8, delete after v10. This API should be used only be generated code, and that
 * code should now use ΔdefineInjectable instead.
 * @publicApi
 */
export const defineInjectable = ΔdefineInjectable;

/**
 * Construct an `InjectorDef` which configures an injector.
 *
 * This should be assigned to a static `ngInjectorDef` field on a type, which will then be an
 * `InjectorType`.
 *
 * Options:
 *
 * * `factory`: an `InjectorType` is an instantiable type, so a zero argument `factory` function to
 *   create the type must be provided. If that factory function needs to inject arguments, it can
 *   use the `inject` function.
 * * `providers`: an optional array of providers to add to the injector. Each provider must
 *   either have a factory or point to a type which has an `ngInjectableDef` static property (the
 *   type must be an `InjectableType`).
 * * `imports`: an optional array of imports of other `InjectorType`s or `InjectorTypeWithModule`s
 *   whose providers will also be added to the injector. Locally provided types will override
 *   providers from imports.
 *
 * @publicApi
 */
export function ΔdefineInjector(options: {factory: () => any, providers?: any[], imports?: any[]}):
    never {
  return ({
    factory: options.factory, providers: options.providers || [], imports: options.imports || [],
  } as ΔInjectorDef<any>) as never;
}

/**
 * Read the `ngInjectableDef` type in a way which is immune to accidentally reading inherited value.
 *
 * @param type type which may have `ngInjectableDef`
 */
export function getInjectableDef<T>(type: any): ΔInjectableDef<T>|null {
  return type && type.hasOwnProperty(NG_INJECTABLE_DEF) ? (type as any)[NG_INJECTABLE_DEF] : null;
}

/**
 * Read the `ngInjectorDef` type in a way which is immune to accidentally reading inherited value.
 *
 * @param type type which may have `ngInjectorDef`
 */
export function getInjectorDef<T>(type: any): ΔInjectorDef<T>|null {
  return type && type.hasOwnProperty(NG_INJECTOR_DEF) ? (type as any)[NG_INJECTOR_DEF] : null;
}

export const NG_INJECTABLE_DEF = getClosureSafeProperty({ngInjectableDef: getClosureSafeProperty});
export const NG_INJECTOR_DEF = getClosureSafeProperty({ngInjectorDef: getClosureSafeProperty});


text:
\chapter{IC commands for 6.270}

{\sl The Interactive C Manual For the Handy Board\/} describes the basic
set of commands you will
have access to on the Handy Board.  In addition, to make use of the
6.270 expansion board, you will need to use several extensions to the
standard IC library, described in this appendix.

\section{Expansion Board: Motors, Analog Inputs, Digital Outputs}

There are two motor ports on the expansion board, numbered 4 and~5.
You can use them just as you use the motors on the main board:
\begin{quote}
\begin{verbatim}
fd(4);
motor(5,-100);
/* etc... */
\end{verbatim}
\end{quote}
Since the expansion board motors are not speed-controlled, all
positive speeds and all negative speeds are equivalent to 100
and~-100, respectively.

The expansion board add 16 analog inputs, labelled~16--31.  They are
used just like the analog ports on the main board:
\begin{quote}
\begin{verbatim}
analog(23);
\end{verbatim}
\end{quote}
When the expansion board is in use, ports 1 and~2 on the main board
can't be used.

There are three digital outputs: \texttt{do0}, \texttt{do1},
and~\texttt{do2}, which correspond to ports 8, 7, and~6 in software respectively. To turn the three digital outputs on and off, use the following commands:
\begin{quote}
\begin{verbatim}
set_digital_out(p);
clear_digital_out(p);
\end{verbatim}
\end{quote}
where \verb^p^ is replaced by whatever port you wish to control.

\section{Expansion Board: Servos}

The expansion board has the ability to control up to six servos.
To turn on the servos, run the following command:
\begin{quote}
\begin{verbatim}
enable_servos();
\end{verbatim}
\end{quote}
To turn off servo power, run this:
\begin{quote}
\begin{verbatim}
disable_servos();
\end{verbatim}
\end{quote}

The function \verb^servo(int port, int period)^ sets the servo to an
angle that depends on \texttt{period}, which can vary from 0 to 4000.

\section{Using the RF Reciever}
Connect your RF receiver to the phone jack on your handyboard using the telephone cable.  To enable the RF receiver, use the following command:

\begin{verbatim}
    rf_team = YOURTEAMNUMBER;
    rf_enable();
\end{verbatim}

The IC libraries include code to detect the start of the match.  Call the procedure \verb+start_machine()+ when your robot is ready to begin.  The code will walk you through the starting routine, consisting of the following
steps:

\begin{itemize}
\item Your LCD will display a message as soon as it has heard an announcement from the RF system.  This should happen within a second.

\item Announce "ready to go" and step back.

\item When the match begins, \verb+start_machine()+ will return.  Start doing stuff!

\item When the match ends, \verb+start_machine()+ will automatically shut down your robot.
\end{itemize}

The following is the basic outline for a program that follows the rules of 6.270.

\begin{verbatim}
void main() {
  rf_team = 1;
  rf_enable();

  /* calibrate your robot... */

  start_machine();

  printf("GO!\n");

  /* your code goes here... */
}
\end{verbatim}


text:
function[z] = backward_map(z,mapdata,varargin)
% backward_map -- Maps the disc to a shape
%
% [z] = backward_map(z,mapdata,{point_id=false(size(z))})
%
%     Uses the map mapdata to take points from the disc to the interior of the
%     shape. Assumes a welding map so it maps 'exterior' points as well. Whether
%     a point is 'exterior' or 'interior' is not needed as input, but the map
%     is different depending on this condition.
%
%     point_id == false ---> points are 'interior' to the disc
%     point_id == true  ---> points are 'exterior' to the disc
%
%     Note that there is no ambiguity unless abs(z)==1. For those z such that
%     abs(z)~=1, the input point_id is ignored.
%
%     This function is the opposite of unzip_shape.
%
%     [1]: Marshall and Rohde, "Convergence of the Zipper algorithm for
%     conformal mapping", 2006.

persistent strict_inputs zip moebius
persistent inverse_initial_map inverse_terminal_map assert_enough_points select_slider inverse_moebius_alignment

if isempty(strict_inputs)
  from labtools import strict_inputs
  from shapelab.common import moebius
  from shapelab.zipper import select_slider assert_enough_points
  from shapelab.zipper.drivers import inverse_initial_map inverse_terminal_map inverse_moebius_alignment
end

zsize = size(z);
z = z(:);

opt = strict_inputs({'point_id'}, {false(size(z))}, [], varargin{:});

% Set point_id -- override user specifications if magnitude of z dictates
point_id = opt.point_id(:);
tol = 1e-8;
nflags = abs(z)<(1-tol);
point_id(nflags) = false;
pflags = abs(z)>(1+tol);
point_id(pflags) = true;

interior = zeros(size(z));
interior = (nflags | pflags);
slit_interior = not(interior) & not(point_id);
slit_exterior = not(interior) & point_id;

% We're doing all the maps backwards now:
[z(~point_id), z(point_id)] = inverse_moebius_alignment(z(~point_id), z(point_id), mapdata);

% Fix real-valued crap:
z(slit_interior) = real(z(slit_interior));
z(slit_exterior) = real(z(slit_exterior));

z = inverse_terminal_map(z, mapdata, interior, slit_interior, slit_exterior);

slide = select_slider(mapdata.type);

for q = mapdata.N_teeth:-1:1
  [z] = slide('zipup', q, z, mapdata, interior, slit_interior, slit_exterior);
end

z = reshape(inverse_initial_map(z, mapdata), zsize);


text:
describe('#CreateViewInstanceCtrl', function () {
  var scope, ctrl, $httpBackend, View;

  beforeEach(module('ambariAdminConsole', function($provide){
    $provide.value('$routeParams', {viewId: 'TestView'});
  }));

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  beforeEach(inject(function (_$httpBackend_, $rootScope, $controller, _View_, $q) {
    View = _View_;
    spyOn(View, 'createInstance').andReturn($q.defer().promise);
    spyOn(View, 'getInstance').andReturn($q.defer().promise);

    $httpBackend = _$httpBackend_;
    $httpBackend.whenGET(/\/api\/v1\/views\/TestView\?.+/).respond(200, {
      "versions": [{"ViewVersionInfo": {}}]
    });
    $httpBackend.whenGET(/\/api\/v1\/views\/TestView\/versions\/1\.0\.0/).respond(200, {
      "ViewVersionInfo": {"parameters": [{"name": "n", "defaultValue": "d"}]}
    });
    $httpBackend.whenGET('template/modal/backdrop.html').respond(200, '

');
    $httpBackend.whenGET('template/modal/window.html').respond(200, '

');
    scope = $rootScope.$new();
    ctrl = $controller('CreateViewInstanceCtrl', {$scope: scope});
  }));

  it('it should invoke View.createInstance on save', function () {
    scope.form = {
      instanceCreateForm: {
        submitted: false,
        $valid: true
      }
    };
    $httpBackend.flush();
    scope.instance = {};
    scope.save();
    expect(View.createInstance).toHaveBeenCalled();
  });

  it('should set default property value before creating view instance', function () {
    scope.form = {
      instanceCreateForm: {
        $dirty: true
      }
    };
    scope.instance = {};
    scope.version = '1.0.0';
    scope.isClone=false;
    $httpBackend.expectGET('template/modal/backdrop.html');
    $httpBackend.expectGET('template/modal/window.html');
    $httpBackend.whenGET(/\/api\/v1\/clusters\?fields=Clusters\/cluster_id&_=\d+/).respond(200, {
      "items" : [
        {
          "Clusters" : {
            "cluster_name" : "c1",
            "version" : "HDP-2.2"
          }
        }
      ]
    });
    $httpBackend.whenGET(/\/api\/v1\/remoteclusters\?fields=ClusterInfo\/services,ClusterInfo\/cluster_id&_=\d+/).respond(200, {
      "items" : [
         {
           "ClusterInfo" : {
            "name" : "c1",
            "services" : ["HDFS"]
          }
        }
      ]
    });
    scope.$digest();
    $httpBackend.flush();
    chai.expect(scope.view.ViewVersionInfo.parameters[0].value).to.equal('d');
    expect(View.getInstance).not.toHaveBeenCalled();
  });

  it('before cloning view instance confirm that View.getInstance is called', function () {
    scope.form = {
      instanceCreateForm: {
        $dirty: true
      }
    };
    scope.instance = {};
    scope.version = '1.0.0';
    scope.isClone=true;
    $httpBackend.expectGET('template/modal/backdrop.html');
    $httpBackend.expectGET('template/modal/window.html');
    $httpBackend.whenGET(/\/api\/v1\/clusters\?fields=Clusters\/cluster_id&_=\d+/).respond(200, {
      "items" : [
        {
          "Clusters" : {
            "cluster_name" : "c1",
            "version" : "HDP-2.2"
          }
        }
      ]
    });
    $httpBackend.whenGET(/\/api\/v1\/remoteclusters\?fields=ClusterInfo\/services,ClusterInfo\/cluster_id&_=\d+/).respond(200, {
      "items" : [
         {
           "ClusterInfo" : {
            "name" : "c1",
            "services" : ["HDFS"]
          }
        }
      ]
    });
    scope.$digest();
    $httpBackend.flush();
    expect(View.getInstance).toHaveBeenCalled();
  });

});


text:
from django import apps

class ApiConfig(apps.AppConfig):
    name = 'api'


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.intention.impl.singlereturn;

import com.intellij.psi.*;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.util.CommonJavaRefactoringUtil;
import com.intellij.util.containers.ContainerUtil;
import com.siyeh.ig.psiutils.BoolUtils;
import com.siyeh.ig.psiutils.EquivalenceChecker;
import com.siyeh.ig.psiutils.VariableNameGenerator;
import org.jetbrains.annotations.NotNull;

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

import static java.util.Objects.requireNonNull;

/**
 * Tracks method exit strategy and additional variables which could be necessary for single-return conversion
 */
class ExitContext {
  private final @NotNull PsiType myReturnType;
  private final @NotNull FinishMarker.FinishMarkerType myFinishMarkerType;
  private String myFinishedVariable;
  private final @NotNull PsiCodeBlock myBlock;
  private final @NotNull String myReturnVariable;
  private final @NotNull PsiElementFactory myFactory;
  private boolean myReturnVariableUsed = false;
  private final PsiExpression myReturnVariableDefaultValue;

  ExitContext(@NotNull PsiCodeBlock block, @NotNull PsiType returnType, @NotNull FinishMarker marker) {
    myBlock = block;
    myFactory = JavaPsiFacade.getElementFactory(block.getProject());
    myReturnType = returnType;
    myReturnVariable =
      new VariableNameGenerator(block, VariableKind.LOCAL_VARIABLE).byName("result", "res").byType(returnType).generate(true);
    if (marker.myDefaultValue != null && PsiTreeUtil.isAncestor(block, marker.myDefaultValue, true)) {
      myReturnVariableDefaultValue = (PsiExpression)marker.myDefaultValue.copy();
    } else {
      myReturnVariableDefaultValue = marker.myDefaultValue;
    }
    myFinishMarkerType = marker.myType;
  }

  String generateExitCondition() {
    return switch (myFinishMarkerType) {
      case BOOLEAN_FALSE -> "!" + myReturnVariable;
      case BOOLEAN_TRUE -> myReturnVariable;
      case VALUE_EQUAL -> myReturnVariable + "==" + myReturnVariableDefaultValue.getText();
      case VALUE_NON_EQUAL -> myReturnVariable + "!=" + myReturnVariableDefaultValue.getText();
      default -> {
        assert myFinishedVariable != null;
        yield myFinishedVariable;
      }
    };
  }

  String getNonExitCondition() {
    return switch (myFinishMarkerType) {
      case BOOLEAN_FALSE -> myReturnVariable;
      case BOOLEAN_TRUE -> "!" + myReturnVariable;
      case VALUE_EQUAL -> myReturnVariable + "!=" + myReturnVariableDefaultValue.getText();
      case VALUE_NON_EQUAL -> myReturnVariable + "==" + myReturnVariableDefaultValue.getText();
      default -> {
        assert myFinishedVariable != null;
        yield "!" + myFinishedVariable;
      }
    };
  }

  void registerReturnValue(PsiExpression value, List<? super String> replacements) {
    myReturnVariableUsed = true;
    if (!EquivalenceChecker.getCanonicalPsiEquivalence().expressionsAreEquivalent(myReturnVariableDefaultValue, value)) {
      replacements.add(0, myReturnVariable + "=" + value.getText() + ";");
    }
  }

  void register(List<String> replacements) {
    if (myFinishMarkerType != FinishMarker.FinishMarkerType.SEPARATE_VAR) return;
    if (myFinishedVariable == null) {
      myFinishedVariable =
        new VariableNameGenerator(myBlock, VariableKind.LOCAL_VARIABLE).byName("finished", "completed").generate(true);
    }
    String assignment = myFinishedVariable + "=true;";
    if (!replacements.contains(assignment)) {
      String first = ContainerUtil.getFirstItem(replacements);
      int index = first != null && first.startsWith(myReturnVariable + "=") ? 1 : 0;
      replacements.add(index, assignment);
    }
  }

  PsiLocalVariable declareVariables() {
    if (myFinishedVariable != null) {
      PsiJavaToken start = requireNonNull(myBlock.getLBrace());
      PsiExpression initializer = myFactory.createExpressionFromText("false", null);
      PsiDeclarationStatement declaration =
        myFactory.createVariableDeclarationStatement(myFinishedVariable, PsiType.BOOLEAN, initializer);
      PsiModifierList list = ((PsiLocalVariable)declaration.getDeclaredElements()[0]).getModifierList();
      if (list != null) {
        // Cannot be final: always reassigned or useless
        list.setModifierProperty(PsiModifier.FINAL, false);
      }
      myBlock.addAfter(declaration, start);
    }
    if (myReturnVariableUsed) {
      PsiJavaToken start = requireNonNull(myBlock.getLBrace());
      PsiExpression initializer = myReturnVariableDefaultValue;
      if (initializer == null && myFinishedVariable != null) {
        initializer = myFactory.createExpressionFromText(PsiTypesUtil.getDefaultValueOfType(myReturnType), null);
      }
      PsiDeclarationStatement declaration = myFactory.createVariableDeclarationStatement(myReturnVariable, myReturnType, initializer);
      PsiLocalVariable var = (PsiLocalVariable)((PsiDeclarationStatement)myBlock.addAfter(declaration, start)).getDeclaredElements()[0];
      if (var.hasModifierProperty(PsiModifier.FINAL) && !CommonJavaRefactoringUtil.canBeDeclaredFinal(var)) {
        // Keep final when possible to respect code style setting "generate local variables as 'final'"
        requireNonNull(var.getModifierList()).setModifierProperty(PsiModifier.FINAL, false);
      }
      return var;
    }
    return null;
  }

  public boolean isFinishCondition(PsiStatement statement) {
    if (!(statement instanceof PsiIfStatement)) return false;
    PsiExpression condition = ((PsiIfStatement)statement).getCondition();
    if (condition == null) return false;
    if (BoolUtils.isNegation(condition)) {
      condition = BoolUtils.getNegated(condition);
    }
    if (condition instanceof PsiBinaryExpression) {
      condition = ((PsiBinaryExpression)condition).getLOperand();
    }
    if (!(condition instanceof PsiReferenceExpression)) return false;
    PsiReferenceExpression ref = (PsiReferenceExpression)condition;
    return ref.getQualifierExpression() == null &&
           (Objects.equals(myFinishedVariable, ref.getReferenceName()) ||
            Objects.equals(myReturnVariable, ref.getReferenceName()));
  }

  /**
   * @param statement statement to check
   * @return true if given statement is a return statement which returns registered default value, so it could be fully removed
   */
  boolean isDefaultReturn(PsiStatement statement) {
    if (myReturnVariableDefaultValue != null && statement instanceof PsiReturnStatement) {
      PsiReturnStatement returnStatement = (PsiReturnStatement)statement;
      return EquivalenceChecker.getCanonicalPsiEquivalence()
               .expressionsAreEquivalent(myReturnVariableDefaultValue, returnStatement.getReturnValue()) &&
             !FinishMarker.mayNeedMarker(returnStatement, myBlock);
    }
    return false;
  }
}


text:
from gnocchi import statsd as statsd_service

def statsd():
    statsd_service.start()


text:
// Copyright © 2014 Intel Corporation. All rights reserved.
// Use  of this  source  code is  governed by  an Apache v2
// license that can be found in the LICENSE-APACHE-V2 file.

var ChildProcess = require("child_process");
var FS = require("fs");
var Path = require('path');

var FormatJson = require("format-json");
var MkTemp = require('mktemp');
var ShellJS = require("shelljs");

var AndroidManifest = require("./AndroidManifest");
var AndroidSDK = require("./AndroidSDK");
var JavaActivity = require("./JavaActivity");
var ProjectProperties = require("./ProjectProperties");
var XmlTheme = require("./XmlTheme");

/**
 * Android project class.
 * @extends PlatformBase
 * @constructor
 * @param {Function} PlatformBase Base class constructor {@link PlatformBase}
 * @param {PlatformData} baseData Init data passed to the platform
 * @throws {@link AndroidSDK~SDKNotFoundError} If the Android SDK was not found in the environment.
 */
function AndroidPlatform(PlatformBase, baseData) {

    // Create base instance.
    var instance = new PlatformBase(baseData);
    var o = instance.output;

    // Override manually, because Object.extend() is not yet available on node.
    var names = Object.getOwnPropertyNames(AndroidPlatform.prototype);
    for (var i = 0; i < names.length; i++) {
        var key = names[i];
        if (key != "constructor") {
            instance[key] = AndroidPlatform.prototype[key];
        }
    }

    instance._sdk = new AndroidSDK(instance.application);
    instance._channel = "stable";
    instance._lite = false;
    instance._shared = false;
    instance._apiTarget = null;

    return instance;
}

/**
 * Minimal API level.
 * FIXME: this is not the optimal way to specify this.
 */
AndroidPlatform.MIN_API_LEVEL = 21;

/**
 * Accessor function for platform-specific command-line argument spec.
 * @static
 */
AndroidPlatform.getArgs =
function() {
    return {
        create: {
            "crosswalk": "                 Channel name (stable/beta/canary)\n" +
                         "\t\t\t\t\t\tor version number (w.x.y.z)\n" +
                         "\t\t\t\t\t\tor crosswalk zip\n" +
                         "\t\t\t\t\t\tor xwalk_app_template dir",
            "lite": "                      Use crosswalk-lite, see Crosswalk Wiki for details",
            "shared": "                    Depend on shared crosswalk installation",
            "targets": "                   Target ABIs to create"
        },
        build: {
            "targets": "                   Target ABIs to build"
        }
    };
};

/**
 * Accessor function for platform-specific environment variables spec.
 * @static
 */
AndroidPlatform.getEnv =
function() {
    return {
        CROSSWALK_APP_TOOLS_CACHE_DIR: "Keep downloaded files in this dir"
    };
};

/**
 * Check host setup.
 * @param {OutputIface} output Output to write to
 * @param {Function} callback Function(success) to be called when done
 * @static
 */
AndroidPlatform.check =
AndroidPlatform.prototype.check =
function(output, callback) {

    // Checking deps
    var deps = [
        "android",
        "ant",
        "java",
        "lzma"
    ];

    var found = true;
    var msg;

    deps.forEach(function (dep) {
        var path = ShellJS.which(dep);
        msg = "Checking for " + dep + "...";
        if (path) {
            output.info(msg, path);
        } else {
            found = false;
            output.error(msg + " " + path);
        }
    });

    // Checking env
    var androidHome = "ANDROID_HOME";
    msg = "Checking for " + androidHome + "...";
    if (process.env[androidHome]) {
        output.info(msg, process.env[androidHome]);
    } else {
        found = false;
        output.info(msg + " empty");
        output.error(androidHome + " needs to be set for builds to work");
    }

    if (!found) {
        callback(false);
        return;
    }

    // Build dummy project
    var app = {
        output: output
    };

    ShellJS.pushd(ShellJS.tempdir());
    var dir = MkTemp.createDirSync("XXXXXX");
    // Delete dir right after, just allocate name.
    ShellJS.rm("-rf", dir);
    ShellJS.popd();

    var path = Path.join(ShellJS.tempdir(), dir);
    output.info("Testing dummy project in", path);

    var dummyPackageId = "com.example.foo";
    var dummyLog = "";
    var sdk = new AndroidSDK(app);
    // Progress display
    var indicator = output.createInfiniteProgress("Building " + dummyPackageId);
    sdk.onData = function(data) {

        dummyLog += data;

        // Scan first 7 chars if data starts with a [tag]
        var tag = null;
        for (var i = 0; i < 7 && i < data.length; i++) {
            if (data[i] === '[') {

                // Scan on a bit if there's a closing ']'
                for (j = i+1; j < i+15; j++) {
                    if (data[j] === ']') {
                        tag = data.substring(i+1, j);
                        indicator.update(tag);
                        return;
                    }
                }
            } else if (data[i] != ' ') {
                break;
            }
        }
    };

    sdk.queryTarget(AndroidPlatform.MIN_API_LEVEL,
                    function(apiTarget, errormsg) {

        if (errormsg) {
            callback(errormsg);
            return;
        }

        sdk.generateProjectSkeleton(path, dummyPackageId, apiTarget,
                                    function (path, logmsg, errormsg) {

            dummyLog += logmsg;

            if (!path || errormsg) {
                output.error(errormsg);
                ShellJS.rm("-rf", path);
                output.error("Generating project failed");
                if (dummyLog) {
                    FS.writeFileSync(path, dummyLog);
                    output.error("Consult logfile " + path);
                }
                callback(false);
                return;
            }

            // Build
            ShellJS.pushd(path);
            sdk.buildProject(false,
                             function(success) {

                ShellJS.popd();
                ShellJS.rm("-rf", path);
                indicator.done();
                if (!success) {
                    output.error("Building project failed");
                    if (dummyLog) {
                        FS.writeFileSync(path, dummyLog);
                        output.error("Consult logfile " + path);
                    }
                }
                callback(success);
            });
        });
    });
};

/**
 * Fill template files and put them into the project skeleton.
 * @param {String} apiTarget Android API target (greater android-14)
 * @param {String} activityClassName Class ame for the Activity
 * @returns {Boolean} True on success.
 */
AndroidPlatform.prototype.fillTemplates =
function(apiTarget, activityClassName) {

    // Namespace util
    var util = this.application.util;

    var parts = this.packageId.split('.');
    var packageName = parts[parts.length - 1];
    var data = {
        "packageId" : this.packageId,
        "packageName" : this.packageId,
        "activityName": this.packageId + "." + activityClassName,
        "apiTarget" : apiTarget,
        "xwalkLibrary" : this._shared ? "xwalk_shared_library" : "xwalk_core_library"
    };

    // AndroidManifest.xml
    var tpl = new util.TemplateFile(Path.join(__dirname, "..", "data", "AndroidManifest.xml.tpl"));
    tpl.render(data, this.platformPath + Path.sep + "AndroidManifest.xml");

    // build.xml
    tpl = new util.TemplateFile(Path.join(__dirname, "..", "data", "build.xml.tpl"));
    tpl.render(data, this.platformPath + Path.sep + "build.xml");

    // project.properties
    tpl = new util.TemplateFile(Path.join(__dirname, "..", "data", "project.properties.tpl"));
    tpl.render(data, this.platformPath + Path.sep + "project.properties");

    // Make html5 app dir and copy sample content
    var wwwPath = Path.join(this.platformPath, "assets", "www");
    ShellJS.mkdir("-p", wwwPath);
    ShellJS.cp("-rf", this.appPath + Path.sep + "*", wwwPath);

    // TODO check for errors
    return true;
};

/**
 * Import Crosswalk libraries and auxiliary files into the project.
 * @param {String} crosswalkPath Location of Crosswalk zip or xwalk_app_template build dir
 * @param {String} activityClassName Class ame for the Activity
 * @returns {String} Imported version on success, otherwise null.
 */
AndroidPlatform.prototype.importCrosswalkFromDisk =
function(crosswalkPath, activityClassName) {

    // Namespace util
    var util = this.application.util;

    var output = this.application.output;

    // "  * Extracting /home/robsta/Devel/tmp/crosswalk/crosswalk-15.44.384.12.zip [##########]"
    // Windows breaks at > 78.
    // Length of decorations/text is 28, so max length of path is 78-28,
    // minus nother 3 for ellipsis is 47.
    var indicator;
    if (crosswalkPath.length > 47) {
        var abbrv = crosswalkPath.substring(crosswalkPath.length - 47);
        indicator = output.createFiniteProgress("Extracting ..." + abbrv);
    } else {
        indicator = output.createFiniteProgress("Extracting " + crosswalkPath);
    }

    // Extract contents
    var xwalk = null;
    try {
        if (ShellJS.test("-d", crosswalkPath)) {
            xwalk = new util.CrosswalkDir(crosswalkPath);
        } else {
            xwalk = new util.CrosswalkZip(crosswalkPath);
        }
    } catch (e) {
        // HACK we're in the midst of a progress display, force line break
        output.write("\n");
        output.error("Failed to read " + crosswalkPath);
        if (ShellJS.test("-f", crosswalkPath)) {
            // Remove incomplete/corrupted zip so next time we start over downloading.
            ShellJS.rm("-f", crosswalkPath);
            output.error("Invalid file has been deleted, please try again");
        }
        return null;
    }

    indicator.update(0.2);

    if (xwalk.version.major < 9) {
        output.error("Crosswalk version " + xwalk.version.major + " not supported. Use 8+.");
        return null;
    } else if (xwalk.version.major < 17) {
        output.error("This version can't support Crosswalk " + xwalk.version.major + ". Please use previous version of this tool.");
        return null;
    } else if (xwalk.version.major > 19) {
        output.warning("This tool has not been tested with Crosswalk " + xwalk.version.major + ".");
    }

    var entry = xwalk.getEntry(xwalk.root);
    if (!entry) {
        output.error("Failed to find root entry " + xwalk.root);
        return null;
    }

    indicator.update(0.4);

    // Extract xwalk_core_library or xwalk_shared_library
    var path;
    var xwalkLibrary = this._shared ?
                            "xwalk_shared_library" :
                            "xwalk_core_library";
    var name = xwalk.root + xwalkLibrary + "/";
    entry = xwalk.getEntry(name);
    if (entry) {
        path = Path.join(this.platformPath, xwalkLibrary);
        xwalk.extractEntryTo(entry, path);
    } else {
        output.error("Failed to find entry " + name);
        return null;
    }

    indicator.update(0.5);

    // Update project properties
    var props = new ProjectProperties(Path.join(this.platformPath, "project.properties"), output);
    props.androidLibraryReference1 = xwalkLibrary;

    props = new ProjectProperties(Path.join(this.platformPath, xwalkLibrary, "project.properties"), output);
    props.target = this._apiTarget;

    indicator.update(0.6);

    name = xwalk.root + "template/libs/xwalk_app_runtime_java.jar";
    entry = xwalk.getEntry(name);
    if (entry) {
        xwalk.extractEntryTo(entry, this.platformPath + Path.sep + "libs");
    } else {
        output.error("Failed to find entry " + name);
        return null;
    }

    indicator.update(0.7);

    // Extract main activity java file
    name = xwalk.root + "template/src/org/xwalk/app/template/AppTemplateActivity.java";
    entry = xwalk.getEntry(name);
    if (entry) {

        // Create path
        var activityDirPath = JavaActivity.pathForPackage(this.platformPath, this.packageId);
        ShellJS.mkdir("-p", activityDirPath);
        if (!ShellJS.test("-d", activityDirPath)) {
            output.error("Failed to create activity dir " + activityDirPath);
            return false;
        }

        var activity = new JavaActivity(output,
                                        Path.join(activityDirPath, activityClassName + ".java"));
        if (!activity.importFromZip(entry, this.packageId, activityClassName))
            return null;

    } else {
        output.error("Failed to find in crosswalk release: " + name);
        return null;
    }

    indicator.update(0.8);

    // Extract res
    name = xwalk.root + "template/res/";
    entry = xwalk.getEntry(name);
    if (entry) {
        xwalk.extractEntryTo(entry, this.platformPath + Path.sep + "res");
    } else {
        output.error("Failed to find entry " + name);
        return null;
    }

    indicator.update(1);
    indicator.done();

    return xwalk.version.toString();
};

/**
 * Split target APIs string
 * TODO this is no more needed after crosswalk-app deprecation
 */
AndroidPlatform.prototype.parseTargets =
function(targetsSpec) {

    if (typeof targetsSpec === "string") {
        return targetsSpec.split(" ").filter(function (value) {
            // Filter empty entries caused by extra whitespace.
            return value;
        });
    }

    return targetsSpec;
};

/**
 * Implements {@link PlatformBase.create}
 */
AndroidPlatform.prototype.create =
function(packageId, args, callback) {

    // Namespace util
    var util = this.application.util;
    var output = this.application.output;

    if (args.lite && args.shared) {
        callback("Options \"lite\" and \"shared\" can not be used together");
        return;
    }

    if (args.lite) {
        this._lite = true;
    }

    if (args.shared) {
        this._shared = true;
    }

    // TODO this is no more needed after crosswalk-app deprecation
    args.targets = this.parseTargets(args.targets);

    // Check that only same-size ABIs are requested.
    if (args.targets) {
        var wordSize = 0;
        args.targets.forEach(function (abi) {
            if (wordSize &&
                wordSize != util.Targets.ABI_WORDSIZE[abi]) {
                callback("Projects can only be created for same-size ABIs (" + args.targets.join(",") + ")");
                return;
            }
            wordSize = util.Targets.ABI_WORDSIZE[abi];
        });
    }

    this._sdk.queryTarget(AndroidPlatform.MIN_API_LEVEL,
                          function(apiTarget, errormsg) {

        if (errormsg) {
            callback(errormsg);
            return;
        }

        this._apiTarget = apiTarget;
        output.info("Building against API level " + apiTarget);

        this._sdk.generateProjectSkeleton(this.platformPath, this.packageId, apiTarget,
                                          function(path, logmsg, errormsg) {

            this.logOutput.write(logmsg);

            if (!path || errormsg) {
                callback(errormsg);
                return;
            }

            // Remove _* from the default set of assets that are ignored
            // see sdk/tools/ant/build.xml for more info
            // the following is the default, without '_*'
            'aapt.ignore.assets = "!.svn:!.git:.*:!CVS:!thumbs.db:!picasa.ini:!*.scc:*~"\n'.toEnd(path + Path.sep + 'ant.properties');

            var versionSpec = null;
            if (args.crosswalk) {
                // TODO verify version/channel
                versionSpec = args.crosswalk;
            } else if (this._lite) {
                versionSpec = "canary"; //Lite only has canary release.
            } else {
                versionSpec = "stable";
                output.info("Defaulting to download channel " + versionSpec);
            }

            // Activity class name is the last part of the package-id
            // starting in caps, plus "Activity".
            // E.g. Package com.example.foo will get activity FooActivity.
            var activityClassName = this.application.manifest.packageId.split(".").pop();
            activityClassName = activityClassName[0].toUpperCase() + activityClassName.substring(1);
            activityClassName += "Activity";

            if (!this.fillTemplates(apiTarget, activityClassName)) {
                callback("Failed to initialise project templates");
                return;
            }

            var deps = new util.Download01Org(this.application, "android", "stable" /* FIXME this is just a placeholder */);
            if (this._lite) {
                deps.androidFlavor = "crosswalk-lite";
            }

            if (args.targets && args.targets.length > 0) {
                // We only handle ABIs with same word size in one create() call
                // so just check for the first one.
                var wordSize = util.Targets.ABI_WORDSIZE[args.targets[0]];
                deps.androidWordSize = wordSize;
            }
            deps.importCrosswalk(versionSpec,
                                 function(path) {
                                     return this.importCrosswalkFromDisk(path, activityClassName);
                                 }.bind(this),
                                 function(version, errormsg) {

                if (errormsg) {
                    output.error(errormsg);
                    callback("Creating project template failed");
                    return;
                }

                output.info("Project template created at", path);
                callback(null);
            }.bind(this));
        }.bind(this));
    }.bind(this));
};

/**
 * Enable ABIs so they are built into the APK.
 * @param {String} [abi] ABI identifier "armeabi-v7a" / "x86". When not passed,
 *                       all ABIs are enabled
 * @returns {Boolean} True on success or false.
 */
AndroidPlatform.prototype.enableABI =
function(abi) {

    var output = this.application.output;

    // There is no need to enable/disable various ABIs when building shared.
    // Only one APK is being built.
    if (this._shared) {
        return true;
    }

    var libsDir = "xwalk_core_library/libs";
    if (!ShellJS.test("-d", libsDir)) {
        output.error("This does not appear to be the root of a Crosswalk project.");
        return false;
    }

    var abiMatched = false;
    FS.readdirSync(libsDir).forEach(function (entry) {

        // This is a dir inside "libs", enable/disable depending
        // on which ABI we want.
        var libxwalkcore = Path.join(libsDir, entry, "libxwalkcore.so");
        var libxwalkcoreCompressed = Path.join(libsDir, entry, "libxwalkcoreCompressed.so");
        var libxwalkdummy = Path.join(libsDir, entry, "libxwalkdummy.so");
        if (!abi) {
            // No ABI passed, enable all of them, this is default
            // status of the project.
            ShellJS.mv(libxwalkcore + ".foo", libxwalkcore);
            ShellJS.mv(libxwalkcoreCompressed + ".foo", libxwalkcoreCompressed);
            ShellJS.mv(libxwalkdummy + ".foo", libxwalkdummy);
            abiMatched = true;
        } else if (abi === entry) {
            // enable
            ShellJS.mv(libxwalkcore + ".foo", libxwalkcore);
            ShellJS.mv(libxwalkcoreCompressed + ".foo", libxwalkcoreCompressed);
            ShellJS.mv(libxwalkdummy + ".foo", libxwalkdummy);
            abiMatched = true;
        } else {
            // disable
            ShellJS.mv(libxwalkcore, libxwalkcore + ".foo");
            ShellJS.mv(libxwalkcoreCompressed, libxwalkcoreCompressed + ".foo");
            ShellJS.mv(libxwalkdummy, libxwalkdummy + ".foo");
        }
    });

    return abiMatched;
};

/**
 * Rename the build APK to contain an ABI suffix, before the .apk suffix,
 * so when building multiple ABIs one after another, the subsequent APKs
 * do not overwrite the previously built ones.
 * @param {String} abi ABI name
 * @param {Boolean} release Whether we're building release or debug packages
 * @returns {String} Filename on success, otherwise null.
 */
AndroidPlatform.prototype.abifyAPKName =
function(abi, release) {

    var output = this.application.output;

    var apkInPattern;
    if (release) {
        apkInPattern = "-release-unsigned.apk";
    } else {
        apkInPattern = "-debug.apk";
    }

    ShellJS.pushd("bin");
    var apkInName = ShellJS.ls("*" + apkInPattern)[0];
    ShellJS.popd();

    if (!ShellJS.test("-f", "bin" + Path.sep + apkInName)) {
        output.error("APK bin" + Path.sep + apkInName + " not found");
        return null;
    }

    var base = apkInName.substring(0, apkInName.length - apkInPattern.length);
    var apkOutName = base + "-" +
                     this.application.manifest.appVersion + "-" +
                     (release ? "release-unsigned" : "debug") + "." +
                     abi + ".apk";
    ShellJS.mv("bin" + Path.sep + apkInName,
               "bin" + Path.sep + apkOutName);

    if (!ShellJS.test("-f", "bin" + Path.sep + apkOutName)) {
        output.error("APK bin" + Path.sep + apkOutName + " not found");
        return null;
    }

    return apkOutName;
};

/**
 * Generate versionCode for AndroidManifest.xml
 * @param {String} abi ABI to create the code for
 * @returns {String} Version code or null on failure.
 * @private
 * @static
 */
AndroidPlatform.prototype.generateVersionCode =
function(output, appVersion, abi) {

    function zeropad(string, length) {

        var str = (typeof string === "string") ? string : "";
        var padLen = length - str.length;
        var pad = Array(padLen + 1).join("0");
        return pad + str;
    }

    var abiCodes = {
        "shared": 2, // use same as ARM, TODO check if correct.
        "armeabi-v7a": 2,
        "arm64-v8a": 3,
        "x86": 6,
        "x86_64": 7
    };
    var versionNums = appVersion.split(".");

    var abiCode = abiCodes[abi];
    if (!abiCode) {
        output.error("Unsupported ABI code '" + abi + "'");
        return null;
    }

    // The format for versionCode is "ammiiccc", where
    // a .. abi
    // m .. major release number (optional, or 0)
    // i .. minor release number (optional, or 0)
    // c .. micro release number
    // This is a simplified version of
    // https://software.intel.com/en-us/blogs/2012/11/12/how-to-publish-your-apps-on-google-play-for-x86-based-android-devices-using
    //
    // We build the array holding the numbers in a reverse fashion,
    // that's easier with the optional parts.
    var reversedCode = ["000", "00", "00", "0"];
    var reversedVersion = versionNums.reverse();

    reversedCode[0] = zeropad(reversedVersion[0], 3);

    reversedCode[1] = zeropad(reversedVersion[1], 2);

    reversedCode[2] = zeropad(reversedVersion[2], 2);

    reversedCode[3] = abiCode;

    return reversedCode.reverse().join("");
};

/**
 * Update versionCode in AndroidManifest.xml for ABI
 * @param {String} abi ABI to generate the versionCode for
 * @returns {Boolean} true on success, false on failure.
 */
AndroidPlatform.prototype.updateVersionCode =
function(abi) {

    var output = this.application.output;

    var manifest = new AndroidManifest(this.application.output,
                                       Path.join(this.platformPath, "AndroidManifest.xml"));

    var versionCode = this.generateVersionCode(this.application.output,
                                               this.application.manifest.appVersion,
                                               abi);

    output.info("Using android:versionCode '" + versionCode + "'");
    manifest.versionCode = versionCode;

    return true;
};

/**
 * Build APK for one ABI. This method is calling itself recursively, until
 * all ABIs are built.
 * @param {Object} Closure Information to pass between ABI build runs
 */
AndroidPlatform.prototype.buildABI =
function(closure) {

    var output = this.application.output;

    // If done with all the ABIs, terminate successfully.
    if (closure.abiIndex >= closure.abis.length) {
        this.enableABI();
        closure.callback(null);
        return;
    }

    // Pick and enable ABI.
    var abi = closure.abis[closure.abiIndex];
    if (this.enableABI(abi)) {
        closure.abiIndex++;
    } else {
        // Failed, enable all ABIs and terminate build.
        this.enableABI();
        closure.callback("Enabling ABI '" + abi + "' failed");
        return;
    }

    // Progress display
    var indicator = output.createInfiniteProgress("Building " + abi);
    this._sdk.onData = function(data) {

        this.logOutput.write(data);

        // Scan first 7 chars if data starts with a [tag]
        var tag = null;
        for (var i = 0; i < 7 && i < data.length; i++) {
            if (data[i] === '[') {

                // Scan on a bit if there's a closing ']'
                for (j = i+1; j < i+15; j++) {
                    if (data[j] === ']') {
                        tag = data.substring(i+1, j);
                        indicator.update(tag);
                        return;
                    }
                }
            } else if (data[i] != ' ') {
                break;
            }
        }
    }.bind(this);

    // Update versionCode in AndroidManifest.xml
    this.updateVersionCode(abi);

    // Build for ABI.
    this._sdk.buildProject(closure.release, function(success) {

        indicator.done();
        if (success) {

            // Preserve APK by renaming it by ABI
            // Otherwise IA and ARM APKs would overwrite each other,
            // as we simply run ant twice.
            var apk = this.abifyAPKName(abi, closure.release);
            if (apk) {
                closure.apks.push(apk);
            } else {
                // Failed, enable all ABIs and terminate build.
                this.enableABI();
                closure.callback("Building ABI '" + abi + "' failed");
                return;
            }

            // Delete unaligned APK, so only the ones that are to be used
            // remain, and there's no confusion.
            ShellJS.rm("bin" + Path.sep + "*-debug-unaligned.apk");

            // Build next ABI.
            this.buildABI(closure);
            return;

        } else {
            // Failed, enable all ABIs and terminate build.
            this.enableABI();
            closure.callback("Building ABI '" + abi + "' failed");
            return;
        }
    }.bind(this));
};

/**
 * Apply icon if none yet, or source has higher quality
 * @param {String} srcPath Icon to apply
 * @param {String} dstDir Path to destination directory
 * @param {String} iconFilename Destination icon filename without extension
 * @param {Function} callback Error callback
 * @returns {Boolean} True if applied, otherwise false.
 */
AndroidPlatform.prototype.applyIcon =
function(srcPath, dstDir, iconFilename, callback) {

    var output = this.application.output;

    // Different image types get different priorities.
    var score = {
        "png": 3,
        "jpeg": 2,
        "jpg": 2,
        "gif": 1
    };

    // extname() includes the ".", so strip it
    var srcExt = Path.extname(srcPath);
    if (srcExt && srcExt[0] === ".")
        srcExt = srcExt.substring(1);

    var srcScore = score[srcExt.toLowerCase()];
    if (!srcScore) {
        output.warning("Image type not supported: " + srcPath);
        return false;
    }

    // Replace existing icon if we have a better one.
    var curPath = null;
    var curScore = -1;
    var ls = ShellJS.ls(Path.join(dstDir, iconFilename + "*"));
    if (ls.length > 1) {
        output.warning("Unexpected extra files in " + dstDir);
    }
    if (ls.length > 0) {

        // extname() includes the ".", so strip it
        curPath = ls[0];
        var curExt = Path.extname(curPath);
        if (curExt && curExt[0] === ".")
            curExt = curExt.substring(1);

        curScore = +score[curExt.toLowerCase()];
    }

    if (srcScore >= curScore) {
        if (curPath) {
            // We have found a better quality icon
            ShellJS.rm(curPath);
        }
        var dstPath = Path.join(dstDir, iconFilename + Path.extname(srcPath));
        ShellJS.cp("-f", srcPath, dstPath);
    }

    return true;
};

/**
 * Update launcher icons.
 * @param {AndroidManifest} androidManifest
 * @param {Function} callback Error callback
 */
AndroidPlatform.prototype.updateIcons =
function(androidManifest, callback) {

    var output = this.application.output;

    // See http://iconhandbook.co.uk/reference/chart/android/
    var sizes = {
        "ldpi": 36,
        "mdpi": 48,
        "hdpi": 72,
        "xhdpi": 96,
        "xxhdpi": 144,
        "xxxhdpi": 192,
        match: function(size) {

            // Default to "hdpi", android will scale.
            if (size === "any")
                return "hdpi";

            // Match size as per categories above.
            // Start from the biggest size, and pick the first
            // one where the icon is bigger or same.
            var keys = Object.keys(this);
            for (var k = keys.length - 1; k >= 0; k--) {
                var prop = keys[k];
                if (size >= this[prop]) {
                    return prop;
                }
            }
            // Default to smallest size when below 36.
            return "ldpi";
        }
    };

    var nUpdated = 0;
    var iconFilename = "crosswalk_icon";

    // Add icons from manifest
    var icons = this.application.manifest.icons;
    if (icons && icons.length > 0) {

        // Remove existing icons, so we don't have stale ones around
        // FIXME check that no icon was added manually.
        ShellJS.rm("-rf", Path.join(this.platformPath, "res", "mipmap-*"));

        for (var i = 0; i < icons.length; i++) {

            var icon = icons[i];
            var size = icon.sizes ? +icon.sizes.split("x")[0] : "any";
            var density = sizes.match(size);

            // Copy icon into place
            // Icon will always be named crosswalk-icon.<ext>
            // Because android:icon has no way to refer to different sizes.
            var src = Path.join(this.appPath, icon.src);
            var dstPath = Path.join(this.platformPath, "res", "mipmap-" + density);
            ShellJS.mkdir(dstPath);

            var ret = this.applyIcon(src, dstPath, iconFilename, callback);
            if (ret)
                nUpdated++;
        }
    }

    if (nUpdated > 0) {
        androidManifest.applicationIcon = "@mipmap/" + iconFilename;
    } else {
        output.warning("No usable icons found in manifest.json");
        output.warning("Using builtin default icon");

        // Fall back to the default icon
        androidManifest.applicationIcon = "@drawable/crosswalk";

        // Make sure the icon is present.
        ShellJS.cp(Path.join(__dirname, "..", "..", "app-template", "icon.png"),
                   Path.join(this.platformPath, "res", "drawable-hdpi", "crosswalk.png"));
    }

    return nUpdated;
};

/**
 * Configure crosswalk runtime.
 */
AndroidPlatform.prototype.updateEngine =
function() {

    var output = this.application.output;

    // Write command-line params file.
    var path = Path.join(this.platformPath, "assets", "xwalk-command-line");

    if (this.application.manifest.commandLine) {
        // Write file.
        output.info("Writing command-line parameters file");
        var commandLine = "xwalk " + this.application.manifest.commandLine;
        FS.writeFileSync(path, commandLine);
    } else {
        // Delete file to make sure there's not a stale one
        ShellJS.rm(path);
    }
};

/**
 * Update android manifest.
 * @param {Function} callback Error callback
 * @returns {AndroidManifest}
 */
AndroidPlatform.prototype.updateManifest =
function(callback) {

    var output = this.application.output;

    var manifest = new AndroidManifest(output,
                                       Path.join(this.platformPath, "AndroidManifest.xml"));

    // Renaming package is not supported.
    if (manifest.package !== this.application.manifest.packageId) {
        callback("Renaming of package not supported (" +
                 manifest.package + "/" + this.application.manifest.packageId + ")");
        return null;
    }

    manifest.versionName = this.application.manifest.appVersion;
    manifest.applicationLabel = this.application.manifest.name;

    // Update icons
    this.updateIcons(manifest, callback);

    // Update orientation
    switch (this.application.manifest.orientation) {
    case "any":
        manifest.screenOrientation = "unspecified";
        break;
    case "natural":
        manifest.screenOrientation = "sensor";
        break;
    case "landscape":
        manifest.screenOrientation = "sensorLandscape";
        break;
    case "portrait":
        manifest.screenOrientation = "sensorPortrait";
        break;
    case "portrait-primary":
        manifest.screenOrientation = "portrait";
        break;
    case "portrait-secondary":
        manifest.screenOrientation = "reversePortrait";
        break;
    case "landscape-primary":
        manifest.screenOrientation = "landscape";
        break;
    case "landscape-secondary":
        manifest.screenOrientation = "reverseLandscape";
        break;
    default:
        output.warning("Unsupported orientation value in web manifest: " + this.application.manifest.orientation);
    }

    // Update permissions
    manifest.permissions = this.application.manifest.androidPermissions;

    return manifest;
};

/**
 * Update java activity file for build config.
 * @param {Boolean} release True if release build, false if debug
 * @param {String} activityClassName Class ame for the Activity
 * @returns {Boolean} True if successful, otherwise false.
 */
AndroidPlatform.prototype.updateJavaActivity =
function(release, activityClassName) {

    var output = this.application.output;
    var ret = true;

    // Update java
    var config = release ? "release" : "debug";
    output.info("Updating java activity for '" + config + "' configuration");

    var dir = JavaActivity.pathForPackage(this.platformPath, this.packageId);
    var path = Path.join(dir, activityClassName + ".java");
    var activity = new JavaActivity(output, path);

    // Enable remote debugging for debug builds.
    ret = activity.enableRemoteDebugging(!release);
    if (!ret)
        return false;

    // Animatable view
    ret = activity.enableAnimatableView(this.application.manifest.androidAnimatableView);
    if (!ret)
        return false;

    // Fullscreen
    var fullscreen = this.application.manifest.display === "fullscreen";
    ret = activity.enableFullscreen(fullscreen);
    if (!ret)
        return false;

    // "Keep screen on"
    ret = activity.enableKeepScreenOn(this.application.manifest.androidKeepScreenOn);
    if (!ret)
        return false;

    return ret;
};

/**
 * Convert assets to webp format
 */
AndroidPlatform.prototype.updateWebApp =
function() {

    var output = this.application.output;

    // Always copy over the app tree to the android project
    var wwwPath = Path.join(this.platformPath, "assets", "www");
    ShellJS.rm("-rf", wwwPath + Path.sep + "*");
    output.info("Copying app to", wwwPath);
    ShellJS.cp("-rf", this.appPath + Path.sep + "*", wwwPath);

    var params = this.application.manifest.androidWebp;
    if (!params) {
        // No webp conversion needed.
        return;
    }

    output.info("Converting image assets to webp format (" + params + ")");

    // Check for conversion tool
    var cwebp = ShellJS.which("cwebp");
    output.info("Checking for cwebp ...", cwebp);
    if (!cwebp) {
        output.warning("Webp conversion tool not found, install from http://downloads.webmproject.org/releases/webp");
        output.warning("Webp conversion failed, packaging unconverted assets");
        return;
    }

    // Quality parameters
    var jpegQuality = 80;
    var pngQuality = 80;
    var pngAlphaQuality = 80;
    var argsList = [];
    if (typeof params === "string")
        argsList = params.split(/[ ,]+/);
    if (argsList && argsList.length > 0)
        jpegQuality = argsList[0];
    if (argsList && argsList.length > 1)
        pngQuality = argsList[1];
    if (argsList && argsList.length > 2)
        pngAlphaQuality = argsList[2];

    // Directory traversal function
    function walk(dir) {
        var results = [];
        var list = FS.readdirSync(dir);
        list.forEach(function(file) {
            file = dir + "/" + file;
            var stat = FS.statSync(file);
            if (stat && stat.isDirectory())
                results = results.concat(walk(file));
            else
                results.push(file);
        });
        return results;
    }

    // Do conversion
    var fileList = walk(wwwPath);
    var progress = output.createInfiniteProgress("Converting images to webp");
    for (var i in fileList) {
        if (FS.lstatSync(fileList[i]).isFile()) {
            var filePath = fileList[i];
            var tmpFilePath = filePath + ".webp";
            var ext = Path.extname(filePath);
            progress.update(filePath);
            if (".jpeg" == ext || ".jpg" == ext) {
                execSync(cwebp +
                         " " + filePath +
                         " -q " + jpegQuality +
                         " -o " + tmpFilePath);
                ShellJS.mv("-f", tmpFilePath, filePath);
            } else if (".png" == ext) {
                execSync(cwebp +
                         " " + filePath +
                         " -q " + pngQuality +
                         " -alpha_q " + pngAlphaQuality +
                         " -o " + tmpFilePath);
                ShellJS.mv("-f", tmpFilePath, filePath);
            }
        }
    }
    progress.done();

    var logOutput = this.logOutput;
    var execSyncImpl;
    function execSync(cmd) {

        // On first run, work out which implementation to use.
        if (typeof execSyncImpl === "undefined") {
            if (ChildProcess.execSync) {
                // Nodejs >= 0.12
                execSyncImpl = ChildProcess.execSync;
            } else {
                // Try to use npm module.
                try {
                    // Exec-sync does throw even though it works, so let's use this hack,
                    // it's just for nodejs 0.10 compat anyway.
                    execSyncImpl = function(cmd) { try { return require("exec-sync")(cmd); } catch (e) {} return null; };
                } catch (e) {
                    output.error("NPM module 'exec-sync' not found");
                    output.error("Please install this package manually when on nodejs < 0.12");
                    execSyncImpl = null;
                }
            }
        }

        if (execSyncImpl !== null) {
            var ret = execSyncImpl(cmd);
            if (ret) {
                logOutput.write(cmd + "\n" + ret + "\n");
            }
        }
    }
};

/**
 * Wrapper for ChildProcess.execSync to preserve some support for nodejs 0.10
 * This can probably go away with Fedora 23.
 */
AndroidPlatform.prototype.execSync =
function(cmd) {

    var execSyncImpl;
    if (ChildProcess.execSync) {
        // Nodejs >= 0.12
        execSyncImpl = ChildProcess.execSync;
    } else {
        // Try to use npm module.
        try {
            // Exec-sync does throw even though it works, so let's use this hack,
            // it's just for nodejs 0.10 compat anyway.
            execSyncImpl = function(cmd) { try { return require("exec-sync")(cmd); } catch (e) {} return null; };
        } catch (e) {
            output.error("NPM module 'exec-sync' not found");
            output.error("Please install this package manually when on nodejs < 0.12");
            execSyncImpl = null;
        }
    }

    if (execSyncImpl !== null) {
        return execSyncImpl(cmd);
    }

    return null;
};

/**
 * Import extensions.
 * The directory of one external extension should be like:
 *   myextension/
 *     myextension.jar
 *     myextension.js
 *     myextension.json
 * That means the name of the internal files should be the same as the
 * directory name.
 * For .jar files, they'll be copied to libs/ and then
 * built into classes.dex in the APK.
 * For .json/.js files, they'll be copied into assets/xwalk-extensions/myextension.
 */
AndroidPlatform.prototype.importExtensions =
function() {

    var output = this.application.output;

    var extensionsPerms = [];
    this.application.manifest.extensions.forEach(function (extPath) {

        // Test integrity
        if (!ShellJS.test("-d", extPath)) {
            output.warning("Skipping invalid extension dir " + extPath);
            return;
        }
        var extName = Path.basename(extPath);

        var jarPath = Path.join(extPath, extName + ".jar");
        if (!ShellJS.test("-f", jarPath)) {
            output.warning("Skipping extension, file not found " + jarPath);
            return;
        }

        var jsonPath = Path.join(extPath, extName + ".json");
        if (!ShellJS.test("-f", jsonPath)) {
            output.warning("Skipping extension, file not found " + jsonPath);
            return;
        }

        var extRootPath = Path.join(this.platformPath, "assets", "xwalk-extensions");
        var jsonDstPath = Path.join(extRootPath, extName);
        var jsonBuf = FS.readFileSync(jsonPath, {"encoding": "utf8"});
        var configJson = JSON.parse(jsonBuf);
        // jsapi is optional
        if (configJson.jsapi) {
            // Copy js
            var jsPath = Path.join(extPath, configJson.jsapi);
            if (!ShellJS.test("-f", jsPath)) {
                output.warning("Skipping extension, file not found " + jsPath);
                return;
            }
            ShellJS.mkdir(extRootPath);
            ShellJS.mkdir(jsonDstPath);
            ShellJS.cp("-f", jsPath, jsonDstPath);
        }

        // Copy json
        ShellJS.mkdir(extRootPath);
        ShellJS.mkdir(jsonDstPath);
        ShellJS.cp("-f", jsonPath, jsonDstPath);
        // Copy jar
        ShellJS.cp("-f", jarPath, Path.join(this.platformPath, "libs"));

        // Accumulate permissions
        for (var i = 0; configJson.permissions && i < configJson.permissions.length; i++) {
            var perm = configJson.permissions[i];
            // Support both android.permission.FOO namespaced and plain
            // version by using last component.
            perm = perm.split(".").pop();
            extensionsPerms.push(perm);
        }

    }.bind(this));

    // Add permissions to manifest, so they end up in AndroidManifest.xml later
    extensionsPerms.forEach(function (perm) {
        var perms = this.application.manifest.androidPermissions;
        if (perms.indexOf(perm) < 0) {
            perms.push(perm);
        }
    }.bind(this));
};

/**
 * Update app theme.
 * @param {AndroidManifest} androidManifest
 * @returns {Boolean} true on success.
 */
AndroidPlatform.prototype.updateXmlTheme =
function(androidManifest) {

    var output = this.application.output;

    var fullscreen = this.application.manifest.display === "fullscreen";
    output.info("Updating theme.xml for display mode (fullscreen: " + (fullscreen ? "yes" : "no") + ")");

    var theme = new XmlTheme(output,
                             Path.join(this.platformPath, "res", "values-v14", "theme.xml"));
    theme.fullscreen = fullscreen;

    // White is default, set colour if not white.
    var bgColor = this.application.manifest.backgroundColor;
    return theme.setSplash(bgColor, androidManifest.applicationIcon);
};

/**
 * Implements {@link PlatformBase.build}
 */
AndroidPlatform.prototype.build =
function(configId, args, callback) {

    var output = this.application.output;

    // TODO should we cd back afterwards?
    process.chdir(this.platformPath);

    // TODO this is no more needed after crosswalk-app deprecation
    args.targets = this.parseTargets(args.targets);

    // Embedded or shared build?
    var abis = [];
    var libPath = Path.join(this.platformPath, "xwalk_core_library", "libs");
    if (ShellJS.test("-d", Path.join(this.platformPath, "xwalk_shared_library"))) {
        this._shared = true;
        abis = [ "shared" ];

    } else if (!args.targets || args.targets.length === 0) {
        // Build all available ABIs
        ShellJS.ls(libPath).forEach(function (lib) {
            if (ShellJS.test("-d", Path.join(libPath, lib))) {
                abis.push(lib);
            }
        }.bind(this));

    } else if (args.targets.length > 0) {
        // Build specified target ABIs.
        args.targets.forEach(function (abi) {
            if (ShellJS.test("-d", Path.join(libPath, abi))) {
                abis.push(abi);
            } else {
                output.error("Failed to find libxwalkcore.so for " + abi + ", skipping");
            }
        });

    } else {
        callback("Failed to determine which ABIs to build");
        return;
    }

    this.updateEngine();
    this.importExtensions();
    var androidManifest = this.updateManifest(callback);
    if (!androidManifest) {
        // Callback already called from updateManifest
        return;
    }
    this.updateJavaActivity(configId === "release", androidManifest.activityClassName);
    this.updateWebApp(this.application.manifest.androidWebp);
    this.updateXmlTheme(androidManifest);

    var closure = {
        abis: abis,
        abiIndex : 0,
        release: configId == "release", // TODO verify above
        apks: [],
        callback: function(errormsg) {

            if (!errormsg &&
                closure.apks.length > 0) {

                for (var i = 0; i < closure.apks.length; i++) {

                    // Export APKs to package folder
                    var packagePath = Path.join(this.platformPath, "bin", closure.apks[i]);
                    this.exportPackage(packagePath);

                    output.highlight("Package: " + closure.apks[i]);
                }
                if (configId === "release") {
                    output.highlight("APKs need to be signed before publishing, see");
                    output.highlight("https://developer.android.com/tools/publishing/app-signing.html#signing-manually");
                }
            }
            callback(errormsg);
        }.bind(this)
    };

    // This builds all ABIs in a recursion (of sorts).
    this.buildABI(closure);
};

module.exports = AndroidPlatform;


text:
<?php

namespace stubbles\test\ioc;
/**
 * Helper class for optional constructor injection.
 *
 * @since  2.0.0
 */
class BikeWithOptionalTire implements Vehicle
{
    /**
     * injected tire instance
     *
     * @type  Tire
     */
    public $tire;

    /**
     * sets the tire
     *
     * @param  Tire  $tire
     */
    public function __construct(Tire $tire = null)
    {
        $this->tire = ((null === $tire) ? (new Goodyear()) : ($tire));
    }

    /**
     * moves the vehicle forward
     *
     * @return  string
     */
    public function moveForward()
    {
        return $this->tire->rotate();
    }
}


text:
package net.oneandone.concierge.api.filter;

import lombok.AllArgsConstructor;
import lombok.Getter;
import net.oneandone.concierge.api.Addressable;

/**
 * An address filter.
 *
 * @see Addressable#address()
 */
@AllArgsConstructor
public class AddressFilter implements Filter {

    /** The address to accept. */
    @Getter private final String address;

}