text:
--beginvalidatingquery
	if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_DatabaseVersion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
    begin
            declare @ver int
            exec @ver=sp_DatabaseVersion
            if (@ver >= 7019)
				select 0, 'Already correct database version'
            else if (@ver = 7018)
                 select 1, 'Upgrading database'
            else
                 select -1, 'Invalid database version detected'
    end
    else
            select -1, 'Not an EPiServer database'
--endvalidatingquery

GO
PRINT N'Dropping [dbo].[DF_tblMappedIdentity_ContentGuid]...';

GO
ALTER TABLE [dbo].[tblMappedIdentity] DROP CONSTRAINT [DF_tblMappedIdentity_ContentGuid];

GO
PRINT N'Starting rebuilding table [dbo].[tblMappedIdentity]...';

GO
BEGIN TRANSACTION;

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

CREATE TABLE [dbo].[tmp_ms_xx_tblMappedIdentity] (
    [pkID]                   INT              IDENTITY (1, 1) NOT NULL,
    [Provider]               NVARCHAR (255)   NOT NULL,
    [ProviderUniqueId]       NVARCHAR (450)   NOT NULL,
    [ContentGuid]            UNIQUEIDENTIFIER CONSTRAINT [DF_tblMappedIdentity_ContentGuid] DEFAULT (NEWID()) NOT NULL,
    [ExistingContentId]      INT              NULL,
    [ExistingCustomProvider] BIT              NULL,
    CONSTRAINT [tmp_ms_xx_constraint_PK_tblMappedIdentity] PRIMARY KEY NONCLUSTERED ([pkID] ASC)
);

CREATE CLUSTERED INDEX [tmp_ms_xx_index_IDX_tblMappedIdentity_ProviderUniqueId]
    ON [dbo].[tmp_ms_xx_tblMappedIdentity]([ProviderUniqueId] ASC);

IF EXISTS (SELECT TOP 1 1
           FROM   [dbo].[tblMappedIdentity])
    BEGIN
        SET IDENTITY_INSERT [dbo].[tmp_ms_xx_tblMappedIdentity] ON;
        INSERT INTO [dbo].[tmp_ms_xx_tblMappedIdentity] ([ProviderUniqueId], [pkID], [Provider], [ContentGuid], [ExistingContentId], [ExistingCustomProvider])
        SELECT   [ProviderUniqueId],
                 [pkID],
                 [Provider],
                 [ContentGuid],
                 [ExistingContentId],
                 [ExistingCustomProvider]
        FROM     [dbo].[tblMappedIdentity]
        ORDER BY [ProviderUniqueId] ASC;
        SET IDENTITY_INSERT [dbo].[tmp_ms_xx_tblMappedIdentity] OFF;
    END

DROP TABLE [dbo].[tblMappedIdentity];

EXECUTE sp_rename N'[dbo].[tmp_ms_xx_tblMappedIdentity]', N'tblMappedIdentity';

EXECUTE sp_rename N'[dbo].[tblMappedIdentity].[tmp_ms_xx_index_IDX_tblMappedIdentity_ProviderUniqueId]', N'IDX_tblMappedIdentity_ProviderUniqueId', N'INDEX';

EXECUTE sp_rename N'[dbo].[tmp_ms_xx_constraint_PK_tblMappedIdentity]', N'PK_tblMappedIdentity', N'OBJECT';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

GO
PRINT N'Creating [dbo].[tblMappedIdentity].[IDX_tblMappedIdentity_Provider]...';

GO
CREATE NONCLUSTERED INDEX [IDX_tblMappedIdentity_Provider]
    ON [dbo].[tblMappedIdentity]([Provider] ASC);

GO
PRINT N'Creating [dbo].[tblMappedIdentity].[IDX_tblMappedIdentity_ContentGuid]...';

GO
CREATE UNIQUE NONCLUSTERED INDEX [IDX_tblMappedIdentity_ContentGuid]
    ON [dbo].[tblMappedIdentity]([ContentGuid] ASC);

GO
PRINT N'Creating [dbo].[tblMappedIdentity].[IDX_tblMappedIdentity_ExternalId]...';

GO
CREATE NONCLUSTERED INDEX [IDX_tblMappedIdentity_ExternalId]
    ON [dbo].[tblMappedIdentity]([ExistingContentId] ASC, [ExistingCustomProvider] ASC);

GO
PRINT N'Creating [dbo].[netMappedIdentityDeleteItems]...';

GO
CREATE PROCEDURE [dbo].[netMappedIdentityDeleteItems]
	@ContentGuids dbo.GuidParameterTable READONLY
AS
BEGIN
	SET NOCOUNT ON;

	DELETE mi
	FROM tblMappedIdentity mi
	INNER JOIN @ContentGuids cg ON mi.ContentGuid = cg.Id
END

GO
PRINT N'Altering [dbo].[sp_DatabaseVersion]...';

GO
ALTER PROCEDURE [dbo].[sp_DatabaseVersion]
AS
	RETURN 7019
GO
PRINT N'Update complete.';

GO


text:
package smartHome;

import java.io.File;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

import smartHome.exceptions.CorruptSettingsFile;
import smartHome.exceptions.SettingsNotSetException;

@SpringBootApplication
@ComponentScan({ "smartHome.controllable", "smartHome.controllable.command",
		"smartHome.controllable.controllableObjects", "smartHome.services", "smartHome" })
public class Application {
	private static File settingsLocation;

	public static void main(String[] args) throws Throwable {
		deriveSettingsLocation(args);
		SpringApplication.run(Application.class, args);
	}

	private static void deriveSettingsLocation(String[] args) throws CorruptSettingsFile {
		try {
			settingsLocation = checkArgumentsForSettings(args);
		} catch (SettingsNotSetException e) {
			System.out.println("Please provide location of settings.xml:");
			settingsLocation = new File(System.console().readLine());
		}
		if (!settingsLocation.exists()) {
			throw new CorruptSettingsFile();
		}
	}

	private static File checkArgumentsForSettings(String[] args) throws SettingsNotSetException {
		boolean isNextSettingsPath = false;
		for (int i = 0; i < args.length; i++) {
			if (isNextSettingsPath) {
				return new File(args[i]);
			} else if (args[i].equals("-s")) {
				isNextSettingsPath = true;
			}
		}

		throw new SettingsNotSetException();
	}

	public static File getSettingsLocation() {
		return settingsLocation;
	}
}

redpajama_set_name: RedPajamaGithub


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const createHash = require("../util/createHash");
const { makePathsRelative } = require("../util/identifier");
const numberHash = require("../util/numberHash");

/** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../ChunkGraph")} ChunkGraph */
/** @typedef {import("../Compilation")} Compilation */
/** @typedef {import("../Module")} Module */
/** @typedef {typeof import("../util/Hash")} Hash */

/**
 * @param {string} str string to hash
 * @param {number} len max length of the hash
 * @param {string | Hash} hashFunction hash function to use
 * @returns {string} hash
 */
const getHash = (str, len, hashFunction) => {
	const hash = createHash(hashFunction);
	hash.update(str);
	const digest = /** @type {string} */ (hash.digest("hex"));
	return digest.substr(0, len);
};

/**
 * @param {string} str the string
 * @returns {string} string prefixed by an underscore if it is a number
 */
const avoidNumber = str => {
	// max length of a number is 21 chars, bigger numbers a written as "...e+xx"
	if (str.length > 21) return str;
	const firstChar = str.charCodeAt(0);
	// skip everything that doesn't look like a number
	// charCodes: "-": 45, "1": 49, "9": 57
	if (firstChar < 49) {
		if (firstChar !== 45) return str;
	} else if (firstChar > 57) {
		return str;
	}
	if (str === +str + "") {
		return `_${str}`;
	}
	return str;
};

/**
 * @param {string} request the request
 * @returns {string} id representation
 */
const requestToId = request => {
	return request
		.replace(/^(\.\.?\/)+/, "")
		.replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_");
};
exports.requestToId = requestToId;

/**
 * @param {string} string the string
 * @param {string} delimiter separator for string and hash
 * @param {string | Hash} hashFunction hash function to use
 * @returns {string} string with limited max length to 100 chars
 */
const shortenLongString = (string, delimiter, hashFunction) => {
	if (string.length < 100) return string;
	return (
		string.slice(0, 100 - 6 - delimiter.length) +
		delimiter +
		getHash(string, 6, hashFunction)
	);
};

/**
 * @param {Module} module the module
 * @param {string} context context directory
 * @param {Object=} associatedObjectForCache an object to which the cache will be attached
 * @returns {string} short module name
 */
const getShortModuleName = (module, context, associatedObjectForCache) => {
	const libIdent = module.libIdent({ context, associatedObjectForCache });
	if (libIdent) return avoidNumber(libIdent);
	const nameForCondition = module.nameForCondition();
	if (nameForCondition)
		return avoidNumber(
			makePathsRelative(context, nameForCondition, associatedObjectForCache)
		);
	return "";
};
exports.getShortModuleName = getShortModuleName;

/**
 * @param {string} shortName the short name
 * @param {Module} module the module
 * @param {string} context context directory
 * @param {string | Hash} hashFunction hash function to use
 * @param {Object=} associatedObjectForCache an object to which the cache will be attached
 * @returns {string} long module name
 */
const getLongModuleName = (
	shortName,
	module,
	context,
	hashFunction,
	associatedObjectForCache
) => {
	const fullName = getFullModuleName(module, context, associatedObjectForCache);
	return `${shortName}?${getHash(fullName, 4, hashFunction)}`;
};
exports.getLongModuleName = getLongModuleName;

/**
 * @param {Module} module the module
 * @param {string} context context directory
 * @param {Object=} associatedObjectForCache an object to which the cache will be attached
 * @returns {string} full module name
 */
const getFullModuleName = (module, context, associatedObjectForCache) => {
	return makePathsRelative(
		context,
		module.identifier(),
		associatedObjectForCache
	);
};
exports.getFullModuleName = getFullModuleName;

/**
 * @param {Chunk} chunk the chunk
 * @param {ChunkGraph} chunkGraph the chunk graph
 * @param {string} context context directory
 * @param {string} delimiter delimiter for names
 * @param {string | Hash} hashFunction hash function to use
 * @param {Object=} associatedObjectForCache an object to which the cache will be attached
 * @returns {string} short chunk name
 */
const getShortChunkName = (
	chunk,
	chunkGraph,
	context,
	delimiter,
	hashFunction,
	associatedObjectForCache
) => {
	const modules = chunkGraph.getChunkRootModules(chunk);
	const shortModuleNames = modules.map(m =>
		requestToId(getShortModuleName(m, context, associatedObjectForCache))
	);
	chunk.idNameHints.sort();
	const chunkName = Array.from(chunk.idNameHints)
		.concat(shortModuleNames)
		.filter(Boolean)
		.join(delimiter);
	return shortenLongString(chunkName, delimiter, hashFunction);
};
exports.getShortChunkName = getShortChunkName;

