text:
package org.elasticsearch.action.admin.indices.readonly;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.DestructiveOperations;
import org.elasticsearch.action.support.master.TransportMasterNodeAction;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.metadata.MetadataIndexStateService;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.index.Index;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;

import java.util.Collections;

/**
 * Adds a single index level block to a given set of indices. Not only does it set the correct setting,
 * but it ensures that, in case of a write block, once successfully returning to the user, all shards
 * of the index are properly accounting for the block, for instance, when adding a write block all
 * in-flight writes to an index have been completed prior to the response being returned. These actions
 * are done in multiple cluster state updates (at least two). See also {@link TransportVerifyShardIndexBlockAction}
 * for the eventual delegation for shard-level verification.
 */
public class TransportAddIndexBlockAction extends TransportMasterNodeAction<AddIndexBlockRequest, AddIndexBlockResponse> {

    private static final Logger logger = LogManager.getLogger(TransportAddIndexBlockAction.class);

    private final MetadataIndexStateService indexStateService;
    private final DestructiveOperations destructiveOperations;

    @Inject
    public TransportAddIndexBlockAction(TransportService transportService, ClusterService clusterService,
                                        ThreadPool threadPool, MetadataIndexStateService indexStateService,
                                        ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver,
                                        DestructiveOperations destructiveOperations) {
        super(AddIndexBlockAction.NAME, transportService, clusterService, threadPool, actionFilters, AddIndexBlockRequest::new,
            indexNameExpressionResolver, AddIndexBlockResponse::new, ThreadPool.Names.SAME);
        this.indexStateService = indexStateService;
        this.destructiveOperations = destructiveOperations;
    }

    @Override
    protected void doExecute(Task task, AddIndexBlockRequest request, ActionListener<AddIndexBlockResponse> listener) {
        destructiveOperations.failDestructive(request.indices());
        super.doExecute(task, request, listener);
    }

    @Override
    protected ClusterBlockException checkBlock(AddIndexBlockRequest request, ClusterState state) {
        if (request.getBlock().getBlock().levels().contains(ClusterBlockLevel.METADATA_WRITE) &&
            state.blocks().global(ClusterBlockLevel.METADATA_WRITE).isEmpty())  {
            return null;
        }
        return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA_WRITE,
            indexNameExpressionResolver.concreteIndexNames(state, request));
    }

    @Override
    protected void masterOperation(final Task task,
                                   final AddIndexBlockRequest request,
                                   final ClusterState state,
                                   final ActionListener<AddIndexBlockResponse> listener) throws Exception {
        final Index[] concreteIndices = indexNameExpressionResolver.concreteIndices(state, request);
        if (concreteIndices == null || concreteIndices.length == 0) {
            listener.onResponse(new AddIndexBlockResponse(true, false, Collections.emptyList()));
            return;
        }

        final AddIndexBlockClusterStateUpdateRequest addBlockRequest = new AddIndexBlockClusterStateUpdateRequest(request.getBlock(),
            task.getId())
            .ackTimeout(request.timeout())
            .masterNodeTimeout(request.masterNodeTimeout())
            .indices(concreteIndices);
        indexStateService.addIndexBlock(addBlockRequest, ActionListener.delegateResponse(listener, (delegatedListener, t) -> {
            logger.debug(() -> new ParameterizedMessage("failed to mark indices as readonly [{}]", (Object) concreteIndices), t);
            delegatedListener.onFailure(t);
        }));
    }
}


text:
package test.com.elezeta.wdbunit.testfile.common;

import static org.junit.Assert.*;

import org.junit.Test;

import test.com.elezeta.wdbunit.testfile.TestTools;

import com.elezeta.wdbunit.testfile.common.Identifier;

public class IdentifierTest {

	@Test
	public void IdentifiersTest() {
		TestTools.checkMatches(Identifier.class,"abc",1);
		TestTools.checkMatches(Identifier.class,"a9",1);
		TestTools.checkMatches(Identifier.class,"_abc",1);
		TestTools.checkMatches(Identifier.class,"a_",1);
		TestTools.checkMatches(Identifier.class,"a",1);
		TestTools.checkMatches(Identifier.class,"_",1);
		TestTools.checkMatches(Identifier.class,"0",0);
		TestTools.checkMatches(Identifier.class,"0abc",0);
		TestTools.checkMatches(Identifier.class,"abc-",0);
		TestTools.checkMatches(Identifier.class,"abc@",0);
		TestTools.checkMatches(Identifier.class,"ab.c",0);

		assertEquals("testvalue",((Identifier)TestTools.parse(Identifier.class,"testvalue")).getValue());
	}

}

redpajama_set_name: RedPajamaGithub


text:
#include "Material.h"

class GeneratedMesh;
typedef std::shared_ptr<GeneratedMesh> GeneratedMeshPtr;

class GeneratedMesh
{
public:
	static GeneratedMeshPtr Create(
		ID3D11Device* device,
		unsigned bufferSize,
		const std::string& generatingFunction,
		const DirectX::XMINT3& dispatch);
	virtual ~GeneratedMesh();

	void SetDynamic(bool d)
	{
		m_Dynamic = d;
	}

	bool IsDynamic() const
	{
		return m_Dynamic;
	}

	const Material& GetMaterial() const
	{
		return m_Material;
	}

	void SetMaterial(const Material& m)
	{
		m_Material = m;
	}

	void SetGenerator(const std::string& generatingFunction,
		const DirectX::XMINT3& dispatch)
	{
		m_GeneratingFunction = generatingFunction;
		m_Dispatch = dispatch;
	}

	const std::string& GetGeneratingFunction() const
	{
		return m_GeneratingFunction;
	}

	const DirectX::XMINT3& GetDispatch() const
	{
		return m_Dispatch;
	}

	unsigned GetBufferSize() const
	{
		return m_BufferSize;
	}

	ID3D11Buffer* GetVertexBuffer() const
	{
		return m_GeneratedBuffer.Get();
	}
	ID3D11Buffer* GetIndexBuffer() const
	{
		return m_GeneratedIB.Get();
	}
	ID3D11Buffer* GetCountersBuffer() const
	{
		return m_CountersBuffer.Get();
	}
	ID3D11Buffer* GetIndirectBuffer() const
	{
		return m_IndirectBuffer.Get();
	}

	ID3D11UnorderedAccessView* GetVertexBufferUAV() const
	{
		return m_GeneratedUAV.Get();
	}
	ID3D11UnorderedAccessView* GetIndexBufferUAV() const
	{
		return m_GeneratedIBUAV.Get();
	}
	ID3D11UnorderedAccessView* GetCountersBufferUAV() const
	{
		return m_CountersUAV.Get();
	}
	ID3D11UnorderedAccessView* GetIndirectBufferUAV() const
	{
		return m_IndirectUAV.Get();
	}

	ID3D11ShaderResourceView* GetCountersSRV() const
	{
		return m_CountersSRV.Get();
	}
private:
	GeneratedMesh(unsigned buffSize,
		const std::string& generatingFunction,
		const DirectX::XMINT3& dispatch);

	unsigned m_BufferSize;
	std::string m_GeneratingFunction;
	DirectX::XMINT3 m_Dispatch;

	ReleaseGuard<ID3D11Buffer> m_GeneratedBuffer;
	ReleaseGuard<ID3D11UnorderedAccessView> m_GeneratedUAV;

	ReleaseGuard<ID3D11Buffer> m_GeneratedIB;
	ReleaseGuard<ID3D11UnorderedAccessView> m_GeneratedIBUAV;

	ReleaseGuard<ID3D11Buffer> m_CountersBuffer;
	ReleaseGuard<ID3D11UnorderedAccessView> m_CountersUAV;
	ReleaseGuard<ID3D11ShaderResourceView> m_CountersSRV;

	ReleaseGuard<ID3D11Buffer> m_IndirectBuffer;
	ReleaseGuard<ID3D11UnorderedAccessView> m_IndirectUAV;

	Material m_Material;
	bool m_Dynamic;
};


text:
export interface HTTPResponse {
    /**
     * The status number of the response
     */
    status: number;
    /**
     * The data that is in the response. This property usually exists when a promise returned by a request method resolves.
     */
    data?: any;
    /**
     * The headers of the response
     */
    headers: any;
    /**
     * Error response from the server. This property usually exists when a promise returned by a request method rejects.
     */
    error?: string;
}
/**
 * @name HTTP
 * @description
 * Cordova / Phonegap plugin for communicating with HTTP servers. Supports iOS and Android.
 *
 * Advantages over Javascript requests:
 * - Background threading - all requests are done in a background thread
 * - SSL Pinning
 *
 * @usage
 * ```
 * import { HTTP } from 'ionic-native';
 *
 * HTTP.get('http://ionic.io', {}, {})
 *   .then(data => {
 *
 *     console.log(data.status);
 *     console.log(data.data); // data received by server
 *     console.log(data.headers);
 *
 *   })
 *   .catch(error => {
 *
 *     console.log(error.status);
 *     console.log(error.error); // error message as string
 *     console.log(error.headers);
 *
 *   });
 *
 * ```
 * @interfaces
 * HTTPResponse
 */
export declare class HTTP {
    /**
     * This returns an object representing a basic HTTP Authorization header of the form.
     * @param username {string} Username
     * @param password {string} Password
     * @returns {Object} an object representing a basic HTTP Authorization header of the form {'Authorization': 'Basic base64encodedusernameandpassword'}
     */
    static getBasicAuthHeader(username: string, password: string): {
        Authorization: string;
    };
    /**
     * This sets up all future requests to use Basic HTTP authentication with the given username and password.
     * @param username {string} Username
     * @param password {string} Password
     */
    static useBasicAuth(username: string, password: string): void;
    /**
     * Set a header for all future requests. Takes a header and a value.
     * @param header {string} The name of the header
     * @param value {string} The value of the header
     */
    static setHeader(header: string, value: string): void;
    /**
     * Enable or disable SSL Pinning. This defaults to false.
     *
     * To use SSL pinning you must include at least one .cer SSL certificate in your app project. You can pin to your server certificate or to one of the issuing CA certificates. For ios include your certificate in the root level of your bundle (just add the .cer file to your project/target at the root level). For android include your certificate in your project's platforms/android/assets folder. In both cases all .cer files found will be loaded automatically. If you only have a .pem certificate see this stackoverflow answer. You want to convert it to a DER encoded certificate with a .cer extension.
     *
     * As an alternative, you can store your .cer files in the www/certificates folder.
     * @param enable {boolean} Set to true to enable
     * @returns {Promise<void>} returns a promise that will resolve on success, and reject on failure
     */
    static enableSSLPinning(enable: boolean): Promise<void>;
    /**
     * Accept all SSL certificates. Or disabled accepting all certificates. Defaults to false.
     * @param accept {boolean} Set to true to accept
     * @returns {Promise<void>} returns a promise that will resolve on success, and reject on failure
     */
    static acceptAllCerts(accept: boolean): Promise<void>;
    /**
     * Whether or not to validate the domain name in the certificate. This defaults to true.
     * @param validate {boolean} Set to true to validate
     * @returns {Promise<void>} returns a promise that will resolve on success, and reject on failure
     */
    static validateDomainName(validate: boolean): Promise<void>;
    /**
     * Make a POST request
     * @param url {string} The url to send the request to
     * @param body {Object} The body of the request
     * @param headers {Object} The headers to set for this request
     * @returns {Promise<HTTPResponse>} returns a promise that resolve on success, and reject on failure
     */
    static post(url: string, body: any, headers: any): Promise<HTTPResponse>;
    /**
     *
     * @param url {string} The url to send the request to
     * @param parameters {Object} Parameters to send with the request
     * @param headers {Object} The headers to set for this request
     * @returns {Promise<HTTPResponse>} returns a promise that resolve on success, and reject on failure
     */
    static get(url: string, parameters: any, headers: any): Promise<HTTPResponse>;
    /**
     *
     * @param url {string} The url to send the request to
     * @param body {Object} The body of the request
     * @param headers {Object} The headers to set for this request
     * @param filePath {string} The local path of the file to upload
     * @param name {string} The name of the parameter to pass the file along as
     * @returns {Promise<HTTPResponse>} returns a promise that resolve on success, and reject on failure
     */
    static uploadFile(url: string, body: any, headers: any, filePath: string, name: string): Promise<HTTPResponse>;
    /**
     *
     * @param url {string} The url to send the request to
     * @param body {Object} The body of the request
     * @param headers {Object} The headers to set for this request
     * @param filePath {string} The path to donwload the file to, including the file name.
     * @returns {Promise<HTTPResponse>} returns a promise that resolve on success, and reject on failure
     */
    static downloadFile(url: string, body: any, headers: any, filePath: string): Promise<HTTPResponse>;
}