/**
 * @param {Chunk} chunk the chunk
 * @param {ChunkGraph} chunkGraph the chunk graph
 * @param {string} context context directory
 * @param {string} delimiter delimiter for names
 * @param {string | Hash} hashFunction hash function to use
 * @param {Object=} associatedObjectForCache an object to which the cache will be attached
 * @returns {string} short chunk name
 */
const getLongChunkName = (
	chunk,
	chunkGraph,
	context,
	delimiter,
	hashFunction,
	associatedObjectForCache
) => {
	const modules = chunkGraph.getChunkRootModules(chunk);
	const shortModuleNames = modules.map(m =>
		requestToId(getShortModuleName(m, context, associatedObjectForCache))
	);
	const longModuleNames = modules.map(m =>
		requestToId(
			getLongModuleName("", m, context, hashFunction, associatedObjectForCache)
		)
	);
	chunk.idNameHints.sort();
	const chunkName = Array.from(chunk.idNameHints)
		.concat(shortModuleNames, longModuleNames)
		.filter(Boolean)
		.join(delimiter);
	return shortenLongString(chunkName, delimiter, hashFunction);
};
exports.getLongChunkName = getLongChunkName;

/**
 * @param {Chunk} chunk the chunk
 * @param {ChunkGraph} chunkGraph the chunk graph
 * @param {string} context context directory
 * @param {Object=} associatedObjectForCache an object to which the cache will be attached
 * @returns {string} full chunk name
 */
const getFullChunkName = (
	chunk,
	chunkGraph,
	context,
	associatedObjectForCache
) => {
	if (chunk.name) return chunk.name;
	const modules = chunkGraph.getChunkRootModules(chunk);
	const fullModuleNames = modules.map(m =>
		makePathsRelative(context, m.identifier(), associatedObjectForCache)
	);
	return fullModuleNames.join();
};
exports.getFullChunkName = getFullChunkName;

/**
 * @template K
 * @template V
 * @param {Map<K, V[]>} map a map from key to values
 * @param {K} key key
 * @param {V} value value
 * @returns {void}
 */
const addToMapOfItems = (map, key, value) => {
	let array = map.get(key);
	if (array === undefined) {
		array = [];
		map.set(key, array);
	}
	array.push(value);
};

/**
 * @param {Compilation} compilation the compilation
 * @param {function(Module): boolean=} filter filter modules
 * @returns {[Set<string>, Module[]]} used module ids as strings and modules without id matching the filter
 */
const getUsedModuleIdsAndModules = (compilation, filter) => {
	const chunkGraph = compilation.chunkGraph;

	const modules = [];

	/** @type {Set<string>} */
	const usedIds = new Set();
	if (compilation.usedModuleIds) {
		for (const id of compilation.usedModuleIds) {
			usedIds.add(id + "");
		}
	}

	for (const module of compilation.modules) {
		if (!module.needId) continue;
		const moduleId = chunkGraph.getModuleId(module);
		if (moduleId !== null) {
			usedIds.add(moduleId + "");
		} else {
			if (
				(!filter || filter(module)) &&
				chunkGraph.getNumberOfModuleChunks(module) !== 0
			) {
				modules.push(module);
			}
		}
	}

	return [usedIds, modules];
};
exports.getUsedModuleIdsAndModules = getUsedModuleIdsAndModules;

/**
 * @param {Compilation} compilation the compilation
 * @returns {Set<string>} used chunk ids as strings
 */
const getUsedChunkIds = compilation => {
	/** @type {Set<string>} */
	const usedIds = new Set();
	if (compilation.usedChunkIds) {
		for (const id of compilation.usedChunkIds) {
			usedIds.add(id + "");
		}
	}

	for (const chunk of compilation.chunks) {
		const chunkId = chunk.id;
		if (chunkId !== null) {
			usedIds.add(chunkId + "");
		}
	}

	return usedIds;
};
exports.getUsedChunkIds = getUsedChunkIds;

/**
 * @template T
 * @param {Iterable<T>} items list of items to be named
 * @param {function(T): string} getShortName get a short name for an item
 * @param {function(T, string): string} getLongName get a long name for an item
 * @param {function(T, T): -1|0|1} comparator order of items
 * @param {Set<string>} usedIds already used ids, will not be assigned
 * @param {function(T, string): void} assignName assign a name to an item
 * @returns {T[]} list of items without a name
 */
const assignNames = (
	items,
	getShortName,
	getLongName,
	comparator,
	usedIds,
	assignName
) => {
	/** @type {Map<string, T[]>} */
	const nameToItems = new Map();

	for (const item of items) {
		const name = getShortName(item);
		addToMapOfItems(nameToItems, name, item);
	}

	/** @type {Map<string, T[]>} */
	const nameToItems2 = new Map();

	for (const [name, items] of nameToItems) {
		if (items.length > 1 || !name) {
			for (const item of items) {
				const longName = getLongName(item, name);
				addToMapOfItems(nameToItems2, longName, item);
			}
		} else {
			addToMapOfItems(nameToItems2, name, items[0]);
		}
	}

	/** @type {T[]} */
	const unnamedItems = [];

	for (const [name, items] of nameToItems2) {
		if (!name) {
			for (const item of items) {
				unnamedItems.push(item);
			}
		} else if (items.length === 1 && !usedIds.has(name)) {
			assignName(items[0], name);
			usedIds.add(name);
		} else {
			items.sort(comparator);
			let i = 0;
			for (const item of items) {
				while (nameToItems2.has(name + i) && usedIds.has(name + i)) i++;
				assignName(item, name + i);
				usedIds.add(name + i);
				i++;
			}
		}
	}

	unnamedItems.sort(comparator);
	return unnamedItems;
};
exports.assignNames = assignNames;

/**
 * @template T
 * @param {T[]} items list of items to be named
 * @param {function(T): string} getName get a name for an item
 * @param {function(T, T): -1|0|1} comparator order of items
 * @param {function(T, number): boolean} assignId assign an id to an item
 * @param {number[]} ranges usable ranges for ids
 * @param {number} expandFactor factor to create more ranges
 * @param {number} extraSpace extra space to allocate, i. e. when some ids are already used
 * @param {number} salt salting number to initialize hashing
 * @returns {void}
 */
const assignDeterministicIds = (
	items,
	getName,
	comparator,
	assignId,
	ranges = [10],
	expandFactor = 10,
	extraSpace = 0,
	salt = 0
) => {
	items.sort(comparator);

	// max 5% fill rate
	const optimalRange = Math.min(
		Math.ceil(items.length * 20) + extraSpace,
		Number.MAX_SAFE_INTEGER
	);

	let i = 0;
	let range = ranges[i];
	while (range < optimalRange) {
		i++;
		if (i < ranges.length) {
			range = Math.min(ranges[i], Number.MAX_SAFE_INTEGER);
		} else if (expandFactor) {
			range = Math.min(range * expandFactor, Number.MAX_SAFE_INTEGER);
		} else {
			break;
		}
	}

	for (const item of items) {
		const ident = getName(item);
		let id;
		let i = salt;
		do {
			id = numberHash(ident + i++, range);
		} while (!assignId(item, id));
	}
};
exports.assignDeterministicIds = assignDeterministicIds;

/**
 * @param {Set<string>} usedIds used ids
 * @param {Iterable<Module>} modules the modules
 * @param {Compilation} compilation the compilation
 * @returns {void}
 */
const assignAscendingModuleIds = (usedIds, modules, compilation) => {
	const chunkGraph = compilation.chunkGraph;

	let nextId = 0;
	let assignId;
	if (usedIds.size > 0) {
		assignId = module => {
			if (chunkGraph.getModuleId(module) === null) {
				while (usedIds.has(nextId + "")) nextId++;
				chunkGraph.setModuleId(module, nextId++);
			}
		};
	} else {
		assignId = module => {
			if (chunkGraph.getModuleId(module) === null) {
				chunkGraph.setModuleId(module, nextId++);
			}
		};
	}
	for (const module of modules) {
		assignId(module);
	}
};
exports.assignAscendingModuleIds = assignAscendingModuleIds;

/**
 * @param {Iterable<Chunk>} chunks the chunks
 * @param {Compilation} compilation the compilation
 * @returns {void}
 */
const assignAscendingChunkIds = (chunks, compilation) => {
	const usedIds = getUsedChunkIds(compilation);

	let nextId = 0;
	if (usedIds.size > 0) {
		for (const chunk of chunks) {
			if (chunk.id === null) {
				while (usedIds.has(nextId + "")) nextId++;
				chunk.id = nextId;
				chunk.ids = [nextId];
				nextId++;
			}
		}
	} else {
		for (const chunk of chunks) {
			if (chunk.id === null) {
				chunk.id = nextId;
				chunk.ids = [nextId];
				nextId++;
			}
		}
	}
};
exports.assignAscendingChunkIds = assignAscendingChunkIds;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Lighthouse: lapack/sgttrs.f File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="tabs.css" rel="stylesheet" type="text/css" />
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

lapack

Functions/Subroutines

sgttrs.f File Reference

Functions/Subroutines

subroutine 	sgttrs (TRANS, N, NRHS, DL, D, DU, DU2, IPIV, B, LDB, INFO)

 	SGTTRS

Function/Subroutine Documentation

          subroutine sgttrs
          (
          character
          TRANS,

          integer
          N,

          integer
          NRHS,

          real, dimension( * )
          DL,

          real, dimension( * )
          D,

          real, dimension( * )
          DU,

          real, dimension( * )
          DU2,

          integer, dimension( * )
          IPIV,

          real, dimension( ldb, * )
          B,

          integer
          LDB,

          integer
          INFO

          )

SGTTRS

 Download SGTTRS + dependencies

 [TGZ]

 [ZIP]

 [TXT]

Purpose:

 SGTTRS solves one of the systems of equations
    A*X = B  or  A**T*X = B,
 with a tridiagonal matrix A using the LU factorization computed
 by SGTTRF.

Parameters

[in]	TRANS
          TRANS is CHARACTER*1
          Specifies the form of the system of equations.
          = 'N':  A * X = B  (No transpose)
          = 'T':  A**T* X = B  (Transpose)
          = 'C':  A**T* X = B  (Conjugate transpose = Transpose)

[in]	N
          N is INTEGER
          The order of the matrix A.

[in]	NRHS
          NRHS is INTEGER
          The number of right hand sides, i.e., the number of columns
          of the matrix B.  NRHS >= 0.

[in]	DL
          DL is REAL array, dimension (N-1)
          The (n-1) multipliers that define the matrix L from the
          LU factorization of A.

[in]	D
          D is REAL array, dimension (N)
          The n diagonal elements of the upper triangular matrix U from
          the LU factorization of A.

[in]	DU
          DU is REAL array, dimension (N-1)
          The (n-1) elements of the first super-diagonal of U.

[in]	DU2
          DU2 is REAL array, dimension (N-2)
          The (n-2) elements of the second super-diagonal of U.

[in]	IPIV
          IPIV is INTEGER array, dimension (N)
          The pivot indices; for 1 <= i <= n, row i of the matrix was
          interchanged with row IPIV(i).  IPIV(i) will always be either
          i or i+1; IPIV(i) = i indicates a row interchange was not
          required.

[in,out]	B
          B is REAL array, dimension (LDB,NRHS)
          On entry, the matrix of right hand side vectors B.
          On exit, B is overwritten by the solution vectors X.

[in]	LDB
          LDB is INTEGER
          The leading dimension of the array B.  LDB >= max(1,N).

[out]	INFO
          INFO is INTEGER
          = 0:  successful exit
          < 0:  if INFO = -i, the i-th argument had an illegal value

Author

Univ. of Tennessee

Univ. of California Berkeley

Univ. of Colorado Denver

NAG Ltd.

Date

November 2011

<address class="footer">
Generated on Mon Jul 14 2014 18:28:49 for Lighthouse by

 1.8.2
</address>


text:
<?php

namespace core\session\handler;
use core\util\string\StringUtil as StringUtil;
use core\util\param\Validator as Validator;
use core\util\param\Accessor as Accessor;
use core\util\param\filter\FilterUnit as FilterUnit;
use core\object\handler\Handable as Handable;
use core\session\User as User;
use core\session\Session as Session;
use core\session\auth\Authenticator as Authenticator;
use core\excception\html\ActionException as ActionException;

/**
 * Handles an action defined in the query.
 * @author Marc Bredt
 */
class ActionHandler implements Handable {

  private $method  = null;
  private $fid     = null;
  private $module  = null;
  private $fname   = null;
  private $fconfig = null;
  private $action  = null;
  private $defines = null;
  private $handler = null;
  private $depends = null;
  private $token   = null;

  /**
   * Handle actions invoked by form submissions.
   * @return true if successfully handling an action completely, otherwise false
   * @throws ActionException
   */
  public static function handle(){

    global $filelogger;

    // perform checks on parameters passed based for a valid action
    if(!$this->initialize()){
      $filelogger->error("%",array(new ActionException("checks failed",2)));
      throw(new ActionException("checks failed",2));
    }

    // handle the desired action
    $this->handle_action();

  }

  /**
   * Load the required form chain (actions -> forms -> form) for an action and
   * perform checks on the chain configuration and parameters passed.
   * @return true if the config chain was completly loaded successfully,
   *         otherwise false
   * @see core\html\form\io\InputElement
   */
  private function initialize() {

    global $session, $filelogger, $inputprovider;

    // determine the request method
    $this->method = $this->determine_request_method();

    // determine the form identifier
    $this->fid = $this->determine_form_identifier();
    $this->module = explode(".",$this->fid)[0];
    $this->fname = explode(".",$this->fid)[1];
    $filelogger->debug("fid=%, mid=%, fname=%",
                       array($this->fid,$this->module,$this->fname));

    // determine the form config and check the rights
    $this->fconfig = $this->determine_form_configuration();
    $form = new Form($this->fconfig);
    RightManager::has($form); // result info is produced by the manager
    $filelogger->debug("form = %", array($form));

    // determine form action key
    $this->action = $this->determine_form_action_key();

    // determine form key definitions
    $this->defines = $this->determine_form_definitions();

    // determine the action handler and the depends
    $this->determine_action_handler_and_depends();

    // check if all action dependencies are fulfilled by the definitions
    if($this->determine_action_dependencies_present()) {

      // TODO: add range values from $fconfig elements to the filter

      // TODO: validate data passed to the corresponding form
      // if all data is present check the entire parameter set
      // containing only parameters needed against regex in the
      // form config $fconfig
      // TODO: set the action token passed
      //foreach $var Accessor::get() and store em into a parameter map
      //$unit = new FilterUnit("action","GET","^[a-z]+$","validate_regexp,string");
      //$this->action = Accessor::get($unit); // filter failures are thrown in here
      //$inputprovider->set("action",$this->action);

      // print some information on the filtered input elements
      $filelogger->debug("filtered input = %",array($inputprovider));

      return true;

    }

    return false;

  }

  /**
   * Determine the request method.
   * @return string representing the request method, currently a dummy function
   *                returning "POST" as only post requests will be evaluated
   *                conceptually
   * @see core\html\form\FormBuilder
   */
  private function determine_request_method() {
    return "POST";
  }

  /**
   * Determines the submitted form identifier from (filtered) keys in $_POST.
   * @return string containing the form identifier MID.FID derived from
   *                MID.FID.GID.(NUM|RID.CID)[.(x|y)]
   * @see core\html\form\io\InputElement
   */
  private function determine_form_identifier() {

    // array_map - filter each _POST key
    // array_filter - remove all invalid keys, filtered via false
    // array_count_values - count filtered/sanitized keys with valid prefix
    $regex   = "^[a-z]+\.[a-z]+\.(e\.[0-9]+|g)\.[0-9]+(\.[xy])*$";
    $filters ="validate_regexp,stripped";
    $fkunit  = new FilterUnit(array_keys($_POST),"",$regex,$filters);
    $akunit  = Accessor::get($fkunit);
    $fkeys=array_count_values(array_filter(array_map(
             function($fkey,$fmeth,$regex,$filters){
               $kunit = new FilterUnit($fkey,"",$regex,$filters);
               $aku = Accessor::get($kunit);
               if(Validator::isa($aku,"null")) return false;
               else return substr($aku,0,strpos($aku,".",strpos($aku,".")+1));
             },
             array_keys($_POST), // keys to filter from
             array_fill(0,count($_POST),$regex), // regex parameter
             array_fill(0,count($_POST),$filters) // filters parameter
           )));

    // sort to get the key with the max value from the last element of the array
    asort($fkeys); end($fkeys);

    // return the main key determined
    return key($fkeys);

  }

  /**
   * Determine the form file path relative to html/form/ from forms.xml
   * @return
   */
  private function determine_form_configuration() {

    $xdf = new XMLDocument(PATH_CONF."/html/forms.xml",PATH_DTD."/html/forms.dtd");

    if(Validator::equals($this->module,"core"))
      $fconfig =
        PATH_CONF."/html/form/".$xdf->xpath("normalize-space(".
          "//form[@active=\"y\" and @module=\"".$this->module."\"".
          " and @name=\"".$this->fname."\"]/text())");

    else
      $fconfig =
        constant("MOD_".strtoupper($module)."_PATH_CONF")."/html/form/".
          $xdf->xpath("normalize-space(".
            "//form[@active=\"y\" and @module=\"".$this->module."\"".
            " and @name=\"".$this->fname."\"]/text())");

    $filelogger->debug("fconfig = [ % ]",array($fconfig));
    return $fconfig;

  }

  /**
   * Determine the form action key via key layout and the defines attribute in
   * form configuration.
   * @return string representing the name of the action key which invoked the
   *                form submission. This is possible because only the invacating
   *                submit button is provided.
   * @throws ActionException in case multiple action keys are found which would
   *                         be possible upon query injection
   */
  private function determine_form_action_key() {

    $unit = new FilterUnit($actionkey,"GET","^[a-z]+$","validate_regexp,string");
    $this->action = Accessor::get($unit); // filter failures are thrown in here
    $inputprovider->set("action",$this->action);
    $filelogger->info("evaluated action=%, unit=%",array($this->action,$unit));

  }

  /**
   * Determine the action handler corresponding to the action key and the form
   * identifier definition set in conf/data/actions.xml. Defaults to the class
   * core\session\handler\ActionHandler. Every handler configured need to
   * implement core\object\handler\Handable because the functions defined in
   * there will be called in ::handle_action().
   * @see core\object\handler\Handable
   * @see core\session\handler\ActionHandler
   * TODO: check if the handler is a valid one
   */
  private function determine_action_handler_and_depends() {

    $xda = new XMLDocument(PATH_CONF."/data/actions.xml",PATH_DTD."/data/actions.dtd");

    $this->handler = $xda->xpath("//action[@name=\"".$this->action."\" ".
                                      "and @active=\"y\" ".
                                      "and @form=\"".$this->fid."\"]/@handler");
    $this->depends = $xda->xpath("//action[@name=\"".$this->action."\" ".
                                      "and @active=\"y\" ".
                                      "and @form=\"".$this->fid."\"]/@depends");

    $filelogger->debug("handler for action % = %",array($this->action,$handler));
    $filelogger->debug("depends for action % = %",array($this->action,$depends));

  }

  /**
   * Determine if all action dependencies are present.
   * @return true if all action dependencies defined via form keys are present
   */
  private function determine_action_dependencies_present() {
    // TODO: diff the depends and define maps
    return true;
  }

  /**
   * Handle a specific action defined in conf/data/actions.xml
   * @param $this->action action going to be handled
   * @param $handler action handler going to be used
   * @see call_user_func()
   * @req PHP >= 5.3.0, call_user_func() is able to invoke class functions
   */
  private function handle_action() {

    global $filelogger, $session;

    // check the action token
    $token = $this->token;
    $stoken = $session->get("tokens",$this->action);
    if(!Validator::equals($stoken,$this->token)) {
      $filelogger->error("invalid token=%, expected=%, %",array($token,$stoken,
                         new ActionException("invalid token '".$token."', ".
                                             "expected '".$stoken."'",2)));
      throw(new ActionException("invalid token '".$token."', ".
                                "expected '".$stoken."'",2));
    }

    // execute the handler defined
    //call_user_func(array($this->handler,"handle"),$param1,...,$paramN);
    call_user_func(array($this->handler,"handle"));

    // remove the action token
    $session->uset("tokens",$this->action);

  }

}

?>


text:
<?php

require_once(dirname(__FILE__).'/../../bootstrap/unit.php');

$t = new lime_test(69, new lime_output_color());

$tmpDir = sfToolkit::getTmpDir();
$content = 'This is an ASCII file.';
file_put_contents($tmpDir.'/test.txt', $content);

class testValidatorFile extends sfValidatorFile
{
  public function getMimeType($file, $fallback)
  {
    return parent::getMimeType($file, $fallback);
  }

  public function guessFromNothing($file)
  {
    return 'nothing/plain';
  }

  public function guessFromFileinfo($file)
  {
    return parent::guessFromFileinfo($file);
  }

  public function guessFromMimeContentType($file)
  {
    return parent::guessFromMimeContentType($file);
  }

  public function guessFromFileBinary($file)
  {
    return parent::guessFromFileBinary($file);
  }