text:
import gulp = require('gulp');
import debug = require('gulp-debug');

gulp.task('default', () =>
    gulp.src('foo.js')
        .pipe(debug({title: 'unicorn:'}))
        .pipe(gulp.dest('dist'))
);

debug();


text:
<?php

/**
 * Doctrine_Migration_Builder
 *
 * @package     Doctrine
 * @subpackage  Migration
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @author      Jonathan H. Wage <jwage@mac.com>
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link        www.phpdoctrine.org
 * @since       1.0
 * @version     $Revision: 2939 $
 */
class Doctrine_Migration_Builder extends Doctrine_Builder
{
    /**
     * migrationsPath
     *
     * The path to your migration classes directory
     *
     * @var string
     */
    private $migrationsPath = '';

    /**
     * suffix
     *
     * File suffix to use when writing class definitions
     *
     * @var string $suffix
     */
    private $suffix = '.class.php';

    /**
     * migration
     *
     * @var string
     */
    private $migration;

    /**
     * tpl
     *
     * Class template used for writing classes
     *
     * @var $tpl
     */
    private static $tpl;

    /**
     * __construct
     *
     * @return void
     */
    public function __construct($migrationsPath = null)
    {
        if ($migrationsPath) {
            $this->setMigrationsPath($migrationsPath);
            $this->migration = new Doctrine_Migration($migrationsPath);
        }

        $this->loadTemplate();
    }

    /**
     * setMigrationsPath
     *
     * @param string path   the path where migration classes are stored and being generated
     * @return
     */
    public function setMigrationsPath($path)
    {
        Doctrine_Lib::makeDirectories($path);

        $this->migrationsPath = $path;
    }

    /**
     * getMigrationsPath
     *
     * @return string       the path where migration classes are stored and being generated
     */
    public function getMigrationsPath()
    {
        return $this->migrationsPath;
    }

    /**
     * loadTemplate
     *
     * Loads the class template used for generating classes
     *
     * @return void
     */
    protected function loadTemplate()
    {
        if (isset(self::$tpl)) {
            return;
        }

        self::$tpl =<<<END
/**
 * This class has been auto-generated by the Doctrine ORM Framework
 */
class %s extends %s
{
	public function up()
	{
%s
	}

	public function down()
	{
%s
	}
}
END;
    }

    /**
     * generateMigrationsFromDb
     *
     * @return void
     */
    public function generateMigrationsFromDb()
    {
        $directory = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'tmp_doctrine_models';

        Doctrine::generateModelsFromDb($directory);

        $result = $this->generateMigrationsFromModels($directory, Doctrine::MODEL_LOADING_CONSERVATIVE);

        Doctrine_Lib::removeDirectories($directory);

        return $result;
    }

    /**
     * generateMigrationsFromModels
     *
     * @param string $modelsPath
     * @return void
     */
    public function generateMigrationsFromModels($modelsPath = null, $modelLoading = null)
    {
        if ($modelsPath !== null) {
            $models = Doctrine::filterInvalidModels(Doctrine::loadModels($modelsPath, $modelLoading));
        } else {
            $models = Doctrine::getLoadedModels();
        }

        $models = Doctrine::initializeModels($models);

        $foreignKeys = array();

        foreach ($models as $model) {
            $table = Doctrine::getTable($model);
            if ($table->getTableName() !== $this->migration->getTableName()) {
                $export = $table->getExportableFormat();

                $foreignKeys[$export['tableName']] = $export['options']['foreignKeys'];

                $up = $this->buildCreateTable($export);
                $down = $this->buildDropTable($export);

                $className = 'Add' . Doctrine_Inflector::classify($export['tableName']);

                $this->generateMigrationClass($className, array(), $up, $down);
            }
        }

        if ( ! empty($foreignKeys)) {
            $className = 'ApplyForeignKeyConstraints';

            $up = '';
            $down = '';
            foreach ($foreignKeys as $tableName => $definitions)    {
                $tableForeignKeyNames[$tableName] = array();

                foreach ($definitions as $definition) {
                    $definition['name'] = $tableName . '_' .implode('_', (array)$definition['local']);

                    $up .= $this->buildCreateForeignKey($tableName, $definition);
                    $down .= $this->buildDropForeignKey($tableName, $definition);
                }
            }

            $this->generateMigrationClass($className, array(), $up, $down);
        }

        return true;
    }

    /**
     * buildCreateForeignKey
     *
     * @param string $tableName
     * @param string $definition
     * @return void
     */
    public function buildCreateForeignKey($tableName, $definition)
    {
        return "\t\t\$this->createForeignKey('" . $tableName . "', " . $this->varExport($definition, true) . ");";
    }

    /**
     * buildDropForeignKey
     *
     * @param string $tableName
     * @param string $definition
     * @return void
     */
    public function buildDropForeignKey($tableName, $definition)
    {
        return "\t\t\$this->dropForeignKey('" . $tableName . "', '" . $definition['name'] . "');\n";
    }

    /**
     * buildCreateTable
     *
     * @param string $tableData
     * @return void
     */
    public function buildCreateTable($tableData)
    {
        $code  = "\t\t\$this->createTable('" . $tableData['tableName'] . "', ";

        $code .= $this->varExport($tableData['columns'], true) . ", ";

        $code .= $this->varExport(array('indexes' => $tableData['options']['indexes'], 'primary' => $tableData['options']['primary']), true);

        $code .= ");";

        return $code;
    }

    /**
     * buildDropTable
     *
     * @param string $tableData
     * @return string
     */
    public function buildDropTable($tableData)
    {
        return "\t\t\$this->dropTable('" . $tableData['tableName'] . "');";
    }

    /**
     * generateMigrationClass
     *
     * @return void
     */
    public function generateMigrationClass($className, $options = array(), $up = null, $down = null, $return = false)
    {
        $className = Doctrine_Inflector::urlize($className);
        $className = str_replace('-', '_', $className);
        $className = Doctrine_Inflector::classify($className);

        if ($return || ! $this->getMigrationsPath()) {
            return $this->buildMigrationClass($className, null, $options, $up, $down);
        } else {
            if ( ! $this->getMigrationsPath()) {
                throw new Doctrine_Migration_Exception('You must specify the path to your migrations.');
            }

            $next = (string) $this->migration->getNextVersion();

            $fileName = str_repeat('0', (3 - strlen($next))) . $next . '_' . Doctrine_Inflector::tableize($className) . $this->suffix;

            $class = $this->buildMigrationClass($className, $fileName, $options, $up, $down);

            $path = $this->getMigrationsPath() . DIRECTORY_SEPARATOR . $fileName;

            if ( class_exists($className) || file_exists($path)) {
                return false;
            }

            file_put_contents($path, $class);

            return true;
        }
    }

    /**
     * buildMigrationClass
     *
     * @return string
     */
    public function buildMigrationClass($className, $fileName = null, $options = array(), $up = null, $down = null)
    {
        $extends = isset($options['extends']) ? $options['extends']:'Doctrine_Migration';

        $content  = '<?php' . PHP_EOL;

        $content .= sprintf(self::$tpl, $className,
                                       $extends,
                                       $up,
                                       $down);

        return $content;
    }
}


text:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using TeaCommerce.Api.Services;

namespace TeaCommerce.Umbraco.Application.Views.Shared.Partials {
  public partial class OrderStatusSelector : UserControl {

    public string SelectedValue { get { return drpOrderStatuses.SelectedValue; } set { drpOrderStatuses.SelectedValue = value; } }
    public string CssClass { get { return drpOrderStatuses.CssClass; } set { drpOrderStatuses.CssClass = value; } }
    public ListItemCollection Items { get { return drpOrderStatuses.Items; } }
    public bool InsertEmptyItem { get; set; }
    public event EventHandler SelectedIndexChanged;

    private DropDownList drpOrderStatuses;

    protected override void OnInit( EventArgs e ) {
      drpOrderStatuses = new DropDownList();
      drpOrderStatuses.AppendDataBoundItems = true;
      drpOrderStatuses.DataTextField = "Name";
      drpOrderStatuses.DataValueField = "Id";
      drpOrderStatuses.CssClass = "guiInputText guiInputStandardSize";
      drpOrderStatuses.SelectedIndexChanged += drpOrderStatuses_SelectedIndexChanged;

      Controls.Add( drpOrderStatuses );

      base.OnInit( e );
    }

    protected override void OnLoad( EventArgs e ) {
      drpOrderStatuses.AutoPostBack = ( SelectedIndexChanged != null );

      base.OnLoad( e );
    }

    protected void drpOrderStatuses_SelectedIndexChanged( object sender, EventArgs e ) {
      if ( SelectedIndexChanged != null )
        SelectedIndexChanged( this, e );
    }

    public void LoadOrderStatuses( long storeId ) {
      drpOrderStatuses.Items.Clear();
      if ( InsertEmptyItem )
        drpOrderStatuses.Items.Add( new ListItem( "----", string.Empty ) );

      drpOrderStatuses.DataSource = OrderStatusService.Instance.GetAll( storeId );
      drpOrderStatuses.DataBind();
    }

  }
}


text:
<?php
/**
 * Created by A.Belyakovskiy.
 * Date: 8/16/15
 * Time: 2:21 PM
 */