  public function getMimeTypesFromCategory($category)
  {
    return parent::getMimeTypesFromCategory($category);
  }
}

// ->getMimeTypesFromCategory()
$t->diag('->getMimeTypesFromCategory()');
$v = new testValidatorFile();
try
{
  $t->is($v->getMimeTypesFromCategory('non_existant_category'), '');
  $t->fail('->getMimeTypesFromCategory() throws an InvalidArgumentException if the category does not exist');
}
catch (InvalidArgumentException $e)
{
  $t->pass('->getMimeTypesFromCategory() throws an InvalidArgumentException if the category does not exist');
}
$categories = $v->getOption('mime_categories');
$t->is($v->getMimeTypesFromCategory('web_images'), $categories['web_images'], '->getMimeTypesFromCategory() returns an array of mime types for a given category');
$v->setOption('mime_categories', array_merge($v->getOption('mime_categories'), array('text' => array('text/plain'))));
$t->is($v->getMimeTypesFromCategory('text'), array('text/plain'), '->getMimeTypesFromCategory() returns an array of mime types for a given category');

// ->guessFromFileinfo()
$t->diag('->guessFromFileinfo()');
if (!function_exists('finfo_open'))
{
  $t->skip('finfo_open is not available', 2);
}
else
{
  $v = new testValidatorFile();
  $t->is($v->guessFromFileinfo($tmpDir.'/test.txt'), 'text/plain', '->guessFromFileinfo() guesses the type of a given file');
  $t->is($v->guessFromFileinfo($tmpDir.'/foo.txt'), null, '->guessFromFileinfo() returns null if the file type is not guessable');
}

// ->guessFromMimeContentType()
$t->diag('->guessFromMimeContentType()');
if (!function_exists('mime_content_type'))
{
  $t->skip('mime_content_type is not available', 2);
}
else
{
  $v = new testValidatorFile();
  $t->is($v->guessFromMimeContentType($tmpDir.'/test.txt'), 'text/plain', '->guessFromMimeContentType() guesses the type of a given file');
  $t->is($v->guessFromMimeContentType($tmpDir.'/foo.txt'), null, '->guessFromMimeContentType() returns null if the file type is not guessable');
}

// ->guessFromFileBinary()
$t->diag('->guessFromFileBinary()');
$v = new testValidatorFile();
$t->is($v->guessFromFileBinary($tmpDir.'/test.txt'), 'text/plain', '->guessFromFileBinary() guesses the type of a given file');
$t->is($v->guessFromFileBinary($tmpDir.'/foo.txt'), null, '->guessFromFileBinary() returns null if the file type is not guessable');
$t->is($v->guessFromFileBinary('/bin/ls'), (PHP_OS != 'Darwin') ? 'application/x-executable' : 'application/octet-stream', '->guessFromFileBinary() returns correct type if file is guessable');

// ->getMimeType()
$t->diag('->getMimeType()');
$v = new testValidatorFile();
$t->is($v->getMimeType($tmpDir.'/test.txt', 'image/png'), 'text/plain', '->getMimeType() guesses the type of a given file');
$t->is($v->getMimeType($tmpDir.'/foo.txt', 'text/plain'), 'text/plain', '->getMimeType() returns the default type if the file type is not guessable');

$v->setOption('mime_type_guessers', array_merge(array(array($v, 'guessFromNothing')), $v->getOption('mime_type_guessers')));
$t->is($v->getMimeType($tmpDir.'/test.txt', 'image/png'), 'nothing/plain', '->getMimeType() takes all guessers from the mime_type_guessers option');

// ->clean()
$t->diag('->clean()');
$v = new testValidatorFile();
try
{
  $v->clean(array('test' => true));
  $t->fail('->clean() throws an sfValidatorError if the given value is not well formatted');
  $t->skip('', 1);
}
catch (sfValidatorError $e)
{
  $t->pass('->clean() throws an sfValidatorError if the given value is not well formatted');
  $t->is($e->getCode(), 'invalid', '->clean() throws a sfValidatorError');
}
$f = $v->clean(array('tmp_name' => $tmpDir.'/test.txt'));
$t->ok($f instanceof sfValidatedFile, '->clean() returns a sfValidatedFile instance');
$t->is($f->getOriginalName(), '', '->clean() returns a sfValidatedFile with an empty original name if the name is not passed in the initial value');
$t->is($f->getSize(), strlen($content), '->clean() returns a sfValidatedFile with a computed file size if the size is not passed in the initial value');
$t->is($f->getType(), 'text/plain', '->clean() returns a sfValidatedFile with a guessed content type');

class myValidatedFile extends sfValidatedFile
{
}

$v->setOption('validated_file_class', 'myValidatedFile');
$f = $v->clean(array('tmp_name' => $tmpDir.'/test.txt'));
$t->ok($f instanceof myValidatedFile, '->clean() can take a "validated_file_class" option');

foreach (array(UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE, UPLOAD_ERR_PARTIAL, UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_CANT_WRITE, UPLOAD_ERR_EXTENSION) as $error)
{
  try
  {
    $v->clean(array('tmp_name' => $tmpDir.'/test.txt', 'error' => $error));
    $t->fail('->clean() throws an sfValidatorError if the error code is not UPLOAD_ERR_OK (0)');
    $t->skip('', 1);
  }
  catch (sfValidatorError $e)
  {
    $t->pass('->clean() throws an sfValidatorError if the error code is not UPLOAD_ERR_OK (0)');
    $t->is($e->getCode(), $code = strtolower(str_replace('UPLOAD_ERR_', '', $e->getCode())), '->clean() throws an error code of '.$code);
  }
}

// max file size
$t->diag('max file size');
$v->setOption('max_size', 4);
try
{
  $v->clean(array('tmp_name' => $tmpDir.'/test.txt'));
  $t->skip();
}
catch (sfValidatorError $e)
{
  $t->pass('->clean() throws an sfValidatorError if the file size is too large');
  $t->is($e->getCode(), 'max_size', '->clean() throws an error code of max_size');
}
$v->setOption('max_size', null);

// mime types
$t->diag('mime types');
$v->setOption('mime_types', 'web_images');
try
{
  $v->clean(array('tmp_name' => $tmpDir.'/test.txt'));
  $t->skip();
}
catch (sfValidatorError $e)
{
  $t->pass('->clean() throws an sfValidatorError if the file mime type is not in mime_types option');
  $t->is($e->getCode(), 'mime_types', '->clean() throws an error code of mime_types');
}
$v->setOption('mime_types', null);

// required
$v = new testValidatorFile();
try
{
  $v->clean(array('tmp_name' => '', 'error' => UPLOAD_ERR_NO_FILE, 'name' => '', 'size' => 0, 'type' => ''));
  $t->fail('->clean() throws an sfValidatorError if the file is required and no file is uploaded');
  $t->skip();
}
catch (sfValidatorError $e)
{
  $t->pass('->clean() throws an sfValidatorError if the file is required and no file is uploaded');
  $t->is($e->getCode(), 'required', '->clean() throws an error code of required');
}
try
{
  $v->clean(null);
  $t->fail('->clean() throws an sfValidatorError if the file is required and no file is uploaded');
  $t->skip();
}
catch (sfValidatorError $e)
{
  $t->pass('->clean() throws an sfValidatorError if the file is required and no file is uploaded');
  $t->is($e->getCode(), 'required', '->clean() throws an error code of required');
}
$v = new testValidatorFile(array('required' => false));
$t->is($v->clean(array('tmp_name' => '', 'error' => UPLOAD_ERR_NO_FILE, 'name' => '', 'size' => 0, 'type' => '')), null, '->clean() handles the required option correctly');

// sfValidatedFile

// ->getOriginalName() ->getTempName() ->getSize() ->getType()
$t->diag('->getOriginalName() ->getTempName() ->getSize() ->getType()');
sfToolkit::clearDirectory($tmpDir.'/foo');
if (is_dir($tmpDir.'/foo'))
{
  rmdir($tmpDir.'/foo');
}
$f = new sfValidatedFile('test.txt', 'text/plain', $tmpDir.'/test.txt', strlen($content));
$t->is($f->getOriginalName(), 'test.txt', '->getOriginalName() returns the original name');
$t->is($f->getTempName(), $tmpDir.'/test.txt', '->getTempName() returns the temp name');
$t->is($f->getType(), 'text/plain', '->getType() returns the content type');
$t->is($f->getSize(), strlen($content), '->getSize() returns the size of the uploaded file');

// ->save() ->isSaved() ->getSavedName()
$t->diag('->save() ->isSaved() ->getSavedName()');
$f = new sfValidatedFile('test.txt', 'text/plain', $tmpDir.'/test.txt', strlen($content));
$t->is($f->isSaved(), false, '->isSaved() returns false if the file has not been saved');
$t->is($f->getSavedName(), null, '->getSavedName() returns null if the file has not been saved');
$filename = $f->save($tmpDir.'/foo/test1.txt');
$t->is($filename, $tmpDir.'/foo/test1.txt', '->save() returns the saved filename');
$t->is(file_get_contents($tmpDir.'/foo/test1.txt'), file_get_contents($tmpDir.'/test.txt'), '->save() saves the file to the given path');
$t->is($f->isSaved(), true, '->isSaved() returns true if the file has been saved');
$t->is($f->getSavedName(), $tmpDir.'/foo/test1.txt', '->getSavedName() returns the saved file name');

$f = new sfValidatedFile('test.txt', 'text/plain', $tmpDir.'/test.txt', strlen($content), $tmpDir);
$filename = $f->save($tmpDir.'/foo/test1.txt');
$t->is($filename, 'foo/test1.txt', '->save() returns the saved filename relative to the path given');
$t->is(file_get_contents($tmpDir.'/foo/test1.txt'), file_get_contents($tmpDir.'/test.txt'), '->save() saves the file to the given path');
$t->is($f->getSavedName(), $tmpDir.'/foo/test1.txt', '->getSavedName() returns the saved file name');

$filename = $f->save('foo/test1.txt');
$t->is($filename, 'foo/test1.txt', '->save() returns the saved filename relative to the path given');
$t->is(file_get_contents($tmpDir.'/foo/test1.txt'), file_get_contents($tmpDir.'/test.txt'), '->save() saves the file to the given path and uses the path if the file is not absolute');
$t->is($f->getSavedName(), $tmpDir.'/foo/test1.txt', '->getSavedName() returns the saved file name');

$filename = $f->save();
$t->is(file_get_contents($tmpDir.'/'.$filename), file_get_contents($tmpDir.'/test.txt'), '->save() returns the generated file name is none was given');
$t->is($f->getSavedName(), $tmpDir.'/'.$filename, '->getSavedName() returns the saved file name');

try
{
  $f = new sfValidatedFile('test.txt', 'text/plain', $tmpDir.'/test.txt', strlen($content));
  $f->save();
  $t->fail('->save() throws an Exception if you don\'t give a filename and the path is empty');
}
catch (Exception $e)
{
  $t->pass('->save() throws an Exception if you don\'t give a filename and the path is empty');
}

try
{
  $f->save($tmpDir.'/test.txt/test1.txt');
  $t->fail('->save() throws an Exception if the directory already exists and is not a directory');
}
catch (Exception $e)
{
  $t->pass('->save() throws an Exception if the directory already exists and is not a directory');
}

// ->getExtension()
$t->diag('->getExtension()');
$f = new sfValidatedFile('test.txt', 'text/plain', $tmpDir.'/test.txt', strlen($content));
$t->is($f->getExtension(), '.txt', '->getExtension() returns file extension based on the content type');
$f = new sfValidatedFile('test.txt', 'image/x-png', $tmpDir.'/test.txt', strlen($content));
$t->is($f->getExtension(), '.png', '->getExtension() returns file extension based on the content type');
$f = new sfValidatedFile('test.txt', 'very/specific', $tmpDir.'/test.txt', strlen($content));
$t->is($f->getExtension(), '', '->getExtension() returns an empty string if it does not know the content type');
$f = new sfValidatedFile('test.txt', '', $tmpDir.'/test.txt', strlen($content));
$t->is($f->getExtension(), '', '->getExtension() returns an empty string if the content type is empty');
$t->is($f->getExtension('bin'), 'bin', '->getExtension() takes a default extension as its first argument');

// ->getOriginalExtension()
$t->diag('->getOriginalExtension()');
$f = new sfValidatedFile('test.txt', 'text/plain', $tmpDir.'/test.txt', strlen($content));
$t->is($f->getOriginalExtension(), '.txt', '->getOriginalExtension() returns the extension based on the uploaded file name');
$f = new sfValidatedFile('test', 'text/plain', $tmpDir.'/test.txt', strlen($content));
$t->is($f->getOriginalExtension(), '', '->getOriginalExtension() returns an empty extension if the uploaded file name has no extension');
$t->is($f->getOriginalExtension('bin'), 'bin', '->getOriginalExtension() takes a default extension as its first argument');

unlink($tmpDir.'/test.txt');
sfToolkit::clearDirectory($tmpDir.'/foo');
rmdir($tmpDir.'/foo');


text:
package com.amazonaws.services.simpleemail.model;

import javax.annotation.Generated;

/**
 *

 * Indicates that the provided receipt rule does not exist.
 *

 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class RuleDoesNotExistException extends com.amazonaws.services.simpleemail.model.AmazonSimpleEmailServiceException {
    private static final long serialVersionUID = 1L;

    /**
     *

     * Indicates that the named receipt rule does not exist.
     *

     */
    private String name;

    /**
     * Constructs a new RuleDoesNotExistException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public RuleDoesNotExistException(String message) {
        super(message);
    }

    /**
     *

     * Indicates that the named receipt rule does not exist.
     *

     *
     * @param name
     *        Indicates that the named receipt rule does not exist.
     */

    public void setName(String name) {
        this.name = name;
    }

    /**
     *

     * Indicates that the named receipt rule does not exist.
     *

     *
     * @return Indicates that the named receipt rule does not exist.
     */

    public String getName() {
        return this.name;
    }

    /**
     *

     * Indicates that the named receipt rule does not exist.
     *

     *
     * @param name
     *        Indicates that the named receipt rule does not exist.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public RuleDoesNotExistException withName(String name) {
        setName(name);
        return this;
    }

}


text:
package org.compass.core.util.reflection.asm;

import org.objectweb.asm.Type;

/**
 * @author kimchy
 */
public class Boxer {

    final static public String INTERNAL_NAME = Type.getInternalName(Boxer.class);

    public static Object box(boolean v) {
        return v;
    }

    public static Object box(byte v) {
        return v;
    }

    public static Object box(char v) {
        return v;
    }

    public static Object box(short v) {
        return v;
    }

    public static Object box(int v) {
        return v;
    }

    public static Object box(long v) {
        return v;
    }

    public static Object box(float v) {
        return v;
    }

    public static Object box(double v) {
        return v;
    }
}


text:
#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import unicodedata
import re
# from xml.sax.saxutils import escape as xml_escape
import itertools
import csv
import argparse

global __showwarnings, __showinfo

def loginfo(str):
    """Utility function to log information"""
    if __showinfo:
        print(str)

def logwarning(str):
    """Utility function to log warnings"""
    if __showwarnings:
        print('Warning: '+str)

class LangError(Exception):
    """Base class for exception created by this script"""

    def prefix(cls):
        return 'Error'

    def __str__(self):
        return self.prefix() + ': '+ super(LangError, self).__str__()

class LangParseError(LangError):
    """Class for exception found while parsing"""

    def prefix(cls):
        return 'ParseError'

class LanguageElement:
    """Class encapsulating the key of the string and the different values."""

    # regex used to properly strip "pretty" (with repeated *) multiline comments
    pc_pattern = re.compile(r'^[ \t\f\v]*\*?[ \t\f\v]*(.*)$',re.MULTILINE)

    def __init__(self, key='', comment=''):
        """Keyword Arguments:

        key    -- The string key. Must not be None, must be normalized.
        values -- A list containing the different values"""
        self.key = key
        self.values = {}
        self.comment = "\n".join(self.pc_pattern.findall(comment.strip()))

    #regex used to normalize keys
    #TODO:  Normalizing keys is not a good idea because people might use
    #       accents in their string keys and this will then change the
    #       key in the output...
    key_pattern = re.compile('[^\w\s_]+')
    @classmethod
    def normalizekey(cls, key):
        """Normalizes keys between android and ios"""
        u = unicodedata.normalize('NFKD', unicode(key, 'utf-8'))
        formattedKey = u.encode('ascii', 'ignore')
        return cls.key_pattern.sub(' ', formattedKey)

    def getvalue(self, language):
        """Getter for string value

        Keyword Arguments:
        language -- the language your want the value for"""
        try:
            return self.values[language]
        except KeyError, IndexError:
            return None

    def setvalue(self, language, value):
        """setter for string value

        Keyword Arguments:
        language -- the language the value is for
        value    -- the value"""
        assert self.key, 'Tried to set a value {} without a key'.format(value)
        if value:
            self.values[language] = value

    def csv_columns(self, languages):
        """Convernience method that returns a generator
        representing the string for a csv line"""
        a = [self.comment, self.key, ]
        a.extend(((self.getvalue(l) or '') for l in languages))
        return a

    # def androidline(self, language):
    #     """Returns a string corresponding to the android line for the language

    #     Keyword arguments:
    #     languageIndex --  the language index (defaults to 0)
    #     """
    #     formattedKey = self.key.replace(' ', '_')
    #     formattedValue = xml_escape(self.values[language])
    #     return '<string name="{}">{}</string>'.format(formattedKey, formattedValue)

    def cocoa_line(self, language):
        """Convenience method that returns a string corresponding
        to the cocoa line for the provided language

        Keyword arguments:
        language -- the language
        """
        value = self.getvalue(language)
        if value:
            value = value.replace('"', '\\"') #todo:replace with regex
        else:
            value = ''
        commentstring = None
        if '\n' in self.comment:
            commentstring = '/*\n * ' + self.comment.replace('\n','\n * ') + '\n */'
        elif self.comment:
            commentstring = '// ' + self.comment

        line = ''
        if self.key:
            line += '"{}" = "{}";'.format(self.key, value)
        if commentstring:
            line += commentstring
        return line

    def __str__(self):
        return str({ 'key' : self.key, 'values' : self.values, 'comment' : self.comment })