namespace spartaksun\OrientDb;

use PhpOrient\Protocols\Binary\Data\ID;

/**
 * Class EntityInterface
 * @package spartaksun\OrientDb
 */
interface EntityInterface
{
    /**
     * @return ID
     */
    public function getRid();

    /**
     * @param $rid
     * @return void
     */
    public function setRid($rid);

    /**
     * Value of attribute
     * @param $attributeName
     * @return false|Entity|Entity[]
     */
    public function getAttribute($attributeName);

    /**
     * Entity attributes
     * @return array of name => value pairs
     */
    public function getAttributes();

    /**
     * @param array $attributes
     */
    public function setAttributes(array $attributes);

    /**
     * @param $name
     * @param $value
     */
    public function setAttribute($name, $value);

    /**
     * @return array of callable validators
     */
    public function validators();

    /**
     * @return array
     */
    public function getErrors();

    /**
     * @param $attribute
     * @param $error
     * @return mixed
     */
    public function addError($attribute, $error);

}


text:
<?php

namespace Recoil\Amqp\v091\Protocol;

/**
 * Parse scalar values from an internal buffer.
 *
 * This trait requires a string property named buffer, which it does NOT declare.
 *
 * @property string $buffer
 */
trait ScalarParserTrait
{
    /**
     * Parse an AMQP "short string" from the head of the buffer.
     *
     * The maximum length of a short string is 255 bytes.
     *
     * @todo UTF-8 validation, maybe.
     */
    private function parseShortString() : string
    {
        $length = \ord($this->buffer);

        try {
            return \substr($this->buffer, 1, $length);
        } finally {
            $this->buffer = \substr($this->buffer, $length + 1);
        }
    } // @codeCoverageIgnore

    /**
     * Parse an AMQP "long string" from the head of the buffer.
     *
     * @todo UTF-8 validation, maybe.
     */
    private function parseLongString() : string
    {
        list(, $length) = \unpack('N', $this->buffer);

        try {
            return \substr($this->buffer, 4, $length);
        } finally {
            $this->buffer = \substr($this->buffer, $length + 4);
        }
    } // @codeCoverageIgnore

    /**
     * Parse a 8-bit signed integer from the head of the buffer.
     */
    private function parseSignedInt8() : int
    {
        try {
            $result = \ord($this->buffer);

            if ($result & 0x80) {
                return $result - 0x100;
            }

            return $result;
        } finally {
            $this->buffer = \substr($this->buffer, 1);
        }
    } // @codeCoverageIgnore

    /**
     * Parse a 8-bit unsigned integer from the head of the buffer.
     */
    private function parseUnsignedInt8() : int
    {
        try {
            return \ord($this->buffer);
        } finally {
            $this->buffer = \substr($this->buffer, 1);
        }
    } // @codeCoverageIgnore

    /**
     * Parse a 16-bit signed integer from the head of the buffer.
     */
    private function parseSignedInt16() : int
    {
        try {
            $result = \unpack('n', $this->buffer)[1];

            if ($result & 0x8000) {
                return $result - 0x10000;
            }

            return $result;
        } finally {
            $this->buffer = \substr($this->buffer, 2);
        }
    } // @codeCoverageIgnore

    /**
     * Parse a 32-bit signed integer from the head of the buffer.
     */
    private function parseSignedInt32() : int
    {
        try {
            $result = \unpack('N', $this->buffer)[1];

            if ($result & 0x80000000) {
                return $result - 0x100000000;
            }

            return $result;
        } finally {
            $this->buffer = \substr($this->buffer, 4);
        }
    } // @codeCoverageIgnore

    /**
     * Parse a 32-bit unsigned integer from the head of the buffer.
     */
    private function parseUnsignedInt32() : int
    {
        try {
            return \unpack('N', $this->buffer)[1];
        } finally {
            $this->buffer = \substr($this->buffer, 4);
        }
    } // @codeCoverageIgnore

    /**
     * Parse a 64-bit signed integer from the head of the buffer.
     */
    private function parseSignedInt64() : int
    {
        try {
            // 'J' is documented as unsigned, but because PHP only has a signed
            // type a signed value is returned anyway ...
            return \unpack('J', $this->buffer)[1];
        } finally {
            $this->buffer = \substr($this->buffer, 8);
        }
    } // @codeCoverageIgnore

    /**
     * Parse a 64-bit unsigned integer from the head of the buffer.
     *
     * @return integer|string A string is returned when the value is is outside
     *                        the range of PHP's signed integer type.
     */
    private function parseUnsignedInt64()
    {
        try {
            $result = \unpack('J', $this->buffer)[1];

            if ($result < 0) {
                return \sprintf('%u', $result);
            }

            return $result;
        } finally {
            $this->buffer = \substr($this->buffer, 8);
        }
    } // @codeCoverageIgnore

    /**
     * Parse a float (4-byte) from the head of the buffer.
     */
    public function parseFloat() : float
    {
        try {
            if (Endianness::LITTLE) {
                return \unpack('f', \strrev(\substr($this->buffer, 0, 4)))[1];
            } else {
                return \unpack('f', $this->buffer)[1]; // @codeCoverageIgnore
            }
        } finally {
            $this->buffer = \substr($this->buffer, 4);
        }
    } // @codeCoverageIgnore

    /**
     * Parse a double (8-byte) from the head of the buffer.
     */
    public function parseDouble() : float
    {
        try {
            if (Endianness::LITTLE) {
                return \unpack('d', \strrev(\substr($this->buffer, 0, 8)))[1];
            } else {
                return \unpack('d', $this->buffer)[1]; // @codeCoverageIgnore
            }
        } finally {
            $this->buffer = \substr($this->buffer, 8);
        }
    } // @codeCoverageIgnore
}


text:
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, content=minimal-ui">
	<title>Question</title>
	<link rel="stylesheet" href="<?php echo base_url("assets/css/bootstrap.css"); ?>" />
	<link rel="stylesheet" href="<?php echo base_url("assets/css/style.css"); ?>" />
	<link href='http://fonts.googleapis.com/css?family=Comfortaa:400,300' rel='stylesheet' type='text/css'>

 <?php echo $question?>

<?php echo "" ?>

 <?php echo $answer_a?>

<?php echo "" ?>

 <?php echo $answer_b?>

<?php echo "" ?>

 <?php echo $answer_c?>

<?php echo "" ?>

 <?php echo $answer_d?>


text:
import React from 'react';

var GameWindowMessage = React.createClass({

  render: function() {
    var usernameChunk = this.props.message.username ?
      (<span>{ this.props.message.username }: </span>) :
      null;

    return (
      <p>
        { usernameChunk }
        { this.props.message.message }
      </p>
    );
  }

});

export default GameWindowMessage;


text:
	"this file is changed in master\n" \
	"this file is automergeable\n" \
	"this file is automergeable\n" \
	"this file is automergeable\n" \
	"this file is automergeable\n" \
	"this file is automergeable\n" \
	"this file is automergeable\n" \
	"this file is automergeable\n" \
	"this file is changed in branch\n"

#define AUTOMERGEABLE_MERGED_FILE_CRLF \
	"this file is changed in master\r\n" \
	"this file is automergeable\r\n" \
	"this file is automergeable\r\n" \
	"this file is automergeable\r\n" \
	"this file is automergeable\r\n" \
	"this file is automergeable\r\n" \
	"this file is automergeable\r\n" \
	"this file is automergeable\r\n" \
	"this file is changed in branch\r\n"

#define CONFLICTING_MERGE_FILE \
	"<<<<<<< HEAD\n" \
	"this file is changed in master and branch\n" \
	"=======\n" \
	"this file is changed in branch and master\n" \
	">>>>>>> 7cb63eed597130ba4abb87b3e544b85021905520\n"

#define CONFLICTING_DIFF3_FILE \
	"<<<<<<< HEAD\n" \
	"this file is changed in master and branch\n" \
	"||||||| initial\n" \
	"this file is a conflict\n" \
	"=======\n" \
	"this file is changed in branch and master\n" \
	">>>>>>> 7cb63eed597130ba4abb87b3e544b85021905520\n"

#define CONFLICTING_UNION_FILE \
	"this file is changed in master and branch\n" \
	"this file is changed in branch and master\n"

struct merge_index_entry {
	uint16_t mode;
	char oid_str[GIT_OID_HEXSZ+1];
	int stage;
	char path[128];
};

struct merge_name_entry {
	char ancestor_path[128];
	char our_path[128];
	char their_path[128];
};

struct merge_index_with_status {
	struct merge_index_entry entry;
	unsigned int status;
};

struct merge_reuc_entry {
	char path[128];
	unsigned int ancestor_mode;
	unsigned int our_mode;
	unsigned int their_mode;
	char ancestor_oid_str[GIT_OID_HEXSZ+1];
	char our_oid_str[GIT_OID_HEXSZ+1];
	char their_oid_str[GIT_OID_HEXSZ+1];
};

struct merge_index_conflict_data {
	struct merge_index_with_status ancestor;
	struct merge_index_with_status ours;
	struct merge_index_with_status theirs;
	git_merge_diff_type_t change_type;
};

int merge_trees_from_branches(
	git_index **index, git_repository *repo,
	const char *ours_name, const char *theirs_name,
	git_merge_options *opts);

int merge_commits_from_branches(
	git_index **index, git_repository *repo,
	const char *ours_name, const char *theirs_name,
	git_merge_options *opts);

int merge_branches(git_repository *repo,
	const char *ours_branch, const char *theirs_branch,
	git_merge_options *merge_opts, git_checkout_options *checkout_opts);

int merge_test_diff_list(git_merge_diff_list *diff_list, const struct merge_index_entry expected[], size_t expected_len);

int merge_test_merge_conflicts(git_vector *conflicts, const struct merge_index_conflict_data expected[], size_t expected_len);

int merge_test_index(git_index *index, const struct merge_index_entry expected[], size_t expected_len);

int merge_test_names(git_index *index, const struct merge_name_entry expected[], size_t expected_len);

int merge_test_reuc(git_index *index, const struct merge_reuc_entry expected[], size_t expected_len);

int merge_test_workdir(git_repository *repo, const struct merge_index_entry expected[], size_t expected_len);

#endif


text:
from django.http import HttpResponseBadRequest
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse

class GWellsRequestParsingMiddleware(MiddlewareMixin):

    def get(self, request):
        pass

    def post(self, request):
        pass

    def put(self, request):
        request.PUT = request.POST

    def delete(self, request):
        pass

    def process_request(self, request):
        _method = request.POST.get('_method')

        if _method:
            if _method.upper() == 'GET':
                self.get(request)
            elif _method.upper() == 'PUT':
                self.put(request)
            elif _method.upper() == 'POST':
                self.post(request)
            elif _method.upper() == 'DELETE':
                self.delete(request)
            else:
                message = 'Unsupported _method: ' + _method
                return HttpResponse(message, status=500)


text:
package main

import (
	"fmt"

	alerts "github.com/opsgenie/opsgenie-go-sdk/alerts"
	ogcli "github.com/opsgenie/opsgenie-go-sdk/client"
	samples "github.com/opsgenie/opsgenie-go-sdk/_samples"
	"github.com/opsgenie/opsgenie-go-sdk/_samples/constants"
)

func main() {
	cli := new(ogcli.OpsGenieClient)
	cli.SetAPIKey(constants.APIKey)

	alertCli, cliErr := cli.Alert()

	if cliErr != nil {
		panic(cliErr)
	}

	// create the alert
	req := alerts.CreateAlertRequest{Message: samples.RandStringWithPrefix("Test", 8)}
	response, alertErr := alertCli.Create(req)

	if alertErr != nil {
		panic(alertErr)
	}

	fmt.Printf("message: %s\n", response.Message)
	fmt.Printf("alert id: %s\n", response.AlertID)
	fmt.Printf("status: %s\n", response.Status)
	fmt.Printf("code: %d\n", response.Code)

	// acknowledge the alert
	ackReq := alerts.AcknowledgeAlertRequest{ID: response.AlertID}
	ackResponse, alertErr := alertCli.Acknowledge(ackReq)
	if alertErr != nil {
		panic(alertErr)
	}

	fmt.Printf("status: %s\n", ackResponse.Status)
	fmt.Printf("code: %d\n", ackResponse.Code)
}


text:
package com.alipay.api.domain;

import java.util.List;

import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;

/**
 * 随机立减奖品模型
 *
 * @author auto create
 * @since 1.0, 2017-03-03 16:47:49
 */
public class RandomDiscountDstCampPrizeModel extends AlipayObject {

	private static final long serialVersionUID = 7199678883813991514L;

	/**
	 * 折扣预算ID
	 */
	@ApiField("budget_id")
	private String budgetId;

	/**
	 * 随机立减折扣幅度列表
	 */
	@ApiListField("discount_random_model_list")
	@ApiField("discount_random_model")
	private List<DiscountRandomModel> discountRandomModelList;

	/**
	 * 奖品id
	 */
	@ApiField("id")
	private String id;

	/**
	 * 最高优惠金额=订单金额X(1-封顶折扣)
折扣幅度必须为0.3到1之间的小数(保留小数点后2位)
	 */
	@ApiField("max_random_discount_rate")
	private String maxRandomDiscountRate;

	public String getBudgetId() {
		return this.budgetId;
	}
	public void setBudgetId(String budgetId) {
		this.budgetId = budgetId;
	}

	public List<DiscountRandomModel> getDiscountRandomModelList() {
		return this.discountRandomModelList;
	}
	public void setDiscountRandomModelList(List<DiscountRandomModel> discountRandomModelList) {
		this.discountRandomModelList = discountRandomModelList;
	}

	public String getId() {
		return this.id;
	}
	public void setId(String id) {
		this.id = id;
	}

	public String getMaxRandomDiscountRate() {
		return this.maxRandomDiscountRate;
	}
	public void setMaxRandomDiscountRate(String maxRandomDiscountRate) {
		this.maxRandomDiscountRate = maxRandomDiscountRate;
	}

}


text:
class MessageBase
{
private:
    unsigned int m_time;
    unsigned int m_id;

    static unsigned int s_messageCount;

    MessageBase(const MessageBase&);

public:
    MessageBase(unsigned int time) : m_time(time), m_id(s_messageCount++) { }
    virtual ~MessageBase() { }

    void BeginTimer() { m_time += GetTickCount(); };
    unsigned int GetTime() { return m_time; };
    unsigned int GetId() { return m_id; };

    virtual HRESULT Call(LPCWSTR fileName) = 0;

    struct Comparator
    {
        bool operator()(MessageBase const* const& lhs, MessageBase const* const& rhs) const
        {
            return lhs->m_time > rhs->m_time;
        }
    };
};

class MessageQueue
{
    std::multimap<unsigned int, MessageBase*> m_queue;

public:
    void Push(MessageBase *message)
    {
        message->BeginTimer();
        m_queue.insert(std::make_pair(message->GetTime(), message));
    }

    MessageBase* PopAndWait()
    {
        Assert(!m_queue.empty());

        auto it = m_queue.begin();
        MessageBase *tmp = it->second;

        m_queue.erase(it);

        int waitTime = tmp->GetTime() - GetTickCount();
        if(waitTime > 0)
        {
            Sleep(waitTime);
        }

        return tmp;
    }

    bool IsEmpty()
    {
        return m_queue.empty();
    }

    void RemoveById(unsigned int id)
    {
        // Search for the message with the correct id, and delete it. Can be updated
        // to a hash to improve speed, if necessary.
        for(auto it = m_queue.begin(); it != m_queue.end(); ++it)
        {
            MessageBase *msg = it->second;
            if(msg->GetId() == id)
            {
                m_queue.erase(it);
                delete msg;
                break;
            }
        }
    }

    HRESULT ProcessAll(LPCWSTR fileName)
    {
        while(!IsEmpty())
        {
            MessageBase *msg = PopAndWait();

            // Omit checking return value for async function, since it shouldn't affect others.
            msg->Call(fileName);
            delete msg;
        }
        return S_OK;
    }
};

//
// A custom message helper class to assist defining messages handled by callback functions.
//
template <class Func, class CustomBase>
class CustomMessage : public CustomBase
{
private:
    Func m_func;

public:
    CustomMessage(unsigned int time, const typename CustomBase::CustomArgType& customArg, const Func& func) :
        CustomBase(time, customArg), m_func(func)
    {}

    virtual HRESULT Call(LPCWSTR fileName) override
    {
        return m_func(*this);
    }
};