class LanguageResource:
    """Represents the Language Resources.
    I-e several strings and several languages"""

    def __init__(self):
        # an array containing the languages
        self.languages = []
        # an array containing the LanguageElement instances
        # it is repeated in keyedelements so that they can be accessed quickly
        self.elements = []
        self.keyedelements = {}

    def reset(self):
        """Deletes all the resources"""
        self.languages = []
        self.elements = []
        self.keyedelements = {}

    # Convenience

    def getlanguages(self):
        return self.languages

    def getkeyedelement(self, key):
        """Returns the element corresponding to the provided key

        Keyword arguments:
        key -- the key"""
        try:
            return self.keyedelements[key]
        except KeyError, IndexError:
            return None

    def getvalue(self, key, language):
        """Returns the value corresponding to the provided key and language

        Keyword arguments:
        key      -- the key
        language -- the language"""
        try:
            return self.keyedelements[key].getvalue(language)
        except KeyError, IndexError:
            return None

    def missingvalues(self):
        """Returns the array of the elements that are missing values
        in a language"""
        missing = { l : [] for l in self.languages}
        for k,v in self.keyedelements.iteritems():
            for l in self.languages:
                if not v.getvalue(l):
                    missing[l].append(k)
        #There might a more efficient way to cleanup?
        for k in missing.keys():
            if not missing[k]:
                del missing[k]
        return missing

    # Base construction

    def __insertcomment(self, comment, index=None):
        """ Inserts a comment, returns True if a new element was created

        Keyword arguments:
        comment -- a comment string
        index   -- the index at which the comment should be inserted, defaults to end of elements array.
        """
        # This is probably not optimized
        if index == None:
            index = len(self.elements)
        self.elements.insert(index, LanguageElement(comment=comment))
        return index

    def __insertstring(self, key, string, comment, language, index=None):
        """ Inserts a new string, returns True if a new element was created.
        Raises a LangParseError if a value already exists for the corresponding key.

        Keyword arguments:
        key      -- the string key (str)
        string   --  a string (str)
        language -- the language
        index    -- the desired position, if the key was already present, then it is ignored"""
        # This is probably not optimized
        if index == None:
            index = len(self.elements)

        key = LanguageElement.normalizekey(key)
        element = self.getkeyedelement(key)
        if element:
            if element.getvalue(language):
                raise LangParseError("Value already exists for key '{}' and language '{}'".format(key, language))
            index = self.elements.index(element)
        else:
            element = LanguageElement(key=key)
            self.elements.insert(index, element)
            self.keyedelements[key] = element
        element.setvalue(language, string)
        return index

    def __constructelement(self, key, value, comment, language, usecomments = True, index=None):
        """Constructs and inserts a string element
        Returns the index of the inserted object

        Keyword arguments:
        key         -- the key
        value       -- the value
        comment     -- a comment, can be None
        language    -- the language
        usecomments -- if false the comment is ignored, defaults to True
        index       -- the preferred insertion index, defaults to None"""
        if key:
            try:
                return self.__insertstring(key, value, (usecomments and comment) or '', language, index=index)
            except LangParseError as e:
                print(e)
                return index
        elif usecomments and comment:
            return self.__insertcomment(comment, index=index)
        else:
            return index

    def __constructelements(self, key, languagevaluedic, comment, usecomments = True, index = None):
        """Constructs and inserts a string element given a value dictionary,
        The element will contain the languages and values present in the
        provided language-value dictionary
        Returns the index of the inserted object.
        Used mostly when creating elements from a csv file.

        Keyword arguments:
        key              -- the keyindex
        languagevaluedic -- a language-value dictionary containing all the values for the string
        usecomments      -- if false the comment is ignored, defaults to True
        index            -- the preferred insertion index, defaults to None"""
        if key and languagevaluedic:
            for l,v in languagevaluedic.iteritems():
                # index won't change since we are adding values to the same key
                index = self.__constructelement(key=key, value=v, comment=comment, language=l, usecomments=usecomments, index=index)
                # deleting comment so that it is not added twice
                comment = None
                usecomments = None
            return index
        else:
            return self.__constructelement(key=None, value=None, comment=comment, language=None, usecomments=usecomments, index=index)

    # Cocoa reading

    def cocoa_feed(self, path, languages=None, tablename=None, usecomments=True, autocorrect=None):
        """Creates all elements from a provided path, interpreting cocoa files.
        Path can be:
        - a directory containing .lproj directory
        - a .lproj directory (the languages argument will be ignored,
            and the name of the directory will be used instead)
        - a .strings file (in which case the language must be provided)
        This method checks which kind of path it is and then calls the appropriate method

        Keyword arguments:
        path        -- the path
        languages   -- the languages, defaults to None in which case the array will be determined automatically
        tablename   -- the table name (e.g Localizable in Localizable.strings). Defaults to None, i-e all tables will be considered
        usecomments -- if False the comments are ignored, defaults to True
        autocorrect -- if None the user will be prompted in conflicts,
                       if True the conflicts will be autocorrected,
                       if False the conflicts will be ignored"""
        if os.path.isfile(path) and path.endswith('.strings'):
            language = None
            if languages:
                language = languages[0]
                if len(languages) > 1:
                    logwarning('Too many languages specified for .strings file. Only considering first one i-e ' + language)
            self.cocoa_feedstrings(filepath=path, language=language, usecomments=usecomments, autocorrect=autocorrect)
        elif os.path.isdir(path) and path.endswith('.lproj'):
            self.cocoa_feedlproj(path=path, tablename=tablename, usecomments=usecomments, autocorrect=autocorrect)
        elif os.path.isdir(path):
            self.cocoa_feeddir(path=path, languages=languages, tablename=tablename, usecomments=usecomments, autocorrect=autocorrect)
        else:
            raise LangError('Invalid path: ' + path)

    def cocoa_feeddir(self, path, languages=None, tablename=None, usecomments=True, autocorrect=None):
        """Creates all elements from a provided directory path, interpreting cocoa files.
        The directory must contain .lproj directories and not be a .lproj dir itself (see cocoa_feedlproj for that).
        Calls cocoa_feedlproj with the right paths.
        Returns autocorrect (which can change depending on the user's response to prompts)

        Keyword arguments:
        path        -- the path
        languages   -- if provided, restricts the .lproj directory that are considered
        tableName   -- the table name (e.g Localizable in Localizable.strings). Defaults to None, i-e all tables will be considered
        usecomments -- if False the comments are ignored, defaults to True
        autocorrect -- if None the user will be prompted in conflicts,
                       if True the conflicts will be autocorrected,
                       if False the conflicts will be ignored"""
        assert os.path.isdir(path) and not path.endswith('.lproj'), 'Incorrect dir path ' + path

        if languages:
            dirs = list((os.path.join(path,p) for p in os.listdir(path) if p.endswith('.lproj') and p[:-6] in languages))
            if not dirs:
                raise LangError('Directory {} did not contain any lproj dir for the specified languages {}'.format(path, languages))
        else:
            dirs = list((os.path.join(path,p) for p in os.listdir(path) if p.endswith('.lproj')))
            if not dirs:
                raise LangError('Directory {} did not contain any lproj dir'.format(path))

        for lprojpath in dirs:
            autocorrect = self.cocoa_feedlproj(path=lprojpath, tablename=tablename, usecomments=usecomments, autocorrect=autocorrect)
            usecomments = False
        return autocorrect

    def cocoa_feedlproj(self, path, tablename=None, usecomments=True, autocorrect=None):
        """Creates all elements from a provided .lproj directory path, interpreting cocoa files.
        Calls cocoa_feedstrings with the right paths.
        Returns autocorrect (which can change depending on the user's response to prompts)

        Keyword arguments:
        path        -- the path
        tableName   -- the table name (e.g Localizable in Localizable.strings). Defaults to None, i-e all tables will be considered
        usecomments -- if False the comments are ignored, defaults to True
        autocorrect -- if None the user will be prompted in conflicts,
                       if True the conflicts will be autocorrected,
                       if False the conflicts will be ignored"""
        assert path.endswith('.lproj') and os.path.isdir(path), 'Incorrect lproj path ' + path
        language = os.path.basename(path)[:-6]
        if tablename:
            stringpath = os.path.join(path, tablename + '.strings')
            if os.path.isfile(stringpath):
                return self.cocoa_feedstrings(stringpath, language, usecomments, autocorrect)
            else:
                logwarning('File did not exist at path ' + stringpath)
                return autocorrect
        else:
            files = (os.path.join(path,p) for p in os.listdir(path) if p.endswith('.strings'))
            for stringpath in files:
                if usecomments:
                    self.__insertcomment('======================\nTable : ' + os.path.basename(stringpath)[:-8] + '\n======================')
                autocorrect = self.cocoa_feedstrings(stringpath, language, usecomments, autocorrect)

            return autocorrect

    @classmethod
    def cocoa_getlinepattern(cls):
        # regex to parse a line of a strings file
        # groups are :
        #   key (<key> or None)
        #   value (<value> or None)
        #   sc (; or None)
        #   com (// <comment> or /* <comment> or None)
        return re.compile(r'''  (?: # Beginning of key/value block or value block
                                    (?: # Beginning of key block
                                        ((?<![\\])[\'"])                    # unescaped quote or single quote and stores it in 1
                                        (?P<key>(?:.(?!(?<![\\])\1))*.?)    # key
                                        \1                                  # quote found in 1
                                        \s*?=\s*?
                                    )?  # End of key block
                                    ((?<![\\])[\'"])                      # same as before but stored in 3
                                    (?P<val>(?:.(?!(?<![\\])\3))*.?)      # value
                                    \3
                                )?  # End of key/value block or value block
                                \s*?
                                (?P<sc>;{1})?                               # semicolon?
                                [\s|;]*?
                                (?:(?P<com>[//|/*].*))?
                                $'''          # comment?
                                ,re.VERBOSE)

    def cocoa_feedstrings(self, filepath, language=None, usecomments=True, autocorrect=None):
        """Parses a cocoa .strings file and stores its values

        Only supported schemes are (ignoring white spaces):

        "key" = "value"; // comment

        "key" = "value"; /* comment */

        "key" = "value" // comment
                "value2" // comment
                ..
                "value"; // comment

        /* Multiline comment
        ..
        ..
        */

        // Comment

        Returns autocorrect.

        Keyword arguments:
        filepath -- the .strings file path
        language -- the language associated with the file
        """
        try:
            if usecomments and not language is self.languages[0]:
                logwarning('Ignoring comments from file at path '+ filepath)
                usecomments = False
        except IndexError:  # if it fails, it means that there are no languages and therefore no need to warn
            pass

        if not language:
            parentdir = os.path.dirname(filepath)
            if parentdir.endswith('.lproj'):
                language = os.path.basename(parentdir)[:-6]
                logwarning('Assuming language is ' + language)
            else:
                raise LangError("Language was not provided")

        cocoa_pattern = self.cocoa_getlinepattern()

        with open(filepath, 'r') as f:

            if not language in self.languages:
                self.languages.append(language)

            # Initializing variables
            (key, value, comment, multilinecomment, consume) = ('', '', '', False, False)
            (tempkey, tempvalue, tempcomment, tempterm) = (None, None, None, False)
            index = -1
            lastinsertindex = len(self.elements)-1

            for line in f:
                # construct element and reset
                if consume:
                    lastinsertindex = self.__constructelement(key, value, comment, language, usecomments, lastinsertindex+1)
                    (key, value, comment, multilinecomment, consume) = ('', '', '', False, False)

                # Ignoring empty lines
                line = line.strip()
                if not line:
                    continue

                # Handling multiline comments
                if multilinecomment:
                    index = line.find('*/')
                    if index >= 0: #end of multiline comment, boolean reset at beginning of loop
                        comment += ((index > 0 and '\n') or '') + line[:index]
                        consume = True
                        if len(line) > index + 2:
                            logwarning('Ignoring line after "*/": "{}"'.format(line[index+2:]))
                    else:
                        comment += '\n' + line
                    continue

                # Using regex
                m = cocoa_pattern.match(line)
                if m:
                    (tempkey, tempvalue, tempcomment, tempterm) = ( m.group('key'), m.group('val'), m.group('com'), m.group('sc')!=None )

                    # Handling value and key
                    if tempkey:  # Expecting value

                        # Checking for conflict
                        if key:
                            (autocorrect, lastinsertindex) = self.__cocoa_handlecorrection(key, value, comment, language, usecomments, autocorrect, lastinsertindex+1)
                            (key, value, comment, multilinecomment, consume) = ('', '', '', False, False)

                        if tempvalue == None:
                            logwarning('ignoring line because it had a key but not a value:\n    {}'.format(line))
                            continue
                        else:
                            (key, value, consume) = (tempkey, tempvalue, tempterm)
                            consume = tempterm  # Consuming only if ; was present
                    else:
                        if tempvalue != None:
                            if key:
                                value += tempvalue
                                consume = tempterm
                            else:
                                logwarning('ignoring line because it had a value but no key was set:\n    {}'.format(line))
                                continue

                    # Handling comment
                    if tempcomment: # Ignoring empty comments
                        # Checking if comment is multiline
                        if tempcomment.startswith('/*'):
                            index = tempcomment.find('*/')
                            if index >= 0:
                                tempcomment = tempcomment[:index]
                            else:
                                multilinecomment = True
                        else: # Single line comment
                            if not ( key or value ):
                                consume = True
                        # Removing first comment char
                        if comment:
                            comment += '; ' + tempcomment[2:].strip()
                        else:
                            comment = tempcomment[2:].strip()

                else:
                    logwarning('ignoring line because regex did not match:\n    {}'.format(line))
                    continue

            # Dealing with last line
            if consume:
                self.__constructelement(key, value, comment, language, usecomments, lastinsertindex+1)
            elif key and value:
                (autocorrect, lastinsertindex) = self.__cocoa_handlecorrection(key, value, comment, language, usecomments, autocorrect, lastinsertindex+1)

        return autocorrect

    def __cocoa_handlecorrection(self, key, value, comment, language, usecomments, autocorrect, index):
        """Returns (autocorrect, insertindex)"""
        if autocorrect == None:
            i = raw_input('Cocoa parse error (You probably forgot a ;):\n'\
                          '    key = "{}"\n'\
                          '    value = "{}"\n'
                          'Should I still add it?\n'
                          'y(yes), ya(yes to all), n(no), na(no to all)\n'.format(key, value))
            ia = ('y','n','ya','na')
            while i not in ia:
                i = raw_input('What do you mean ?\n')

            if i == 'ya':
                autocorrect = True
            elif i == 'na':
                return (False, index)
            elif i == 'n':
                return (None, index)

        # Resolving
        logwarning('adding from parse error key = {}, value = {}'.format(key, value))
        index = self.__constructelement(key, value, comment, language, usecomments, index)

        return (autocorrect, index)

    # Cocoa writing

    def __cocoa_string(self, language, pretty = False):
        """Returns the corresponding cocoa string
        """
        s = "\n".join((item.cocoa_line(language) for item in self.elements))
        if pretty:
            s = re.sub('$\s*?(?=/)','\n\n',s,flags=re.MULTILINE)
        return s

    def cocoa_write(self, languages=None, path='.', overwrite=False, tablename='Localizable', pretty = False):
        """Writes the resources in the corresponding lproj directories
        e.g with the default arguments, the en file will be written to en.lproj/Localizable.strings

        Keyword Arguments:
        languages --  the chosen languages. If none is provided, all languages are created. Defaults to None.
        path -- the directory in which the .lproj directories will be written. Defaults to '.'
        tablename -- the tableName, i-e the name of the strings file. Defaults to 'Localizable'
        """
        if os.path.exists(path) and not os.path.isdir(path):
            raise LangError('Output path {} is not a directory'.format(path))

        if not languages:
            languages = self.languages

        if len(languages)>1:
            for l in self.languages:
                self.cocoa_write([l], path, overwrite, tablename, pretty)
        else:
            language = languages[0]
            dirpath = os.path.join(path,language + os.path.extsep + "lproj")
            if not os.path.exists(dirpath):
                os.makedirs(dirpath)
            outputpath = os.path.join(dirpath, tablename + os.path.extsep + "strings")
            if os.path.exists(outputpath) and not overwrite:
                raise LangError('File already exists at path %s' % outputpath)

            s = self.__cocoa_string(language, pretty)
            loginfo('Writing cocoa file at path '+outputpath)
            with  open(outputpath, 'w') as f:
                f.write(s)

    # Csv reading

    @classmethod
    def __csv_parsefirstrow(cls, row, languages, usecomments):
        """Returns (keyindex, commentindex, langindices)
        """
        (keyindex, commentindex, langindices) = (None, None, {})
        # Getting key
        try:
            keyindex = row.index('key')
        except IndexError:
            raise LangError('Could not find key column in csv')
        # Getting comment
        if usecomments:
            try:
                commentindex = row.index('comment')
            except IndexError:
                logwarning('Could not find comment column in csv')
        # Getting languages
        for c in row:
            if not c in ('key','comment'):
                if languages and c not in languages:  # ignoring if not in languages
                    continue
                langindices[c] = row.index(c)

        return (keyindex, commentindex, langindices)

    def __csv_feedrow(self, row, keyindex, commentindex, langindices, index):
        # Getting key
        try:
            key = row[keyindex]
        except IndexError:
            key = None
        # Getting value
        values = {}
        for l in self.languages:
            try:
                values[l] = row[langindices[l]]
            except KeyError, IndexError:  # Either language not present in file (language may come from another file), or column not present in row
                values[l] = ''
        # Getting comment
        if commentindex == None:
            comment = None
        else:
            try:
                comment = row[commentindex]
            except IndexError:
                comment = None

        return self.__constructelements(key=key, languagevaluedic=values, comment=comment, index=index)

    # Csv writing

    def csv_feed(self, path, languages=None, usecomments=True):
        with open(path, 'rb') as csvfile:
            reader = csv.reader(csvfile, delimiter=';', quotechar='"')

            (keyindex, commentindex, langindices) = (None, None, {})
            lastinsertindex = len(self.elements)-1
            for row in reader:
                if keyindex == None:  # First row
                    (keyindex, commentindex, langindices) = self.__csv_parsefirstrow(row, languages, usecomments)

                    for l in langindices.keys():
                        if l not in self.languages:
                            self.languages.append(l)

                    if not self.languages:
                        e = 'Did not find any language in file ' + path
                        if languages:
                            e += 'with language filter ' + str(languages)
                        raise LangError(e)
                else:  # Any other row
                    lastinsertindex = self.__csv_feedrow(row=row, keyindex=keyindex, commentindex=commentindex, langindices=langindices, index=lastinsertindex+1)

    def csv_write(self, path='languages.csv', overwrite=False):
        """Writes a csv file containing all the info
        """
        if not overwrite:
            if os.path.exists(path):
                raise LangError('File already existed at path "{}"'.format(path))

        loginfo('Writing csv file at path '+path)

        with open(path, 'wb') as csvfile:
            writer = csv.writer(csvfile, delimiter=';', quotechar='"', quoting=csv.QUOTE_ALL)
            writer.writerow(['comment','key', ] + self.languages)
            for element in self.elements:
                writer.writerow(element.csv_columns(self.languages))

    # Info

    def printinfo(self, details=False):
        print('\n==================\n'\
              ' Info\n')
        print('Languages: ' + str(self.languages))
        print('String count: ' + str(len(self.keyedelements)))
        # Calculating missing keys
        if self.languages and len(self.languages)>1:
            missing = self.missingvalues()
            if missing:
                if details:
                    print('Missing values:')
                    for k,v in missing.iteritems():
                        print('   {} : {}'.format(k, v))
                else:
                    print('Missing value count:')
                    for k,v in missing.iteritems():
                        print('   {} : {}'.format(k, len(v)))
            else:
                print('No missing value')

        print('==================\n')

# Main

if __name__ == '__main__':

    __loginfo = True

    default_outdir = '~/Desktop'
    default_outandroid = os.path.join(default_outdir, 'strings.xml')
    default_outios = os.path.join(default_outdir, 'strings')
    default_outcsv = os.path.join(default_outdir, 'languages.csv')

    parser = argparse.ArgumentParser(prog='gddlang',description='Converts back and forth between csv, android or cocoa langauge files.', epilog='xoxo')
    parser.add_argument('paths', help='Input paths.', type=str, nargs='+')
    parser.add_argument('--no_warning', help='Disable warnings', action='store_true', default=False)
    parser.add_argument('--no_comments', help='Disable comments', action='store_true', default=False)
    parser.add_argument('--auto_correct', help='Consider conflicts? If not specified, you will be prompted if some happen', type=bool, choices=[True,False], default=None)
    parser.add_argument('-l', '--languages', help='Language filter', nargs='+', type=str)
    parser.add_argument('--silent', help='Only outputs error', action='store_true', default=False)
    # Input
    inputs = parser.add_argument_group(title='Input')
    inputargs = inputs.add_mutually_exclusive_group(required=True)
    inputargs.add_argument('-a', help='Input is android.', action='store_true')
    inputargs.add_argument('-c', help='Input is csv. Expecting .csv file with first line : [comment] | keys | language1 | language2 ....', action='store_true')
    inputargs.add_argument('-i', help='Input is cocoa. Path can either be a folder containing lproj dirs, an lproj dir or a .strings file', action='store_true')
    # Output
    outputs = parser.add_argument_group(title='Output')
    outputs.add_argument('--info', help='Do not print info. 0=No info 1=Default 2=Details.', default=1, type=int, choices=[0,1,2])
    outputs.add_argument('-A', help='Output android. If no path is provided, {} is used.'.format(default_outandroid), nargs='?', type=str, const=default_outandroid)
    outputs.add_argument('-C', help='Output csv. If no path is provided, {} is used'.format(default_outcsv), nargs='?', type=str, const=default_outcsv)
    outputs.add_argument('-I', help='Output cocoa. If no path is provided, {} is used'.format(default_outios), nargs='?', type=str, const=default_outios)
    outputs.add_argument('-f', '--force', help='Overwrite', action='store_true')
    outputs.add_argument('-p', '--pretty', help='Try to increase prettyness of output files', action='store_true')

    args = parser.parse_args()

    if args.silent:
        __showinfo = False
        __showwarnings = False
    elif args.no_warning:
        __showinfo = True
        __showwarnings = False
    else:
        __showinfo = True
        __showwarnings = True

    res = LanguageResource()

    for path in args.paths:
        path=os.path.expanduser(path)

        if not os.path.exists(path):
            print('Error: could not find file at path '+path)

        if args.a:
            print('Android input is not yet supported')
            exit()
        elif args.c:
            res.csv_feed(path=path, languages=args.languages, usecomments=not args.no_comments)
        elif args.i:
            res.cocoa_feed(path=path, languages=args.languages, usecomments=not args.no_comments, autocorrect=args.auto_correct)

    if args.info == 1:
        res.printinfo(False)
    elif args.info == 2:
        res.printinfo(True)

    if not res.getlanguages():
        exit()

    if args.A:
        print('Android output is not yet supported')
    if args.C:
        try:
            res.csv_write(path=os.path.expanduser(args.C), overwrite=args.force)
        except LangError as e:
            print(e)
    if args.I:
        try:
            res.cocoa_write(path=os.path.expanduser(args.I), pretty=args.pretty, overwrite=args.force)
        except LangError as e:
            print(e)


text:
var compilerSupport=require('../../src/compilerSupport');// <-- mind the BOM (should be absent in processed file)
var main = function () {
    var __builder = new compilerSupport.TaskBuilder(), __state = 0, __continue = __builder.CONT, __ex;
    var data;
    return __builder.run(function () {
        switch (__state) {
        case 0: {
                data = 12345;
                console.log("data: " + data);
                __state = -1;
                __builder.ret(data);
                break;
            }
        default:
            throw 'Internal error: encountered wrong state';
        }
    });
};

main().then(function(x) {
    console.log("returned: " + x);
}, function(y) {
    console.log("failed: " + y);
});


text:
package com.schinizer.hackernews.features.newsfeed;

import com.schinizer.hackernews.data.ItemRepositoryComponent;
import com.schinizer.hackernews.utility.schedulers.SchedulersModule;
import com.schinizer.hackernews.utility.ActivityScoped;

import dagger.Component;

/**
 * Created by DPSUser on 10/25/2016.
 */