text:
package com.password.protect;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Change  extends Activity  implements OnClickListener{

	Button Submitbutton;
	EditText Passwordedittext;
	String string;
	final String passs = "Password for this app";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.change);
		Submitbutton = (Button) findViewById(R.id.btnchange);
		Submitbutton.setOnClickListener(this);
		Passwordedittext = (EditText) findViewById(R.id.edittextchange);

	}

	@Override
	public void onClick(View arg0) {

		// TODO Auto-generated method stub
		string = Passwordedittext.getText().toString();

		if (string.contentEquals("") ) {

			Toast.makeText(getApplicationContext(), "Password cannot be blank.",
					Toast.LENGTH_SHORT).show();
		} else {
			try {
				FileOutputStream foss = openFileOutput(passs,
						Context.MODE_PRIVATE);
				foss.write(string.getBytes());
				foss.close();
				Toast.makeText(getApplicationContext(),
						"Your Password is changed.", Toast.LENGTH_SHORT)
						.show();
				finish();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	}


text:
#pragma once

#include <U8glib-HAL.h>

#define FONTDATA_ITEM(page, begin, end, data) { page, begin, end, COUNT(data), data }


text:
<?php

use Illuminate\Routing\Router;
use Orchestra\Support\Facades\Foundation;

/*
|--------------------------------------------------------------------------
| Routing
|--------------------------------------------------------------------------
*/

Foundation::group('bluschool/courses', 'courses', ['namespace' => 'Bluschool\Courses\Http\Controllers'], function (Router $router) {

    $router->post('courses/create', 'CoursesController@store');
    $router->get('courses/create', 'CoursesController@create');
    $router->get('courses/update/{id}', 'CoursesController@update');
    $router->get('courses/delete/{id}', 'CoursesController@delete');
    $router->get('courses/manageall', 'CoursesController@manageall');
    $router->get('courses/common', 'CoursesController@common');
    $router->get('courses/admin', 'CoursesController@index');
    $router->get('/', 'HomeController@index');

});


text:
layout: page
title: "unit-companion-banner-rtk"
excerpt: "unit-companion-banner-rtk"
categories: puppeteer
---


text:
from __future__ import unicode_literals

import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django_prices.models

class Migration(migrations.Migration):

    dependencies = [
        ('product', '0010_auto_20160129_0826'),
        ('discount', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Voucher',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('type', models.CharField(choices=[('product', 'Product'), ('category', 'Category'), ('shipping', 'Shipping'), ('basket', 'Baskets over')], max_length=20)),
                ('name', models.CharField(blank=True, max_length=255, null=True)),
                ('code', models.CharField(db_index=True, max_length=12, unique=True)),
                ('usage_limit', models.PositiveIntegerField(blank=True, help_text='Unlimited if empty', null=True)),
                ('used', models.PositiveIntegerField(default=0, editable=False)),
                ('start_date', models.DateField(default=datetime.date.today)),
                ('end_date', models.DateField(blank=True, help_text='Never expire if empty', null=True)),
                ('discount_value_type', models.CharField(choices=[('fixed', settings.DEFAULT_CURRENCY), ('percentage', '%')], default='fixed', max_length=10)),
                ('discount_value', models.DecimalField(decimal_places=2, max_digits=12)),
                ('apply_to', models.CharField(blank=True, max_length=20, null=True)),
                ('limit', django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True)),
                ('category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='product.Category')),
                ('product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='product.Product')),
            ],
        ),
    ]


text:
CREATE TABLE country (id VARCHAR(2) NOT NULL, name VARCHAR(64) NOT NULL, PRIMARY KEY(id));

INSERT INTO "country" ("id", "name") VALUES ('AF', 'Afganistanas');
INSERT INTO "country" ("id", "name") VALUES ('IE', 'Airija');
INSERT INTO "country" ("id", "name") VALUES ('AX', 'Alandų salos');
INSERT INTO "country" ("id", "name") VALUES ('AL', 'Albanija');
INSERT INTO "country" ("id", "name") VALUES ('DZ', 'Alžyras');
INSERT INTO "country" ("id", "name") VALUES ('AS', 'Amerikos Samoa');
INSERT INTO "country" ("id", "name") VALUES ('AD', 'Andora');
INSERT INTO "country" ("id", "name") VALUES ('AI', 'Angilija');
INSERT INTO "country" ("id", "name") VALUES ('AO', 'Angola');
INSERT INTO "country" ("id", "name") VALUES ('AQ', 'Antarktis');
INSERT INTO "country" ("id", "name") VALUES ('AG', 'Antigva ir Barbuda');
INSERT INTO "country" ("id", "name") VALUES ('AR', 'Argentina');
INSERT INTO "country" ("id", "name") VALUES ('AM', 'Armėnija');
INSERT INTO "country" ("id", "name") VALUES ('AW', 'Aruba');
INSERT INTO "country" ("id", "name") VALUES ('AC', 'Ascension sala');
INSERT INTO "country" ("id", "name") VALUES ('AU', 'Australija');
INSERT INTO "country" ("id", "name") VALUES ('AT', 'Austrija');
INSERT INTO "country" ("id", "name") VALUES ('AZ', 'Azerbaidžanas');
INSERT INTO "country" ("id", "name") VALUES ('BS', 'Bahamos');
INSERT INTO "country" ("id", "name") VALUES ('BH', 'Bahreinas');
INSERT INTO "country" ("id", "name") VALUES ('BY', 'Baltarusija');
INSERT INTO "country" ("id", "name") VALUES ('BD', 'Bangladešas');
INSERT INTO "country" ("id", "name") VALUES ('BB', 'Barbadosas');
INSERT INTO "country" ("id", "name") VALUES ('BE', 'Belgija');
INSERT INTO "country" ("id", "name") VALUES ('BZ', 'Belizas');
INSERT INTO "country" ("id", "name") VALUES ('BJ', 'Beninas');
INSERT INTO "country" ("id", "name") VALUES ('BM', 'Bermuda');
INSERT INTO "country" ("id", "name") VALUES ('GW', 'Bisau Gvinėja');
INSERT INTO "country" ("id", "name") VALUES ('BO', 'Bolivija');
INSERT INTO "country" ("id", "name") VALUES ('BA', 'Bosnija ir Hercegovina');
INSERT INTO "country" ("id", "name") VALUES ('BW', 'Botsvana');
INSERT INTO "country" ("id", "name") VALUES ('BV', 'Bouvet sala');
INSERT INTO "country" ("id", "name") VALUES ('BR', 'Brazilija');
INSERT INTO "country" ("id", "name") VALUES ('BN', 'Brunėjus');
INSERT INTO "country" ("id", "name") VALUES ('BG', 'Bulgarija');
INSERT INTO "country" ("id", "name") VALUES ('BF', 'Burkina Fasas');
INSERT INTO "country" ("id", "name") VALUES ('BI', 'Burundis');
INSERT INTO "country" ("id", "name") VALUES ('BT', 'Butanas');
INSERT INTO "country" ("id", "name") VALUES ('CF', 'Centrinės Afrikos Respublika');
INSERT INTO "country" ("id", "name") VALUES ('EA', 'Ceuta ir Melilla');
INSERT INTO "country" ("id", "name") VALUES ('CP', 'Clipperton sala');
INSERT INTO "country" ("id", "name") VALUES ('TD', 'Čadas');
INSERT INTO "country" ("id", "name") VALUES ('CZ', 'Čekija');
INSERT INTO "country" ("id", "name") VALUES ('CL', 'Čilė');
INSERT INTO "country" ("id", "name") VALUES ('DK', 'Danija');
INSERT INTO "country" ("id", "name") VALUES ('GB', 'Didžioji Britanija');
INSERT INTO "country" ("id", "name") VALUES ('VG', 'Didžiosios Britanijos Mergelių salos');
INSERT INTO "country" ("id", "name") VALUES ('DG', 'Diego Garcia');
INSERT INTO "country" ("id", "name") VALUES ('DM', 'Dominika');
INSERT INTO "country" ("id", "name") VALUES ('DO', 'Dominikos Respublika');
INSERT INTO "country" ("id", "name") VALUES ('CI', 'Dramblio Kaulo Krantas');
INSERT INTO "country" ("id", "name") VALUES ('JE', 'Džersis');
INSERT INTO "country" ("id", "name") VALUES ('DJ', 'Džibutis');
INSERT INTO "country" ("id", "name") VALUES ('EG', 'Egiptas');
INSERT INTO "country" ("id", "name") VALUES ('EC', 'Ekvadoras');
INSERT INTO "country" ("id", "name") VALUES ('ER', 'Eritrėja');
INSERT INTO "country" ("id", "name") VALUES ('EE', 'Estija');
INSERT INTO "country" ("id", "name") VALUES ('ET', 'Etiopija');
INSERT INTO "country" ("id", "name") VALUES ('EU', 'Europos Sąjunga');
INSERT INTO "country" ("id", "name") VALUES ('FK', 'Falklando salos');
INSERT INTO "country" ("id", "name") VALUES ('FO', 'Farerų salos');
INSERT INTO "country" ("id", "name") VALUES ('FJ', 'Fidžis');
INSERT INTO "country" ("id", "name") VALUES ('PH', 'Filipinai');
INSERT INTO "country" ("id", "name") VALUES ('GA', 'Gabonas');
INSERT INTO "country" ("id", "name") VALUES ('GY', 'Gajana');
INSERT INTO "country" ("id", "name") VALUES ('GM', 'Gambija');
INSERT INTO "country" ("id", "name") VALUES ('GH', 'Gana');
INSERT INTO "country" ("id", "name") VALUES ('GI', 'Gibraltaras');
INSERT INTO "country" ("id", "name") VALUES ('GR', 'Graikija');
INSERT INTO "country" ("id", "name") VALUES ('GD', 'Grenada');
INSERT INTO "country" ("id", "name") VALUES ('GL', 'Grenlandija');
INSERT INTO "country" ("id", "name") VALUES ('GE', 'Gruzija');
INSERT INTO "country" ("id", "name") VALUES ('GU', 'Guamas');
INSERT INTO "country" ("id", "name") VALUES ('GG', 'Guernsis');
INSERT INTO "country" ("id", "name") VALUES ('GP', 'Gvadelupė');
INSERT INTO "country" ("id", "name") VALUES ('GT', 'Gvatemala');
INSERT INTO "country" ("id", "name") VALUES ('GN', 'Gvinėja');
INSERT INTO "country" ("id", "name") VALUES ('HT', 'Haitis');
INSERT INTO "country" ("id", "name") VALUES ('HM', 'Heardo ir McDonaldo Salų Sritis');
INSERT INTO "country" ("id", "name") VALUES ('HN', 'Hondūras');
INSERT INTO "country" ("id", "name") VALUES ('IN', 'Indija');
INSERT INTO "country" ("id", "name") VALUES ('IO', 'Indijos vandenyno britų sritis');
INSERT INTO "country" ("id", "name") VALUES ('ID', 'Indonezija');
INSERT INTO "country" ("id", "name") VALUES ('IQ', 'Irakas');
INSERT INTO "country" ("id", "name") VALUES ('IR', 'Iranas');
INSERT INTO "country" ("id", "name") VALUES ('IS', 'Islandija');
INSERT INTO "country" ("id", "name") VALUES ('ES', 'Ispanija');
INSERT INTO "country" ("id", "name") VALUES ('IT', 'Italija');
INSERT INTO "country" ("id", "name") VALUES ('IL', 'Izraelis');
INSERT INTO "country" ("id", "name") VALUES ('JM', 'Jamaika');
INSERT INTO "country" ("id", "name") VALUES ('JP', 'Japonija');
INSERT INTO "country" ("id", "name") VALUES ('YE', 'Jemenas');
INSERT INTO "country" ("id", "name") VALUES ('JO', 'Jordanija');
INSERT INTO "country" ("id", "name") VALUES ('US', 'Jungtinės Valstijos');
INSERT INTO "country" ("id", "name") VALUES ('AE', 'Jungtiniai Arabų Emyratai');
INSERT INTO "country" ("id", "name") VALUES ('UM', 'Jungtinių Valstijų mažosios aplinkinės salos');
INSERT INTO "country" ("id", "name") VALUES ('ME', 'Juodkalnija');
INSERT INTO "country" ("id", "name") VALUES ('KY', 'Kaimanų salos');
INSERT INTO "country" ("id", "name") VALUES ('CX', 'Kalėdų sala');
INSERT INTO "country" ("id", "name") VALUES ('KH', 'Kambodža');
INSERT INTO "country" ("id", "name") VALUES ('CM', 'Kamerūnas');
INSERT INTO "country" ("id", "name") VALUES ('CA', 'Kanada');
INSERT INTO "country" ("id", "name") VALUES ('IC', 'Kanarų salos');
INSERT INTO "country" ("id", "name") VALUES ('QA', 'Kataras');
INSERT INTO "country" ("id", "name") VALUES ('KZ', 'Kazachstanas');
INSERT INTO "country" ("id", "name") VALUES ('KE', 'Kenija');
INSERT INTO "country" ("id", "name") VALUES ('CN', 'Kinija');
INSERT INTO "country" ("id", "name") VALUES ('HK', 'Kinijos S. A. R. Honkongas');
INSERT INTO "country" ("id", "name") VALUES ('CY', 'Kipras');
INSERT INTO "country" ("id", "name") VALUES ('KG', 'Kirgiztanas');
INSERT INTO "country" ("id", "name") VALUES ('KI', 'Kiribatis');
INSERT INTO "country" ("id", "name") VALUES ('CC', 'Kokosų salos');
INSERT INTO "country" ("id", "name") VALUES ('CO', 'Kolumbija');
INSERT INTO "country" ("id", "name") VALUES ('KM', 'Komorai');
INSERT INTO "country" ("id", "name") VALUES ('CG', 'Kongas');
INSERT INTO "country" ("id", "name") VALUES ('CD', 'Kongo Demokratinė Respublika');
INSERT INTO "country" ("id", "name") VALUES ('CR', 'Kosta Rika');
INSERT INTO "country" ("id", "name") VALUES ('HR', 'Kroatija');
INSERT INTO "country" ("id", "name") VALUES ('CU', 'Kuba');
INSERT INTO "country" ("id", "name") VALUES ('CK', 'Kuko salos');
INSERT INTO "country" ("id", "name") VALUES ('KW', 'Kuveitas');
INSERT INTO "country" ("id", "name") VALUES ('LA', 'Laosas');
INSERT INTO "country" ("id", "name") VALUES ('LV', 'Latvija');
INSERT INTO "country" ("id", "name") VALUES ('PL', 'Lenkija');
INSERT INTO "country" ("id", "name") VALUES ('LS', 'Lesotas');
INSERT INTO "country" ("id", "name") VALUES ('LB', 'Libanas');
INSERT INTO "country" ("id", "name") VALUES ('LR', 'Liberija');
INSERT INTO "country" ("id", "name") VALUES ('LY', 'Libija');
INSERT INTO "country" ("id", "name") VALUES ('LI', 'Lichtenšteinas');
INSERT INTO "country" ("id", "name") VALUES ('LT', 'Lietuva');
INSERT INTO "country" ("id", "name") VALUES ('LU', 'Liuksemburgas');
INSERT INTO "country" ("id", "name") VALUES ('MO', 'Macao');
INSERT INTO "country" ("id", "name") VALUES ('MG', 'Madagaskaras');
INSERT INTO "country" ("id", "name") VALUES ('YT', 'Mayotte'as');
INSERT INTO "country" ("id", "name") VALUES ('MK', 'Makedonija');
INSERT INTO "country" ("id", "name") VALUES ('MY', 'Malaizija');
INSERT INTO "country" ("id", "name") VALUES ('MW', 'Malavis');
INSERT INTO "country" ("id", "name") VALUES ('MV', 'Maldivai');
INSERT INTO "country" ("id", "name") VALUES ('ML', 'Malis');
INSERT INTO "country" ("id", "name") VALUES ('MT', 'Malta');
INSERT INTO "country" ("id", "name") VALUES ('MP', 'Marianos šiaurinės salos');
INSERT INTO "country" ("id", "name") VALUES ('MA', 'Marokas');
INSERT INTO "country" ("id", "name") VALUES ('MH', 'Maršalo Salos');
INSERT INTO "country" ("id", "name") VALUES ('MQ', 'Martinika');
INSERT INTO "country" ("id", "name") VALUES ('MU', 'Mauricijus');
INSERT INTO "country" ("id", "name") VALUES ('MR', 'Mauritanija');
INSERT INTO "country" ("id", "name") VALUES ('IM', 'Meino sala');
INSERT INTO "country" ("id", "name") VALUES ('MX', 'Meksika');
INSERT INTO "country" ("id", "name") VALUES ('VI', 'Mergelių salos (JAV)');
INSERT INTO "country" ("id", "name") VALUES ('MM', 'Mianmaras');
INSERT INTO "country" ("id", "name") VALUES ('FM', 'Mikronezija');
INSERT INTO "country" ("id", "name") VALUES ('MD', 'Moldova');
INSERT INTO "country" ("id", "name") VALUES ('MC', 'Monakas');
INSERT INTO "country" ("id", "name") VALUES ('MN', 'Mongolija');
INSERT INTO "country" ("id", "name") VALUES ('MS', 'Montserratas');
INSERT INTO "country" ("id", "name") VALUES ('MZ', 'Mozambikas');
INSERT INTO "country" ("id", "name") VALUES ('NA', 'Namibija');
INSERT INTO "country" ("id", "name") VALUES ('NC', 'Naujoji Kaledonija');
INSERT INTO "country" ("id", "name") VALUES ('NZ', 'Naujoji Zelandija');
INSERT INTO "country" ("id", "name") VALUES ('NR', 'Nauru');
INSERT INTO "country" ("id", "name") VALUES ('NP', 'Nepalas');
INSERT INTO "country" ("id", "name") VALUES ('NL', 'Nyderlandai');
INSERT INTO "country" ("id", "name") VALUES ('NG', 'Nigerija');
INSERT INTO "country" ("id", "name") VALUES ('NE', 'Nigeris');
INSERT INTO "country" ("id", "name") VALUES ('NI', 'Nikaragva');
INSERT INTO "country" ("id", "name") VALUES ('NU', 'Niue');
INSERT INTO "country" ("id", "name") VALUES ('NF', 'Norfolko sala');
INSERT INTO "country" ("id", "name") VALUES ('NO', 'Norvegija');
INSERT INTO "country" ("id", "name") VALUES ('QO', 'Nuošali Okeanija');
INSERT INTO "country" ("id", "name") VALUES ('AN', 'Olandijos Antilai');
INSERT INTO "country" ("id", "name") VALUES ('OM', 'Omanas');
INSERT INTO "country" ("id", "name") VALUES ('PK', 'Pakistanas');
INSERT INTO "country" ("id", "name") VALUES ('PW', 'Palau');
INSERT INTO "country" ("id", "name") VALUES ('PS', 'Palestinos teritorija');
INSERT INTO "country" ("id", "name") VALUES ('PA', 'Panama');
INSERT INTO "country" ("id", "name") VALUES ('PG', 'Papua Naujoji Gvinėja');
INSERT INTO "country" ("id", "name") VALUES ('PY', 'Paragvajus');
INSERT INTO "country" ("id", "name") VALUES ('PE', 'Peru');
INSERT INTO "country" ("id", "name") VALUES ('ZA', 'Pietų Afrika');
INSERT INTO "country" ("id", "name") VALUES ('GS', 'Pietų Džordžija ir Pietų Sandvičo salos');
INSERT INTO "country" ("id", "name") VALUES ('KR', 'Pietų Korėja');
INSERT INTO "country" ("id", "name") VALUES ('PN', 'Pitkernas');
INSERT INTO "country" ("id", "name") VALUES ('PT', 'Portugalija');
INSERT INTO "country" ("id", "name") VALUES ('FR', 'Prancūzija');
INSERT INTO "country" ("id", "name") VALUES ('GF', 'Prancūzijos Gviana');
INSERT INTO "country" ("id", "name") VALUES ('TF', 'Prancūzijos Pietų sritys');
INSERT INTO "country" ("id", "name") VALUES ('PF', 'Prancūzų Polinezija');
INSERT INTO "country" ("id", "name") VALUES ('PR', 'Puerto Rikas');
INSERT INTO "country" ("id", "name") VALUES ('GQ', 'Pusiaujo Gvinėja');
INSERT INTO "country" ("id", "name") VALUES ('RE', 'Reunionas');
INSERT INTO "country" ("id", "name") VALUES ('TL', 'Rytų Timoras');
INSERT INTO "country" ("id", "name") VALUES ('RW', 'Ruanda');
INSERT INTO "country" ("id", "name") VALUES ('RO', 'Rumunija');
INSERT INTO "country" ("id", "name") VALUES ('RU', 'Rusijos Federacija');
INSERT INTO "country" ("id", "name") VALUES ('MF', 'Saint-Martin');
INSERT INTO "country" ("id", "name") VALUES ('SB', 'Saliamono salos');
INSERT INTO "country" ("id", "name") VALUES ('SV', 'Salvadoras');
INSERT INTO "country" ("id", "name") VALUES ('WS', 'Samoa');
INSERT INTO "country" ("id", "name") VALUES ('SM', 'San Marinas');
INSERT INTO "country" ("id", "name") VALUES ('ST', 'San Tomė ir Principė');
INSERT INTO "country" ("id", "name") VALUES ('SA', 'Saudo Arabija');
INSERT INTO "country" ("id", "name") VALUES ('SC', 'Seišeliai');
INSERT INTO "country" ("id", "name") VALUES ('PM', 'Sen Pjeras ir Mikelonas');
INSERT INTO "country" ("id", "name") VALUES ('SN', 'Senegalas');
INSERT INTO "country" ("id", "name") VALUES ('KN', 'Sent Kitsas ir Nevis');
INSERT INTO "country" ("id", "name") VALUES ('RS', 'Serbija');
INSERT INTO "country" ("id", "name") VALUES ('CS', 'Serbija ir Juodkalnija');
INSERT INTO "country" ("id", "name") VALUES ('SL', 'Siera Leonė');
INSERT INTO "country" ("id", "name") VALUES ('SG', 'Singapūras');
INSERT INTO "country" ("id", "name") VALUES ('SY', 'Sirija');
INSERT INTO "country" ("id", "name") VALUES ('SK', 'Slovakija');
INSERT INTO "country" ("id", "name") VALUES ('SI', 'Slovėnija');
INSERT INTO "country" ("id", "name") VALUES ('SO', 'Somalis');
INSERT INTO "country" ("id", "name") VALUES ('SD', 'Sudanas');
INSERT INTO "country" ("id", "name") VALUES ('FI', 'Suomija');
INSERT INTO "country" ("id", "name") VALUES ('SR', 'Surinamas');
INSERT INTO "country" ("id", "name") VALUES ('SJ', 'Svalbardo ir Jan Majen salos');
INSERT INTO "country" ("id", "name") VALUES ('SZ', 'Svazilendas');
INSERT INTO "country" ("id", "name") VALUES ('KP', 'Šiaurės Korėja');
INSERT INTO "country" ("id", "name") VALUES ('LK', 'Šri Lanka');
INSERT INTO "country" ("id", "name") VALUES ('SE', 'Švedija');
INSERT INTO "country" ("id", "name") VALUES ('CH', 'Šveicarija');
INSERT INTO "country" ("id", "name") VALUES ('VC', 'Šventasis Vincentas ir Grenadinai');
INSERT INTO "country" ("id", "name") VALUES ('BL', 'Švento Baltramiejaus sala');
INSERT INTO "country" ("id", "name") VALUES ('SH', 'Šventoji Elena');
INSERT INTO "country" ("id", "name") VALUES ('LC', 'Šventoji Liucija');
INSERT INTO "country" ("id", "name") VALUES ('TJ', 'Tadžikistanas');
INSERT INTO "country" ("id", "name") VALUES ('TH', 'Tailandas');
INSERT INTO "country" ("id", "name") VALUES ('TW', 'Taivanas');
INSERT INTO "country" ("id", "name") VALUES ('TZ', 'Tanzanija');
INSERT INTO "country" ("id", "name") VALUES ('TG', 'Togas');
INSERT INTO "country" ("id", "name") VALUES ('TK', 'Tokelau');
INSERT INTO "country" ("id", "name") VALUES ('TO', 'Tonga');
INSERT INTO "country" ("id", "name") VALUES ('TT', 'Trinidadas ir Tobagas');
INSERT INTO "country" ("id", "name") VALUES ('TA', 'Tristan da Cunha');
INSERT INTO "country" ("id", "name") VALUES ('TN', 'Tunisas');
INSERT INTO "country" ("id", "name") VALUES ('TR', 'Turkija');
INSERT INTO "country" ("id", "name") VALUES ('TM', 'Turkmėnistanas');
INSERT INTO "country" ("id", "name") VALUES ('TC', 'Turkso ir Caicoso salos');
INSERT INTO "country" ("id", "name") VALUES ('TV', 'Tuvalu');
INSERT INTO "country" ("id", "name") VALUES ('UG', 'Uganda');
INSERT INTO "country" ("id", "name") VALUES ('UA', 'Ukraina');
INSERT INTO "country" ("id", "name") VALUES ('UY', 'Urugvajus');
INSERT INTO "country" ("id", "name") VALUES ('UZ', 'Uzbekistanas');
INSERT INTO "country" ("id", "name") VALUES ('EH', 'Vakarų Sachara');
INSERT INTO "country" ("id", "name") VALUES ('VU', 'Vanuatu');
INSERT INTO "country" ("id", "name") VALUES ('VA', 'Vatikanas');
INSERT INTO "country" ("id", "name") VALUES ('VE', 'Venesuela');
INSERT INTO "country" ("id", "name") VALUES ('HU', 'Vengrija');
INSERT INTO "country" ("id", "name") VALUES ('VN', 'Vietnamas');
INSERT INTO "country" ("id", "name") VALUES ('DE', 'Vokietija');
INSERT INTO "country" ("id", "name") VALUES ('WF', 'Wallisas ir Futuna');
INSERT INTO "country" ("id", "name") VALUES ('ZM', 'Zambija');
INSERT INTO "country" ("id", "name") VALUES ('ZW', 'Zimbabvė');
INSERT INTO "country" ("id", "name") VALUES ('CV', 'Žaliasis Kyšulys');


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/2048games.iml" filepath="$PROJECT_DIR$/2048games.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
    </modules>
  </component>
</project>


text:
import jobs
import logging
import datetime
from outbuffer import PageBuffer
from wiki import *
from fidoc import FIdoc

class PageLog(PageBuffer):
	def __init__(self, wiki, page):
		PageBuffer.__init__(self, wiki, page)
		self.current = ""

	def write(self, text):
		lines = text.split('\n')
		self.current += lines[0]
		if len(lines) == 1:
			return

		for l in lines[1:-1]:
			PageBuffer.write(self, l)

		PageBuffer.write(self, self.current)
		self.current = lines[-1]

	def flush(self):
		PageBuffer.write(self, self.current)
		self.current = ""
		PageBuffer.flush(self)

def loadjobfile(jobfile):
	logging.info("Loading job file %s ..." % jobfile)

	try:
		import json
		with open(jobfile, 'r') as cf:
			jobdata = json.load(cf)
		return jobdata
	except Exception as e:
		logging.error("Unable to load job file - exception occurred!\n%s" % e)

	return None

def createjobs(jobdata):
	if jobdata is None:
		return []

	job_list = []
	f = jobs.JobFactory()

	for jname, jdata in jobdata["jobs"].items():
		# print(jname)
		# print(jdata)
		if jname == "inactive":
			continue

		if specificjobs is not None:
			if jname.lower() not in specificjobs:
				continue

		j = f.create_job(jdata["job"], jdata["params"])

		if j is None:
			logging.error("Unable to queue job '%s'." % jname)
			continue

		job_list.append(j)

	return job_list

def executejobs(fidoc, jobs, jobsuccess = None):
	overallsuccess = True
	n = len(jobs)

	for i, j in enumerate(jobs):
		p = i+1
		logging.info("JOB %d of %d: %s" % (p, n, j.summary()))

		if not j.required():
			logging.info("Skipped!")
			continue

		try:

			try:
				success = j.perform(fidoc)
			except Exception as e:
				logging.fatal("Exception occured!\n%s" % e)

		except logging.FatalError:
			success = False

		if jobsuccess is not None:
			jobsuccess[j] = success

		overallsuccess &= success

		if not success:
			logging.error("JOB %d of %d: Aborted!" % (p, n))
			person = j.responsible(fidoc)
			if person is not None:
				logging.info("Notify %s about failed JOB %d" % (person, p))

def broadcastfailedjobs(failedjobs, fidoc):
	import notification

	# notifier = notification.MetaNotifier(dw, ':ficontent:private:meta:')
	# notifier = notification.UserFileNotifier(wikiconfig.userfile)

	subject = 'Job failed: %s'
	message = '\n'.join([
		'Hello %s,'
		'',
		'your Job "%s" has failed during last execution.',
		'Please refer to the log at %s for errors and fix them as soon as possible.' % jobslog,
		'',
		'If you got stuck, please contact Stefan (stefan.lemme@dfki.de) or Dirk (dirk.krause@pixelpark.de).',
		'',
		'Best,'
		'\tdokuwikibot'
	])

	for fj in failedJobs:
		person = fj.responsible(fidoc)
		if person is None:
			person = 'DFKI-Stefan'
		summary = fj.summary()
		# notifier.notify(
			# person,
			# subject % summary,
			# message % (person, summary)
		# )

if __name__ == "__main__":
	import sys
	import wikiconfig

	if len(sys.argv) > 1:
		jobdata = loadjobfile(sys.argv[1])

	# print(jobdata)
	if len(sys.argv) > 2:
		specificjobs = [job.lower() for job in sys.argv[2:]]
	else:
		specificjobs = None

	if jobdata is not None:
		jobslog = jobdata["log"]
	else:
		jobslog = None

	jobs = createjobs(jobdata)

	dw = DokuWikiRemote(wikiconfig.url, wikiconfig.user, wikiconfig.passwd)
	log = PageLog(dw, jobslog)
	logging.out = log
	logging.cliplines = False

	log << dw.heading(1, "Log of dokuwikibot's jobs")
	log << "\n"
	log << "Latest run at %s" % datetime.datetime.now()
	log << "\n"
	log << "<code>"

	logging.info("Connected to remote DokuWiki at %s" % wikiconfig.url)

	fidoc = FIdoc(dw)

	jobsuccess = {}

	try:
		overallsuccess = executejobs(fidoc, jobs, jobsuccess)
	except Exception as e:
		logging.error("Exception occured!\n%s" % e)
		overallsuccess = False

	logging.info("All done.")

	log << "\n"
	log << "</code>"
	log << "\n"

	log.flush()

	if not overallsuccess:
		failedJobs = [j for j in jobs if not ((j in jobsuccess) and (jobsuccess[j]))]
		print(failedJobs)
		broadcastfailedjobs(failedJobs, fidoc)


text:
<?php

// метки для вычисление производительности
define('STARTTIME',microtime());
define('STARTMEMORY',memory_get_usage());
define('STARTPEAKMEMORY',0);

// объяление системных констант
define('D',DIRECTORY_SEPARATOR); // файловый разделитель
define('SD','.'.D); // положение текущего файла относительно корневой папки на сервере, папка указывается в конфиге web сервера
define('AP',dirname(__FILE__).D); // абсолютный путь к текущей папке
define('CHAR','UTF-8'); // название кодировки, которая используется по умолчанию
define('ENGINE','engine-server'); // папка с серверной частью frameworka
define('CENGINE','engine-client'); // папка с клиентской частью frameworka
define('APP','applications'); // папка с приложениями(экшенами)
define('SYSTEM','system'); // папка в которой хранится какая либо системная информация
define('PRJ','projects'); // PRJ - переменная тек проэкта
// константа, содержит или определяет по каким либо параметрам название текущего проекта
define('PROJECT',isset($_GET['PRJ'])?$_GET['PRJ']:'project1'); unset($_GET['PRJ']);

error_reporting(E_ALL);// уровень отображения ошибок

require_once(AP.SD.ENGINE.D.'class.Prototype.php');
require_once(AP.SD.ENGINE.D.'abstract.Object.php');
require_once(AP.SD.ENGINE.D.'class.Autoloader.php');

$obj = new Prototype(array(// важен порядок
    'settings'=>null,
    'autoloader'=>null,
    'error'=>null,
    'request'=>array('input'=>null,'output'=>null,'actions'=>null,'cctrl'=>null)
));

$obj['settings'] = require(AP.SD.PRJ.D.PROJECT.D.'configs.php');// путь к файлу с конфигом!!!

// пути жесткие!!! Между путями и классами есть зависимости
$obj['autoloader'] = new Autoloader($obj);// !!!жестко привязаны к пути
$obj['error'] = new Handling($obj);// !!!жестко привязаны к пути

try {

    $obj['request']['input'] = new Input($obj,array('get'=>$_GET));
    $obj['request']['input']->clean();
    $obj['request']['output'] = new OutputBrowser($obj);
    $obj['request']['actions'] = new Actions($obj);
    $obj['request']['cctrl'] = new CController($obj);

    $obj['request']['cctrl']['engine-client'] = CENGINE;

    $obj['request']['cctrl']->checkDep();
    $obj['request']['cctrl']->request();

    $obj['request']['output']->setFragment($obj['request']['cctrl']->__toString());
    $obj['request']['output']->getsHeader();
    $obj['request']['output']->getsBody();

} catch(ErrorException $e) {
    $obj['error']->handlerror($e);
}

//$fs = new FileSystem($obj);
//$fs->remove('./temp');

?>


text:
import logging
import datetime

from dateutil.parser import parse
from rdr_service.clock import CLOCK
from rdr_service.app_util import nonprod
from rdr_service.storage import GoogleCloudStorageCSVReader
from rdr_service.dao.retention_eligible_metrics_dao import RetentionEligibleMetricsDao
from rdr_service.dao.participant_summary_dao import ParticipantSummaryDao
from rdr_service.model.retention_eligible_metrics import RetentionEligibleMetrics
from rdr_service.participant_enums import RetentionType, RetentionStatus

_BATCH_SIZE = 1000

# Note: depreciated to switch to using GoogleCloudStorageCSVReader version.
# def import_retention_eligible_metrics_file(task_data):
#     """
#     Import PTSC retention eligible metric file from bucket.
#     :param task_data: Cloud function event dict.
#     """
#     csv_file_cloud_path = task_data["file_path"]
#     upload_date = task_data["upload_date"]
#     dao = RetentionEligibleMetricsDao()
#
#     # Copy bucket file to local temp file.
#     logging.info(f"Opening gs://{csv_file_cloud_path}.")
#     tmp_file = tempfile.NamedTemporaryFile(prefix='ptsc_')
#     with GoogleCloudStorageProvider().open(csv_file_cloud_path, 'rt') as csv_file:
#         while True:
#             chunk = csv_file.read(_CHUNK_SIZE)
#             tmp_file.write(chunk)
#             if not chunk or len(chunk) < _CHUNK_SIZE:
#                 break
#     tmp_file.seek(0)
#
#     header = tmp_file.readline().decode('utf-8')
#     missing_cols = set(RetentionEligibleMetricCsvColumns.ALL) - set(header.split(','))
#     if missing_cols:
#         raise DataError(f"CSV is missing columns {missing_cols}, had columns {header}.")
#
#     strio = io.StringIO()
#     strio.write(header + '\n')
#     batch_count = upsert_count = 0
#     records = list()
#
#     with dao.session() as session:
#         while True:
#             # Create a mini-csv file with a _BATCH_SIZE number of records in the StringIO obj.
#             line = tmp_file.readline().decode('utf-8')
#             if line:
#                 strio.write(line + '\n')
#                 batch_count += 1
#
#             if batch_count == _BATCH_SIZE or not line:
#                 strio.seek(0)
#                 csv_reader = csv.DictReader(strio, delimiter=",")
#                 for row in csv_reader:
#                     if not row[RetentionEligibleMetricCsvColumns.PARTICIPANT_ID]:
#                         continue
#                     record = _create_retention_eligible_metrics_obj_from_row(row, upload_date)
#                     records.append(record)
#                 upsert_count += dao.upsert_all_with_session(session, records)
#                 if not line:
#                     break
#                 # reset for next batch, re-use objects.
#                 batch_count = 0
#                 records.clear()
#                 strio.seek(0)
#                 strio.truncate(0)
#                 strio.write(header + '\n')
#
#     tmp_file.close()
#
#     logging.info(f"Updating participant summary retention eligible flags for {upsert_count} participants...")
#     ParticipantSummaryDao().bulk_update_retention_eligible_flags(upload_date)
#     logging.info(f"Import and update completed for gs://{csv_file_cloud_path}")

def import_retention_eligible_metrics_file(task_data):
    """
    Import PTSC retention eligible metric file from bucket.
    :param task_data: Cloud function event dict.
    """
    csv_file_cloud_path = task_data["file_path"]
    upload_date = task_data["upload_date"]
    dao = RetentionEligibleMetricsDao()

    # Copy bucket file to local temp file.
    logging.info(f"Reading gs://{csv_file_cloud_path}.")
    csv_reader = GoogleCloudStorageCSVReader(csv_file_cloud_path)

    batch_count = upsert_count = 0
    records = list()
    with dao.session() as session:
        for row in csv_reader:
            if not row[RetentionEligibleMetricCsvColumns.PARTICIPANT_ID]:
                continue
            record = _create_retention_eligible_metrics_obj_from_row(row, upload_date)
            records.append(record)
            batch_count += 1

            if batch_count == _BATCH_SIZE:
                upsert_count += dao.upsert_all_with_session(session, records)
                records.clear()
                batch_count = 0

        if records:
            upsert_count += dao.upsert_all_with_session(session, records)

    logging.info(f"Updating participant summary retention eligible flags for {upsert_count} participants...")
    ParticipantSummaryDao().bulk_update_retention_eligible_flags(upload_date)
    logging.info(f"Import and update completed for gs://{csv_file_cloud_path}")

@nonprod
def calculate_retention_eligible_metrics():
    # Calculate retention eligible metrics
    # This method is for lower env only, Prod env will import from file use above method
    retention_window = datetime.timedelta(days=547)
    eighteen_month_ago = CLOCK.now() - retention_window
    eighteen_month_ago_str = eighteen_month_ago.strftime('%Y-%m-%d %H:%M:%S')
    update_sql = """
        UPDATE participant_summary
        SET retention_eligible_status =
        CASE WHEN
            consent_for_study_enrollment = 1
            AND (consent_for_electronic_health_records = 1 OR consent_for_dv_electronic_health_records_sharing = 1)
            AND questionnaire_on_the_basics = 1
            AND questionnaire_on_overall_health = 1
            AND questionnaire_on_lifestyle = 1
            AND withdrawal_status = 1
            AND suspension_status = 1
            AND samples_to_isolate_dna = 1
            THEN 2 ELSE 1
        END,
        retention_eligible_time =
        CASE WHEN
            consent_for_study_enrollment = 1
            AND (consent_for_electronic_health_records = 1 OR consent_for_dv_electronic_health_records_sharing = 1)
            AND questionnaire_on_the_basics = 1
            AND questionnaire_on_overall_health = 1
            AND questionnaire_on_lifestyle = 1
            AND withdrawal_status = 1
            AND suspension_status = 1
            AND samples_to_isolate_dna = 1
            AND
              COALESCE(sample_status_1ed10_time, sample_status_2ed10_time, sample_status_1ed04_time,
                     sample_status_1sal_time, sample_status_1sal2_time, 0) != 0
            THEN GREATEST(
                GREATEST (consent_for_study_enrollment_authored,
                 questionnaire_on_the_basics_authored,
                 questionnaire_on_overall_health_authored,
                 questionnaire_on_lifestyle_authored,
                 COALESCE(consent_for_electronic_health_records_authored, consent_for_study_enrollment_authored),
                 COALESCE(consent_for_dv_electronic_health_records_sharing_authored, consent_for_study_enrollment_authored)
                ),
                LEAST(COALESCE(sample_status_1ed10_time, '9999-01-01'),
                    COALESCE(sample_status_2ed10_time, '9999-01-01'),
                    COALESCE(sample_status_1ed04_time, '9999-01-01'),
                    COALESCE(sample_status_1sal_time, '9999-01-01'),
                    COALESCE(sample_status_1sal2_time, '9999-01-01')
                )
            )
            ELSE NULL
        END,
        retention_type =
        CASE WHEN
            consent_for_study_enrollment = 1
            AND (consent_for_electronic_health_records = 1 OR consent_for_dv_electronic_health_records_sharing = 1)
            AND questionnaire_on_the_basics = 1
            AND questionnaire_on_overall_health = 1
            AND questionnaire_on_lifestyle = 1
            AND withdrawal_status = 1
            AND suspension_status = 1
            AND samples_to_isolate_dna = 1
            AND (
                    (questionnaire_on_healthcare_access_authored is not null and
                     questionnaire_on_healthcare_access_authored > '{eighteen_month_ago}') or
                    (questionnaire_on_family_health_authored is not null and
                     questionnaire_on_family_health_authored > '{eighteen_month_ago}') or
                    (questionnaire_on_medical_history_authored is not null and
                     questionnaire_on_medical_history_authored > '{eighteen_month_ago}') or
                    (questionnaire_on_cope_nov_authored is not null
                        and questionnaire_on_cope_nov_authored > '{eighteen_month_ago}') or
                    (questionnaire_on_cope_july_authored is not null
                        and questionnaire_on_cope_july_authored > '{eighteen_month_ago}') or
                    (questionnaire_on_cope_june_authored is not null
                        and questionnaire_on_cope_june_authored > '{eighteen_month_ago}') or
                    (questionnaire_on_cope_dec_authored is not null
                        and questionnaire_on_cope_dec_authored > '{eighteen_month_ago}') or
                    (questionnaire_on_cope_may_authored is not null
                        and questionnaire_on_cope_may_authored > '{eighteen_month_ago}') or
                    (questionnaire_on_cope_feb_authored is not null
                        and questionnaire_on_cope_feb_authored > '{eighteen_month_ago}') or
                    (consent_cohort = 1 and consent_for_study_enrollment_authored !=
                                            participant_summary.consent_for_study_enrollment_first_yes_authored and
                     consent_for_study_enrollment_authored > '{eighteen_month_ago}') or
                    (consent_cohort = 1 and consent_for_genomics_ror_authored is not null and
                     consent_for_genomics_ror_authored > '{eighteen_month_ago}') or
                    (consent_cohort = 2 and consent_for_genomics_ror_authored is not null and
                     consent_for_genomics_ror_authored > '{eighteen_month_ago}')
                )
            AND ehr_update_time is not null and ehr_update_time>'{eighteen_month_ago}'
            THEN 3
            WHEN
            consent_for_study_enrollment = 1
            AND (consent_for_electronic_health_records = 1 OR consent_for_dv_electronic_health_records_sharing = 1)
            AND questionnaire_on_the_basics = 1
            AND questionnaire_on_overall_health = 1
            AND questionnaire_on_lifestyle = 1
            AND withdrawal_status = 1
            AND suspension_status = 1
            AND samples_to_isolate_dna = 1
            AND (
                    (questionnaire_on_healthcare_access_authored is not null and
                     questionnaire_on_healthcare_access_authored > '{eighteen_month_ago}') or
                    (questionnaire_on_family_health_authored is not null and
                     questionnaire_on_family_health_authored > '{eighteen_month_ago}') or
                    (questionnaire_on_medical_history_authored is not null and
                     questionnaire_on_medical_history_authored > '{eighteen_month_ago}') or
                    (questionnaire_on_cope_nov_authored is not null
                        and questionnaire_on_cope_nov_authored > '{eighteen_month_ago}') or
                    (questionnaire_on_cope_july_authored is not null
                        and questionnaire_on_cope_july_authored > '{eighteen_month_ago}') or
                    (questionnaire_on_cope_june_authored is not null
                        and questionnaire_on_cope_june_authored > '{eighteen_month_ago}') or
                    (questionnaire_on_cope_dec_authored is not null
                        and questionnaire_on_cope_dec_authored > '{eighteen_month_ago}') or
                    (questionnaire_on_cope_may_authored is not null
                        and questionnaire_on_cope_may_authored > '{eighteen_month_ago}') or
                    (questionnaire_on_cope_feb_authored is not null
                        and questionnaire_on_cope_feb_authored > '{eighteen_month_ago}') or
                    (consent_cohort = 1 and consent_for_study_enrollment_authored !=
                                            participant_summary.consent_for_study_enrollment_first_yes_authored and
                     consent_for_study_enrollment_authored > '{eighteen_month_ago}') or
                    (consent_cohort = 1 and consent_for_genomics_ror_authored is not null and
                     consent_for_genomics_ror_authored > '{eighteen_month_ago}') or
                    (consent_cohort = 2 and consent_for_genomics_ror_authored is not null and
                     consent_for_genomics_ror_authored > '{eighteen_month_ago}')
                )
            THEN 1
            WHEN
            consent_for_study_enrollment = 1
            AND (consent_for_electronic_health_records = 1 OR consent_for_dv_electronic_health_records_sharing = 1)
            AND questionnaire_on_the_basics = 1
            AND questionnaire_on_overall_health = 1
            AND questionnaire_on_lifestyle = 1
            AND withdrawal_status = 1
            AND suspension_status = 1
            AND samples_to_isolate_dna = 1
            THEN 2
            ELSE 0
        END
        WHERE 1=1
    """.format(eighteen_month_ago=eighteen_month_ago_str)

    dao = ParticipantSummaryDao()
    with dao.session() as session:
        session.execute(update_sql)

def _parse_field(parser_func, field_str):
    return parser_func(field_str) if field_str not in ('', 'NULL') else None

def _create_retention_eligible_metrics_obj_from_row(row, upload_date):
    retention_eligible = _parse_field(int, row[RetentionEligibleMetricCsvColumns.RETENTION_ELIGIBLE])
    eligible_time = _parse_field(parse, row[RetentionEligibleMetricCsvColumns.RETENTION_ELIGIBLE_TIME])
    last_active_eligible_activity_time = _parse_field(parse, row[RetentionEligibleMetricCsvColumns
                                                      .LAST_ACTIVE_RETENTION_ACTIVITY_TIME])
    actively_retained = _parse_field(int, row[RetentionEligibleMetricCsvColumns.ACTIVELY_RETAINED])
    passively_retained = _parse_field(int, row[RetentionEligibleMetricCsvColumns.PASSIVELY_RETAINED])

    retention_type = RetentionType.UNSET
    if actively_retained and passively_retained:
        retention_type = RetentionType.ACTIVE_AND_PASSIVE
    elif actively_retained:
        retention_type = RetentionType.ACTIVE
    elif passively_retained:
        retention_type = RetentionType.PASSIVE

    return RetentionEligibleMetrics(
        participantId=row[RetentionEligibleMetricCsvColumns.PARTICIPANT_ID],
        retentionEligible=retention_eligible,
        retentionEligibleTime=eligible_time,
        lastActiveRetentionActivityTime=last_active_eligible_activity_time,
        activelyRetained=actively_retained,
        passivelyRetained=passively_retained,
        fileUploadDate=upload_date,
        retentionEligibleStatus=RetentionStatus.ELIGIBLE if retention_eligible else RetentionStatus.NOT_ELIGIBLE,
        retentionType=retention_type
    )

class RetentionEligibleMetricCsvColumns(object):
    PARTICIPANT_ID = "participant_id"
    RETENTION_ELIGIBLE = "retention_eligible"
    RETENTION_ELIGIBLE_TIME = "retention_eligible_date"
    LAST_ACTIVE_RETENTION_ACTIVITY_TIME = "last_active_retention_activity_date"
    ACTIVELY_RETAINED = "actively_retained"
    PASSIVELY_RETAINED = "passively_retained"

    ALL = (PARTICIPANT_ID, RETENTION_ELIGIBLE, RETENTION_ELIGIBLE_TIME, LAST_ACTIVE_RETENTION_ACTIVITY_TIME,
           ACTIVELY_RETAINED, PASSIVELY_RETAINED)

class DataError(RuntimeError):
    def __init__(self, msg, external=False):
        super(DataError, self).__init__(msg)
        self.external = external