@ActivityScoped
@Component(dependencies = {ItemRepositoryComponent.class}, modules = {NewsFeedPresenterModule.class, SchedulersModule.class})
public interface NewsFeedComponent {
    void inject(NewsFeedActivity activity);
}


text: export { Scan16 as default } from "../../";


text:
Dir[File.dirname(__FILE__)+'/*.rb'].each{ |f| require f }

module RubySvgImageGenerator
  class LandscapeTheme < RubySvgImageGenerator::Theme

    def initialize
      super "landscape", 24, 16
      @parts = [] << Background.new << Sun.new << Ground.new << Flowers.new <<
      CloudsBack.new << MountainsBack.new << MountainsFront.new << River.new <<
      CloudsFront.new << Trees1.new << Trees2.new << Trees3.new
    end

  end
end


text:
from faker import Faker
from sqlalchemy.exc import InvalidRequestError

import zeeguu_core.model

class BaseRule:
    """The base class for the Rule testing framework.
    Holds functions to save an object to the database.
    If the functionality of how to save an object to the database changes, it only needs to be changed here.

    Dedicated Rule classes, which actually create the random objects inherit from this rule class and need to
    implement the '_create_model_object' and '_exists_in_db' function.

    The Rule testing framework uses Rule classes in order to create random objects from the classes defined in the
    zeeguu/model package for testing purposes.

    This way, random model objects can be created and deleted after each unit test.

    The Faker library is used to create the random data.
    """
    faker = Faker()

    db = zeeguu_core.db

    @classmethod
    def save(cls, obj):
        try:
            cls.db.session.add(obj)
            cls.db.session.commit()
        except InvalidRequestError:
            cls.db.session.rollback()
            cls.save(obj)

    def _create_model_object(self, *args):
        raise NotImplementedError

    @staticmethod
    def _exists_in_db(obj):
        raise NotImplementedError


text:
<?php

/**
 * @param array $source_languages
 *
 * @return array[]
 */
function filter_tm_source_langs( $source_languages ) {
	global $wpdb, $sitepress;

	$tm_filter = new WPML_TM_Filters( $wpdb, $sitepress );

	return $tm_filter->filter_tm_source_langs( $source_languages );
}

/**
 *
 * @param bool       $assigned_correctly
 * @param string     $string_translation_id in the format used by
 *                                          TM functionality as
 *                                          "string|{$string_translation_id}"
 * @param int        $translator_id
 * @param int|string $service
 *
 * @return bool
 */
function wpml_st_filter_job_assignment( $assigned_correctly, $string_translation_id, $translator_id, $service ) {
	global $wpdb, $sitepress;

	$tm_filter = new WPML_TM_Filters( $wpdb, $sitepress );

	return $tm_filter->job_assigned_to_filter( $assigned_correctly, $string_translation_id, $translator_id, $service );
}

/**
 * @param string $notice
 * @param array  $custom_posts
 *
 * @return string
 */
function filter_tm_cpt_dashboard_notice( $notice, $custom_posts ) {
	global $sitepress, $wpml_st_string_factory;

	$tm_filter      = new WPML_TM_Widget_Filter( $sitepress, $wpml_st_string_factory );
	$admin_notifier = new WPML_Admin_Notifier();

	return $tm_filter->filter_cpt_dashboard_notice( $notice, $custom_posts, $admin_notifier );
}

add_filter( 'wpml_tm_allowed_source_languages', 'filter_tm_source_langs', 10, 1 );
add_filter( 'wpml_tm_dashboard_cpt_notice', 'filter_tm_cpt_dashboard_notice', 10, 3 );
add_filter( 'wpml_job_assigned_to_after_assignment', 'wpml_st_filter_job_assignment', 10, 4 );

function wpml_st_blog_title_filter( $val ) {
	return icl_t( 'WP', 'Blog Title', $val );
}

function wpml_st_blog_description_filter( $val ) {

	return icl_t( 'WP', 'Tagline', $val );
}


text:
<?php
defined('C5_EXECUTE') or die("Access Denied.");

$controller->nextLabel=t('Next');
$controller->previousLabel=t('Previous');
$controller->parentLabel=t('Up');
$controller->showArrows=1;
$controller->loopSequence=1;
$controller->orderBy='display_asc';

$this->inc('form_setup_html.php', array('controller'=>$controller));


text:
;modjewel.define("weinre/client/InspectorFrontendHostImpl", function(require, exports, module) { // Generated by CoffeeScript 1.3.3
var IDLTools, InspectorFrontendHostImpl, Weinre, _extensionAPI;

Weinre = require('../common/Weinre');

IDLTools = require('../common/IDLTools');

_extensionAPI = null;

module.exports = InspectorFrontendHostImpl = (function() {

  function InspectorFrontendHostImpl() {
    this._getPlatformAndPort();
  }

  InspectorFrontendHostImpl.prototype.showContextMenu = function() {};

  InspectorFrontendHostImpl.prototype.loaded = function() {};

  InspectorFrontendHostImpl.prototype.localizedStringsURL = function() {
    return "nls/English.lproj/localizedStrings.js";
  };

  InspectorFrontendHostImpl.prototype.hiddenPanels = function() {
    return "audits,profiles";
  };

  InspectorFrontendHostImpl.prototype.platform = function() {
    return "weinre";
  };

  InspectorFrontendHostImpl.prototype.port = function() {
    return "weinre";
  };

  InspectorFrontendHostImpl.prototype.sendMessageToBackend = function(message) {
    var object;
    object = JSON.parse(message);
    if (object[0] === "setInjectedScriptSource") {
      object[1] = "<long script elided>";
    }
    return Weinre.logInfo(arguments.callee.name + ("(" + (JSON.stringify(object, null, 4)) + ")"));
  };

  InspectorFrontendHostImpl.prototype.setExtensionAPI = function(extensionAPI) {
    return _extensionAPI = extensionAPI;
  };

  InspectorFrontendHostImpl.prototype.getExtensionAPI = function() {
    return _extensionAPI;
  };

  InspectorFrontendHostImpl.prototype.inspectedURLChanged = function() {};

  InspectorFrontendHostImpl.prototype._getPlatformAndPort = function() {
    var key, pieces, properties, property, splits, uas, url, val, _i, _len, _results;
    this._platform = "weinre";
    this._platformFlavor = "weinre";
    this._port = "weinre";
    if (true) {
      return;
    }
    uas = navigator.userAgent;
    if (uas.match(/mac os x/i)) {
      this._platform = "mac";
    } else if (uas.match(/macintosh/i)) {
      this._platform = "mac";
    } else if (uas.match(/linux/i)) {
      this._platform = "linux";
    } else {
      if (uas.match(/windows/i)) {
        this._platform = "windows";
      }
    }
    url = window.location.href;
    splits = url.split("#", 2);
    if (splits.length > 1) {
      properties = splits[1];
      properties = properties.split("&");
      _results = [];
      for (_i = 0, _len = properties.length; _i < _len; _i++) {
        property = properties[_i];
        pieces = property.split("=");
        if (pieces.length > 1) {
          key = pieces[0];
          val = pieces[1];
          if (key === "platform") {
            _results.push(this._platform = val);
          } else if (key === "platformFlavor") {
            _results.push(this._platformFlavor = val);
          } else {
            if (key === "port") {
              _results.push(this._port = val);
            } else {
              _results.push(void 0);
            }
          }
        } else {
          _results.push(void 0);
        }
      }
      return _results;
    }
  };

  return InspectorFrontendHostImpl;

})();

require("../common/MethodNamer").setNamesForClass(module.exports);

});


text:
'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var Float64Array = require( '@stdlib/array/float64' );
var ArrayBuffer = require( '@stdlib/array/buffer' );
var pkg = require( './../package.json' ).name;
var unshift = require( './../lib' );

// MAIN //

bench( pkg+'::float64array,preallocated', function benchmark( b ) {
	var arr;
	var buf;
	var i;

	buf = new ArrayBuffer( b.iterations*8 ); // 8 bytes per double
	arr = new Float64Array( buf, b.iterations*8, 0 );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		arr = unshift( arr, i );
		if ( arr.length !== i+1 ) {
			b.fail( 'should have added an element' );
		}
	}
	b.toc();
	if ( arr.length !== b.iterations ) {
		b.fail( 'should have added elements' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+'::float64array,preallocated,no-value', function benchmark( b ) {
	var arr;
	var buf;
	var i;

	buf = new ArrayBuffer( b.iterations*8 ); // 8 bytes per double
	arr = new Float64Array( buf, b.iterations*8, 0 );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		arr = unshift( arr );
		if ( arr.length !== 0 ) {
			b.fail( 'should not have added an element' );
		}
	}
	b.toc();
	if ( arr.length !== 0 ) {
		b.fail( 'should not have added elements' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+'::float64array,preallocated,no-wrapper', function benchmark( b ) {
	var unshift;
	var arr;
	var buf;
	var i;

	unshift = require( './../lib/unshift_typed_array.js' );

	buf = new ArrayBuffer( b.iterations*8 ); // 8 bytes per double
	arr = new Float64Array( buf, b.iterations*8, 0 );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		arr = unshift( arr, [ i ] );
		if ( arr.length !== i+1 ) {
			b.fail( 'should have added an element' );
		}
	}
	b.toc();
	if ( arr.length !== b.iterations ) {
		b.fail( 'should have added elements' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+'::float64array,control,preallocated,constructor', function benchmark( b ) {
	var offset;
	var arr;
	var buf;
	var i;

	buf = new ArrayBuffer( b.iterations*8 ); // 8 bytes per double
	arr = new Float64Array( buf, b.iterations*8, 0 );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		// Here, we are only testing the operation of creating a new view each time a value must be added to a typed array:
		offset = arr.byteOffset - arr.BYTES_PER_ELEMENT;
		arr = new Float64Array( arr.buffer, offset, i+1 );
		if ( arr.length !== i+1 ) {
			b.fail( 'should have added an element' );
		}
	}
	b.toc();
	if ( arr.length !== b.iterations ) {
		b.fail( 'should have added elements' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+'::float64array,control,preallocated,constructor,value', function benchmark( b ) {
	var offset;
	var arr;
	var buf;
	var i;
	var j;

	buf = new ArrayBuffer( b.iterations*8 ); // 8 bytes per double
	arr = new Float64Array( buf, b.iterations*8, 0 );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		offset = arr.byteOffset - arr.BYTES_PER_ELEMENT;
		arr = new Float64Array( arr.buffer, offset, i+1 );
		for ( j = 0; j < 1; j++ ) {
			arr[ i+j ] = i + j;
		}
		if ( arr.length !== i+1 ) {
			b.fail( 'should have added an element' );
		}
	}
	b.toc();
	if ( arr.length !== b.iterations ) {
		b.fail( 'should have added elements' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});