text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package erp.mhrs.data;

import erp.data.SDataConstants;
import erp.lib.SLibConstants;
import erp.lib.SLibUtilities;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author Sergio Flores
 */
public class SDataFormerPayrollEmp extends erp.lib.data.SDataRegistry implements java.io.Serializable {

    protected int mnPkPayrollId;
    protected int mnPkEmployeeId;
    protected java.lang.String msEmployee;
    protected java.lang.String msDepartment;
    protected java.lang.String msDepartmentKey;
    protected java.lang.String msEmployeeCategory;
    protected java.lang.String msEmployeeType;
    protected java.lang.String msSalaryType;
    protected double mdDebit;
    protected double mdCredit;
    protected double mdSalary;
    protected double mdDaysNotWorked;
    protected double mdDaysWorked;
    protected double mdDaysPayed;
    protected java.lang.String msNumberSeries;
    protected int mnNumber;
    protected boolean mbIsDeleted;
    protected int mnFkBizPartnerId_n;
    protected int mnFkPaymentSystemTypeId;
    protected int mnFkYearId;
    protected int mnFkPeriodId;
    protected int mnFkBookkeepingCenterId;
    protected java.lang.String msFkRecordTypeId;
    protected int mnFkNumberId;

    private void computeNumber(java.sql.Connection connection) throws SQLException, Exception {
        String sql = "";
        ResultSet resultSet = null;

        mnNumber = 0;

        sql = "SELECT COALESCE(MAX(num), 0) + 1 AS f_num FROM hrs_sie_pay_emp WHERE num_ser = '" + msNumberSeries + "' AND b_del = 0 ";

        resultSet = connection.createStatement().executeQuery(sql);
        if (resultSet.next()) {
            mnNumber = resultSet.getInt("f_num");
        }
    }

    public SDataFormerPayrollEmp() {
        super(SDataConstants.HRS_SIE_PAY_EMP);
        reset();
    }

    public void setPkPayrollId(int n) { mnPkPayrollId = n; }
    public void setPkEmployeeId(int n) { mnPkEmployeeId = n; }
    public void setEmployee(java.lang.String s) { msEmployee = s; }
    public void setDepartment(java.lang.String s) { msDepartment = s; }
    public void setDepartmentKey(java.lang.String s) { msDepartmentKey = s; }
    public void setEmployeeCategory(java.lang.String s) { msEmployeeCategory = s; }
    public void setEmployeeType(java.lang.String s) { msEmployeeType = s; }
    public void setSalaryType(java.lang.String s) { msSalaryType = s; }
    public void setDebit(double d) { mdDebit = d; }
    public void setCredit(double d) { mdCredit = d; }
    public void setSalary(double d) { mdSalary = d; }
    public void setDaysNotWorked(double d) { mdDaysNotWorked = d; }
    public void setDaysWorked(double d) { mdDaysWorked = d; }
    public void setDaysPayed(double d) { mdDaysPayed = d; }
    public void setNumberSeries(java.lang.String s) { msNumberSeries = s; }
    public void setNumber(int n) { mnNumber = n; }
    public void setIsDeleted(boolean b) { mbIsDeleted = b; }
    public void setFkBizPartnerId_n(int n) { mnFkBizPartnerId_n = n; }
    public void setFkPaymentSystemTypeId(int n) { mnFkPaymentSystemTypeId = n; }
    public void setFkYearId(int n) { mnFkYearId = n; }
    public void setFkPeriodId(int n) { mnFkPeriodId = n; }
    public void setFkBookkeepingCenterId(int n) { mnFkBookkeepingCenterId = n; }
    public void setFkRecordTypeId(java.lang.String s) { msFkRecordTypeId = s; }
    public void setFkNumberId(int n) { mnFkNumberId = n; }

    public int getPkPayrollId() { return mnPkPayrollId; }
    public int getPkEmployeeId() { return mnPkEmployeeId; }
    public java.lang.String getEmployee() { return msEmployee; }
    public java.lang.String getDepartment() { return msDepartment; }
    public java.lang.String getDepartmentKey() { return msDepartmentKey; }
    public java.lang.String getEmployeeCategory() { return msEmployeeCategory; }
    public java.lang.String getEmployeeType() { return msEmployeeType; }
    public java.lang.String getSalaryType() { return msSalaryType; }
    public double getDebit() { return mdDebit; }
    public double getCredit() { return mdCredit; }
    public double getSalary() { return mdSalary; }
    public double getDaysNotWorked() { return mdDaysNotWorked; }
    public double getDaysWorked() { return mdDaysWorked; }
    public double getDaysPayed() { return mdDaysPayed; }
    public java.lang.String getNumberSeries() { return msNumberSeries; }
    public int getNumber() { return mnNumber; }
    public boolean getIsDeleted() { return mbIsDeleted; }
    public int getFkBizPartnerId_n() { return mnFkBizPartnerId_n; }
    public int getFkPaymentSystemTypeId() { return mnFkPaymentSystemTypeId; }
    public int getFkYearId() { return mnFkYearId; }
    public int getFkPeriodId() { return mnFkPeriodId; }
    public int getFkBookkeepingCenterId() { return mnFkBookkeepingCenterId; }
    public java.lang.String getFkRecordTypeId() { return msFkRecordTypeId; }
    public int getFkNumberId() { return mnFkNumberId; }

    public java.lang.String getFormerPayrollEmpNumber() {
        return (msNumberSeries.isEmpty() ? "" : msNumberSeries + "-") + mnNumber;
    }

    @Override
    public void setPrimaryKey(java.lang.Object pk) {
        mnPkPayrollId = ((int[]) pk)[0];
        mnPkEmployeeId = ((int[]) pk)[1];
    }

    @Override
    public java.lang.Object getPrimaryKey() {
        return new int[] { mnPkPayrollId, mnPkEmployeeId };
    }

    @Override
    public void reset() {
        super.resetRegistry();

        mnPkPayrollId = 0;
        mnPkEmployeeId = 0;
        msEmployee = "";
        msDepartment = "";
        msDepartmentKey = "";
        msEmployeeCategory = "";
        msEmployeeType = "";
        msSalaryType = "";
        mdDebit = 0;
        mdCredit = 0;
        mdSalary = 0;
        mdDaysNotWorked = 0;
        mdDaysWorked = 0;
        mdDaysPayed = 0;
        msNumberSeries = "";
        mnNumber = 0;
        mbIsDeleted = false;
        mnFkBizPartnerId_n = 0;
        mnFkPaymentSystemTypeId = 0;
        mnFkYearId = 0;
        mnFkPeriodId = 0;
        mnFkBookkeepingCenterId = 0;
        msFkRecordTypeId = "";
        mnFkNumberId = 0;
    }

    @Override
    public int read(java.lang.Object pk, java.sql.Statement statement) {
        int[] key = (int[]) pk;
        String sql;
        ResultSet resultSet = null;

        mnLastDbActionResult = SLibConstants.UNDEFINED;
        reset();

        try {
            sql = "SELECT * FROM hrs_sie_pay_emp WHERE id_pay = " + key[0] + " AND id_emp = " + key[1] + " ";
            resultSet = statement.executeQuery(sql);
            if (!resultSet.next()) {
                throw new Exception(SLibConstants.MSG_ERR_REG_FOUND_NOT);
            }
            else {
                mnPkPayrollId = resultSet.getInt("id_pay");
                mnPkEmployeeId = resultSet.getInt("id_emp");
                msEmployee = resultSet.getString("emp");
                msDepartment = resultSet.getString("dep");
                msDepartmentKey = resultSet.getString("dep_key");
                msEmployeeCategory = resultSet.getString("emp_cat");
                msEmployeeType = resultSet.getString("emp_tp");
                msSalaryType = resultSet.getString("sal_tp");
                mdDebit = resultSet.getDouble("debit");
                mdCredit = resultSet.getDouble("credit");
                mdSalary = resultSet.getDouble("sal");
                mdDaysNotWorked = resultSet.getDouble("day_not_wkd");
                mdDaysWorked = resultSet.getDouble("day_wkd");
                mdDaysPayed = resultSet.getDouble("day_pay");
                msNumberSeries = resultSet.getString("num_ser");
                mnNumber = resultSet.getInt("num");
                mbIsDeleted = resultSet.getBoolean("b_del");
                mnFkBizPartnerId_n = resultSet.getInt("fid_bpr_n");
                mnFkPaymentSystemTypeId = resultSet.getInt("fid_tp_pay_sys");
                mnFkYearId = resultSet.getInt("fid_year");
                mnFkPeriodId = resultSet.getInt("fid_per");
                mnFkBookkeepingCenterId = resultSet.getInt("fid_bkc");
                msFkRecordTypeId = resultSet.getString("fid_tp_rec");
                mnFkNumberId = resultSet.getInt("fid_num");

                mbIsRegistryNew = false;
                mnLastDbActionResult = SLibConstants.DB_ACTION_READ_OK;
            }
        }
        catch (java.sql.SQLException e) {
            mnLastDbActionResult = SLibConstants.DB_ACTION_READ_ERROR;
            SLibUtilities.printOutException(this, e);
        }
        catch (java.lang.Exception e) {
            mnLastDbActionResult = SLibConstants.DB_ACTION_READ_ERROR;
            SLibUtilities.printOutException(this, e);
        }

        return mnLastDbActionResult;
    }

    @Override
    public int save(java.sql.Connection connection) {
        int nParam = 1;
        CallableStatement callableStatement = null;

        mnLastDbActionResult = SLibConstants.UNDEFINED;

        try {
            computeNumber(connection);

            callableStatement = connection.prepareCall(
                    "{ CALL hrs_sie_pay_emp_save(" +
                    "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
                    "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
                    "?, ?, ?, ?, ?, ?) }");
            callableStatement.setInt(nParam++, mnPkPayrollId);
            callableStatement.setInt(nParam++, mnPkEmployeeId);
            callableStatement.setString(nParam++, msEmployee);
            callableStatement.setString(nParam++, msDepartment);
            callableStatement.setString(nParam++, msDepartmentKey);
            callableStatement.setString(nParam++, msEmployeeCategory);
            callableStatement.setString(nParam++, msEmployeeType);
            callableStatement.setString(nParam++, msSalaryType);
            callableStatement.setDouble(nParam++, mdDebit);
            callableStatement.setDouble(nParam++, mdCredit);
            callableStatement.setDouble(nParam++, mdSalary);
            callableStatement.setDouble(nParam++, mdDaysNotWorked);
            callableStatement.setDouble(nParam++, mdDaysWorked);
            callableStatement.setDouble(nParam++, mdDaysPayed);
            callableStatement.setString(nParam++, msNumberSeries);
            callableStatement.setInt(nParam++, mnNumber);
            callableStatement.setBoolean(nParam++, mbIsDeleted);
            callableStatement.setInt(nParam++, mnFkBizPartnerId_n);
            callableStatement.setInt(nParam++, mnFkPaymentSystemTypeId);
            callableStatement.setInt(nParam++, mnFkYearId);
            callableStatement.setInt(nParam++, mnFkPeriodId);
            callableStatement.setInt(nParam++, mnFkBookkeepingCenterId);
            callableStatement.setString(nParam++, msFkRecordTypeId);
            callableStatement.setInt(nParam++, mnFkNumberId);
            callableStatement.registerOutParameter(nParam++, java.sql.Types.SMALLINT);
            callableStatement.registerOutParameter(nParam++, java.sql.Types.VARCHAR);
            callableStatement.execute();

            mnDbmsErrorId = callableStatement.getInt(nParam - 2);
            msDbmsError = callableStatement.getString(nParam - 1);

            if (mnDbmsErrorId != 0) {
                throw new Exception(msDbmsError);
            }
            else {
                mbIsRegistryNew = false;
                mnLastDbActionResult = SLibConstants.DB_ACTION_SAVE_OK;
            }
        }
        catch (java.lang.Exception e) {
            mnLastDbActionResult = SLibConstants.DB_ACTION_SAVE_ERROR;
            SLibUtilities.printOutException(this, e);
        }

        return mnLastDbActionResult;
    }

    @Override
    public java.util.Date getLastDbUpdate() {
        return null;
    }
}


text:
require 'formula'

class RosHydroRosconsole < Formula
  homepage 'http://www.ros.org/wiki/rosconsole'
  url 'https://github.com/ros-gbp/ros_comm-release.git', :tag => 'release/hydro/rosconsole/1.10.2-0'
  version '1.10.2-0'

  # source repos often contain more than one package... not sure if we can handle this
  #head 'https://github.com/ros-gbp/ros_comm-release.git', :branch => 'hydro-devel'

  # FIXEM: these are build depends
  depends_on "boost"
  depends_on "log4cxx"
  depends_on "ros-hydro-catkin"
  depends_on "ros-hydro-cpp-common"
  depends_on "ros-hydro-rostime"
  depends_on "ros-hydro-rosunit"

  depends_on "log4cxx"
  depends_on "ros-hydro-cpp-common"
  depends_on "ros-hydro-rosbuild"
  depends_on "ros-hydro-rostime"

  option 'with-debug-info', "Build with debug info."

  def install
    args = std_cmake_args
    args.delete '-DCMAKE_BUILD_TYPE=None'
    args.delete_if {|s| s.match(/^-DCMAKE_INSTALL_PREFIX/) }
    args << "-DCMAKE_INSTALL_PREFIX=#{prefix}"
    if build.with? "debug-info"
      args << '-DCMAKE_BUILD_TYPE=RelWithDebInfo'
    else
      args << '-DCMAKE_BUILD_TYPE=Release'
    end
    args << '-DCATKIN_BUILD_BINARY_PACKAGE=1'

    system 'if [ -f "/usr/local/setup.sh" ]; then . "/usr/local/setup.sh"; fi && cmake . ' + args.join(" ") + " && make install"
  end
end

redpajama_set_name: RedPajamaGithub


text:
Create games in Python2.7

###Requirements

1. python2.7 `$ sudo apt-get install python2`
2. Idle `$ sudo apt-get install idle`
3. pygame `$ sudo apt-get install pygame`

#HowTo

1. Download the game repository whatever you want to play as zip file.
2. unzip it and go to unzipped folder
3. then run `python2 *.py` where * denotes main python source code.
4. Enjoy !!!!

Source : [here](http://inventwithpython.com/chapter20.html)


text:
package com.android.example.text.styling.parser;

import androidx.annotation.NonNull;

import java.util.List;

/**
 * Simple markdown parsing of text.
 * Contains a list of markdown {@link Element}s
 */
public class TextMarkdown {

    @NonNull
    private final List<Element> elements;

    public TextMarkdown(@NonNull final List<Element> elements) {
        this.elements = elements;
    }

    @NonNull
    public List<Element> getElements() {
        return elements;
    }
}


text:
unsigned int pnSeed[] =
{
    0x12345678
};

class CMainParams : public CChainParams {
public:
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        pchMessageStart[0] = 0xf5;
        pchMessageStart[1] = 0xb2;
        pchMessageStart[2] = 0x53;
        pchMessageStart[3] = 0xde;
        vAlertPubKey = ParseHex("04f05802847840aaf295de8442fbacedf5b095cdbb9bc716bd49110271b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284");
        nDefaultPort = 3388;
        nRPCPort = 3385;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.

        const char* pszTimestamp = "Eaglecoin Genesis Block";
        CTransaction txNew;
        txNew.vin.resize(1);
        txNew.vout.resize(1);
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        txNew.vout[0].nValue = 200 * COIN;
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1435602888;
        genesis.nBits    = 0x1e0ffff0;
        genesis.nNonce   = 413889;

        //// debug print
        hashGenesisBlock = genesis.GetHash();

        genesis.print();

        assert(hashGenesisBlock == uint256("0x0000012b616687a5665b3f7b63ac1ff40bb139df9e0e86e6781c56426ad9b4c2"));
        assert(genesis.hashMerkleRoot == uint256("0x5e279c8d6d6238890afbf19ae8b96f66140a725efbb4a78b46ba0fa36be7375b"));

        vSeeds.push_back(CDNSSeedData("node.EagleCoin.org", "node.EagleCoin.org"));
        vSeeds.push_back(CDNSSeedData("node.EagleCoin.cf", "node.EagleCoin.cf"));
        vSeeds.push_back(CDNSSeedData("EagleCoin.no-ip.org", "EagleCoin.no-ip.org"));

        base58Prefixes[PUBKEY_ADDRESS] = 33;
        base58Prefixes[SCRIPT_ADDRESS] = 9;
        base58Prefixes[SECRET_KEY] = 224;

        // Convert the pnSeeds array into usable address objects.
        for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
        {
            // It'll only connect to one or two seed nodes because once it connects,
            // it'll get a pile of addresses with newer timestamps.
            // Seed nodes are given a random 'last seen time'
            const int64 nTwoDays = 2 * 24 * 60 * 60;
            struct in_addr ip;
            memcpy(&ip, &pnSeed[i], sizeof(ip));
            CAddress addr(CService(ip, GetDefaultPort()));
            addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays;
            vFixedSeeds.push_back(addr);
        }
    }

    virtual const CBlock& GenesisBlock() const { return genesis; }
    virtual Network NetworkID() const { return CChainParams::MAIN; }

    virtual const vector<CAddress>& FixedSeeds() const {
        return vFixedSeeds;
    }
protected:
    CBlock genesis;
    vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;

//
// Testnet (v3)
//
class CTestNetParams : public CMainParams {
public:
    CTestNetParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        pchMessageStart[0] = 0x05;
        pchMessageStart[1] = 0xfe;
        pchMessageStart[2] = 0xa9;
        pchMessageStart[3] = 0x01;
        vAlertPubKey = ParseHex("04303390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a");
        nDefaultPort = 11835;
        nRPCPort = 11832;
        strDataDir = "testnet";

        // Modify the testnet genesis block so the timestamp is valid for a later start.
        genesis.nTime = 1390747675;
        genesis.nNonce = 2091390249;

        //// debug print
        hashGenesisBlock = genesis.GetHash();

        printf("%s\n", hashGenesisBlock.ToString().c_str());
        printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
        genesis.print();

        assert(hashGenesisBlock == uint256("0x00000c7c73d8ce604178dae13f0fc6ec0be3275614366d44b1b4b5c6e238c60c"));

        vFixedSeeds.clear();
        vSeeds.clear();
        // vSeeds.push_back(CDNSSeedData("EagleCoin.test", "test.EagleCoin.org"));

        base58Prefixes[PUBKEY_ADDRESS] = 88;
        base58Prefixes[SCRIPT_ADDRESS] = 188;
        base58Prefixes[SECRET_KEY] = 239;

    }
    virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
//static CTestNetParams testNetParams;

//
// Regression test
//
class CRegTestParams : public CTestNetParams {
public:
    CRegTestParams() {
        pchMessageStart[0] = 0xfa;
        pchMessageStart[1] = 0x0f;
        pchMessageStart[2] = 0xa5;
        pchMessageStart[3] = 0x5a;
        nSubsidyHalvingInterval = 150;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);
        genesis.nTime = 1390748221;
        genesis.nBits = 0x207fffff;
        genesis.nNonce = 4;
        hashGenesisBlock = genesis.GetHash();
        nDefaultPort = 11444;
        strDataDir = "regtest";

        // debug print
        hashGenesisBlock = genesis.GetHash();

        printf("%s\n", hashGenesisBlock.ToString().c_str());
        printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
        genesis.print();

        assert(hashGenesisBlock == uint256("0x57939ce0a96bf42965fee5956528a456d0edfb879b8bd699bcbb4786d27b979d"));

        vSeeds.clear();  // Regtest mode doesn't have any DNS seeds.

        base58Prefixes[PUBKEY_ADDRESS] = 0;
        base58Prefixes[SCRIPT_ADDRESS] = 5;
        base58Prefixes[SECRET_KEY] = 128;
    }

    virtual bool RequireRPCPassword() const { return false; }
    virtual Network NetworkID() const { return CChainParams::REGTEST; }
};
//static CRegTestParams regTestParams;

static CChainParams *pCurrentParams = &mainParams;

const CChainParams &Params() {
    return *pCurrentParams;
}

void SelectParams(CChainParams::Network network) {
    switch (network) {
        case CChainParams::MAIN:
            pCurrentParams = &mainParams;
            break;
        //case CChainParams::TESTNET:
        //    pCurrentParams = &testNetParams;
        //    break;
        //case CChainParams::REGTEST:
        //    pCurrentParams = &regTestParams;
        //    break;
        default:
            assert(false && "Unimplemented network");
            return;
    }
}

bool SelectParamsFromCommandLine() {
    bool fRegTest = GetBoolArg("-regtest", false);
    bool fTestNet = GetBoolArg("-testnet", false);

    if (fTestNet && fRegTest) {
        return false;
    }

    if (fRegTest) {
        SelectParams(CChainParams::REGTEST);
    } else if (fTestNet) {
        SelectParams(CChainParams::TESTNET);
    } else {
        SelectParams(CChainParams::MAIN);
    }
    return true;
}


text: export const ALL_USERS = 'ALL_USERS';


text:
import { combineReducers } from 'redux';
import { COLORS, TYPES } from './Constants';
import { actionTypes } from './actions';
import { generateId } from './utils'

function generateTiles() {
  let tiles = {};
  COLORS.forEach((color) => {
    Object.keys(TYPES).forEach((type) => {
      let count = TYPES[type];
      for (let i=0; i<count; i+=1) {
        let id = generateId(color, type , i);
        tiles[id] = ({
          color: color,
          type: type,
          id: id
        });
      }
    });
  });

  return tiles;
}

const tilesReducer = (state, action) => {
  if (state === undefined) {
    state = generateTiles()
  }
  switch (action.type) {
    case actionTypes.MOVE_TILE:
      return Object.assign({}, state, {
        [action.tileId]: Object.assign({}, state[action.tileId], {
          x: action.x,
          y: action.y
        })
      });
    default:
      return state;
  }
};

const turnReducer = (state='white', action) => {
  switch (action.type) {
    case actionTypes.MOVE_TILE:
      return state === 'white' ? 'black' : 'white';
    default:
      return state;
  }
};

const moveCountReducer = (state=0, action) => {
  switch (action.type) {
    case actionTypes.MOVE_TILE:
      return state + 1;
    default:
      return state;
  }
};

const draggedTileIdReducer = (state=null, action) => {
  switch (action.type) {
    case actionTypes.BEGIN_DRAG:
      return action.tileId;
    case actionTypes.END_DRAG:
      return null;
    default:
      return state;
  }
};

const swarmReducer = combineReducers({
  tiles: tilesReducer,
  turn: turnReducer,
  moveCount: moveCountReducer,
  draggedTileId: draggedTileIdReducer
});

export default swarmReducer


text:
package com.nesting.maven2.db;

import java.io.*;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.zip.GZIPInputStream;

import org.apache.commons.io.ByteOrderMark;
import org.apache.commons.io.input.BOMInputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.settings.Server;
import org.apache.maven.settings.Settings;

/** Abstract mojo that all DB related mojos
 * inherit from. */
public abstract class AbstractDBMojo extends AbstractMojo {

  /** The database connection settings for
   * the application.
   * @parameter
   * @required */
  private DbConfig[] dbConfig;

  public DbConfig getDbConfig() { return currentDbConfig; }
  /** Currenent executed db config */
  private DbConfig currentDbConfig;

  /** The names of configs which is executed, if length = 0 or null then execute for all configs
   * the application.
   * @parameter */
  private String[] runConfigs;

  /** The batch size when executing batches.
   * @parameter default-value="20"
   * @required */
  private int batchSize;

  /** Whether or not to use SQL batches.
   * @parameter default-value="true"
   * @required */
  private boolean useBatch;

  /** The {@link Settings} object.
   * @parameter default-value="${settings}"
   * @required
   * @readonly */
  private Settings settings;

  /** Child mojos need to implement this.
   * @throws MojoExecutionException on error.
   * @throws MojoFailureException on error */
  public abstract void executeInternal() throws MojoExecutionException,  MojoFailureException;

  /** {@inheritDoc} */
  public final void execute() throws MojoExecutionException, MojoFailureException {
    Set<String> cfNames = new HashSet<>();
    if (runConfigs != null) { cfNames.addAll(Arrays.asList(runConfigs)); }
    for (DbConfig cf : dbConfig) {
      if (cfNames.isEmpty() || cfNames.contains(cf.getName())) {
        getLog().info("dbConfig: " + cf.getName());
        currentDbConfig = cf;
        checkDbSettings(cf.getAdminDbConnectionSettings(), "admin");
        checkDbSettings(cf.getAppDbConnectionSettings(), "application");
        executeInternal();
      }
    }
  }

  /** Checks the given database connection settings.
   * @param dbSettings the settings to check
   * @param name the name of the settings
   * @throws MojoExecutionException on error
   * @throws MojoFailureException on error */
  private void checkDbSettings(DatabaseConnectionSettings dbSettings, String name) throws MojoExecutionException, MojoFailureException {

    // check server
    if (!StringUtils.isEmpty(dbSettings.getServerId())) {
      Server server = settings.getServer(dbSettings.getServerId());
      if (server==null) {
        throw new MojoFailureException("["+name+"] Server ID: "
                                       +dbSettings.getServerId()+" not found!");
      } else if (StringUtils.isEmpty(server.getUsername())) {
        throw new MojoFailureException("["+name+"] Server ID: "+dbSettings.getServerId()+" found, "
                                       +"but username is empty!");
      }
      // check non server settings
    } else if (StringUtils.isEmpty(dbSettings.getUserName())) {
      throw new MojoFailureException("["+name+"] No username defined!");
    }

    // check url and jdbc driver
    if (StringUtils.isEmpty(dbSettings.getJdbcUrl())) {
      throw new MojoFailureException("["+name+"] No jdbc url defined!");
    } else if (StringUtils.isEmpty(dbSettings.getJdbcDriver())) {
      throw new MojoFailureException("["+name+"] No jdbc driver defined!");
    }
  }

  /** Executes all of the sql scripts in a given directory
   * using the given database connection.
   * @param directory the directory where the scripts reside
   * @param con the database connection
   * @throws SQLException on error
   * @throws MojoFailureException on error
   * @throws MojoExecutionException on error
   * @throws IOException on error */
  protected void executeScriptsInDirectory(File directory, Connection con)
    throws SQLException, MojoFailureException, MojoExecutionException, IOException {

    // talk a bit :)
    getLog().info("Executing scripts in: "+directory.getName());

    // make sure we can read it, and that it's
    // a file and not a directory
    if (!directory.isDirectory()) {
      throw new MojoFailureException(
                                     directory.getName()+" is not a directory");
    }

    // get all files in directory
    File[] files = directory.listFiles();

    // sort
    Arrays.sort(files, new Comparator() {
        public int compare(Object arg0, Object arg1) {
          return ((File)arg0).getName().compareTo(((File)arg1).getName());
        } }
      );

    // loop through all the files and execute them
    for (int i = 0; i<files.length; i++) {
      if (!files[i].isDirectory() && files[i].isFile() && !files[i].getName().endsWith("~")) {
        double startTime = System.currentTimeMillis();
        if (useBatch) {
          batchExecuteSqlScript(files[i], con);
        } else {
          executeSqlScript(files[i], con);
        }
        double endTime = System.currentTimeMillis();
        double elapsed = ((endTime-startTime)/1000.0);
        getLog().info(" script completed execution in "+elapsed+" second(s)");
      }
    }

  }

  private Reader inputStreamToReaderBOM(InputStream in) throws IOException {
    BOMInputStream bOMInputStream = new BOMInputStream(in, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE,
                                                       ByteOrderMark.UTF_32LE, ByteOrderMark.UTF_32BE);
    ByteOrderMark bom = bOMInputStream.getBOM();
    String charsetName = bom == null ? getDbConfig().getScriptEncoding() : bom.getCharsetName();
    return new InputStreamReader(new BufferedInputStream(bOMInputStream), charsetName);
  }

  /** Batch executes a script file.
   * @param file the file
   * @param con the connection
   * @throws SQLException on error
   * @throws MojoFailureException on error
   * @throws MojoExecutionException on error
   * @throws IOException on error */
  protected void batchExecuteSqlScript(File file, Connection con)
    throws SQLException, MojoFailureException, MojoExecutionException, IOException {
    // talk a bit :)
    getLog().info("batch executing script: "+file.getName());

    // make sure we can read it, and that it's
    // a file and not a directory
    if (!file.exists() || !file.canRead()
        || file.isDirectory() || !file.isFile()) {
      throw new MojoFailureException(file.getName()+" is not a file");
    }

    // open input stream to file
    InputStream ips = new FileInputStream(file);

    // if it's a compressed file (gzip) then unzip as
    // we read it in
    if (file.getName().toUpperCase().endsWith("GZ")) {
      ips = new GZIPInputStream(ips);
    }

    // check encoding
    checkEncoding();
    // our file reader
    Reader reader = inputStreamToReaderBOM(ips);
    // create SQL Statement
    Statement st = con.createStatement();

    StringBuilder sql = new StringBuilder();
    String line;
    BufferedReader in = new BufferedReader(reader);

    // loop through the statements
    int execCount = 0;
    List<String> sqlLines = new ArrayList<>();
    line = in.readLine();
    do {
      // append the line
      line = line == null ? getDbConfig().getTransactionDelimiter() : line;
      line.trim();
      if (getDbConfig().getTransactionDelimiter().toUpperCase().equals(line.toUpperCase())) {
        sqlLines.add(sql.toString());
        executeBatch(st, sqlLines);
        sql.delete(0, sql.length());
        sqlLines.clear();
        execCount++;
      } else {
        sql.append("\n").append(line);
        // if the line ends with the delimiter, then
        // lets execute it
        if (sql.toString().endsWith(getDbConfig().getSqlDelimiter())) {
          String sqlLine = sql.substring(0, sql.length() - getDbConfig().getSqlDelimiter().length());
          sqlLines.add(sqlLine);
          sql.replace(0, sql.length(), "");
          execCount++;
          if (sqlLines.size() >= batchSize) {
            executeBatch(st, sqlLines);
            sqlLines.clear();
          }
        }
      }
    } while ((line = in.readLine()) != null || sql.length() > 0);

    st.close();
    reader.close();
    in.close();

    getLog().info(" "+execCount+" statements batch executed from "+file.getName());
  }

  /** Executes the given sql script, using the given
   * connection.
   * @param file the file to execute
   * @param con the connection
   * @throws SQLException on error
   * @throws MojoFailureException on error
   * @throws MojoExecutionException on error
   * @throws IOException on error */
  protected void executeSqlScript(File file, Connection con)
    throws SQLException, MojoFailureException, MojoExecutionException, IOException {
    // talk a bit :)
    getLog().info("executing script: "+file.getName());
    // make sure we can read it, and that it's
    // a file and not a directory
    if (!file.exists() || !file.canRead() || file.isDirectory() || !file.isFile()) {
      throw new MojoFailureException(file.getName()+" is not a file");
    }

    // open input stream to file
    InputStream ips = new FileInputStream(file);

    // if it's a compressed file (gzip) then unzip as
    // we read it in
    if (file.getName().toUpperCase().endsWith("GZ")) {
      ips = new GZIPInputStream(ips);
      getLog().info(" file is gz compressed, using gzip stream");
    }

    // check encoding
    checkEncoding();

    // our file reader
    Reader reader = inputStreamToReaderBOM(ips);

    // create SQL Statement
    Statement st = con.createStatement();

    StringBuffer sql = new StringBuffer();
    String line;
    BufferedReader in = new BufferedReader(reader);

    // loop through the statements
    int execCount = 0;
    line = in.readLine();
    do {
      line = line == null ? getDbConfig().getTransactionDelimiter() : line;
      if (getDbConfig().getTransactionDelimiter().toUpperCase().equals(line.toUpperCase())) {
        executeStatement(st, sql.toString());
        sql.delete(0, sql.length());
        execCount++;
      } else {
        // append the line
        line.trim();
        sql.append("\n").append(line);
        // if the line ends with the delimiter, then
        // lets execute it
        if (sql.toString().endsWith(getDbConfig().getSqlDelimiter())) {
          String sqlLine = sql.substring(0, sql.length() - getDbConfig().getSqlDelimiter().length());
          executeStatement(st, sqlLine);
          sql.replace(0, sql.length(), "");
          execCount++;
        }
      }
    } while ((line = in.readLine()) != null || sql.length() > 0);

    st.close();
    reader.close();
    in.close();

    getLog().info(" "+execCount+" statements executed from "+file.getName());
  }

  /** Executes a batch update.
   * @param st the statement
   * @param sqlLines the sql lines
   * @throws SQLException on error */
  protected void executeBatch(Statement st, List<String> sqlLines) throws SQLException {
    for (Iterator<String> itt = sqlLines.iterator(); itt.hasNext(); ) {
      String str = itt.next();
      if (str == null || "".equals(str.trim())) { itt.remove(); }
    }
    if (getLog().isDebugEnabled()) {
      getLog().debug("Executing batch");
      getLog().debug(StringUtils.join(sqlLines, "\n"));
    }

    // add to batch
    for (int i=0; i<sqlLines.size(); i++) {
      st.addBatch((String) sqlLines.get(i));
    }

    int[] ret  = st.executeBatch();
    if (getLog().isDebugEnabled()) {
      getLog().debug("    "+ret.length+" statement(s) executed");
    }

    for (int i=0; i<ret.length; i++) {
      if (ret[i] == Statement.SUCCESS_NO_INFO && getLog().isDebugEnabled()) {
        getLog().debug("    statement " + i + " processed successfully without return results");
      } else if (ret[i] == Statement.EXECUTE_FAILED) {
        getLog().error("    error durring batch execution of statement: "+sqlLines.get(i));
        throw new SQLException("Error executing: "+ sqlLines.get(i));
      } else if (ret[i] >= 0 && getLog().isDebugEnabled()) {
        getLog().debug("    statement "+i+" processed successfully with "+ret[i]+" records effected");
      }
    }

  }

  /** Runs the given SQL statement.
   * @param st the statement to run it on
   * @param sqlLine the sql statement
   * @throws SQLException on error */
  protected void executeStatement(Statement st, String sqlLine) throws SQLException {
    if (getLog().isDebugEnabled()) {
      getLog().debug("    executing:\n"+sqlLine);
    }
    boolean execRet = false;
    try {
      execRet = st.execute(sqlLine);
    } catch(SQLException sqle) {
      SQLException se = new SQLException(sqle.getMessage() + "\n\nSQL:\n" + sqlLine,
                                         sqle.getSQLState(), sqle.getErrorCode());
      se.setNextException(sqle);
      throw se;
    }
    boolean loop = true;
    while (loop) {
      if (execRet) {
        getLog().warn(" statement returned a resultset");
      } else {
        // Got an update count
        int count = st.getUpdateCount();

        if (count == -1) {
          // Nothing left
          loop = false;
        } else if (getLog().isDebugEnabled()){
          // An update count was returned
          getLog().debug("    "+count+" row(s) updated");
        }
      }
      if (loop) {
        execRet = st.getMoreResults();
      }
    }
  }

  /** Returns a {@link Connection} to the application database.
   * @return the connection
   * @throws SQLException on error
   * @throws MojoFailureException on error */
  protected Connection openApplicationDbConnection() throws SQLException, MojoFailureException {
    return openConnection(getDbConfig().getAppDbConnectionSettings());
  }

  /** Returns a {@link Connection} to the application
   * database.
   * @return the connection
   * @throws SQLException on error
   * @throws MojoFailureException on error */
  protected Connection openAdminDbConnection() throws SQLException, MojoFailureException {
    return openConnection(getDbConfig().getAdminDbConnectionSettings());
  }

  /** Opens a connection using the given settings.
   * @param dbSettings the connection settings
   * @return the Connection
   * @throws SQLException on error
   * @throws MojoFailureException on error */
  private Connection openConnection(DatabaseConnectionSettings dbSettings)
    throws SQLException, MojoFailureException {

    String username = null;
    String password = null;

    // use settings to get authentication info for the given server
    if (!StringUtils.isEmpty(dbSettings.getServerId())) {
      Server server = settings.getServer(dbSettings.getServerId());
      username = server.getUsername();
      password = server.getPassword();
      // use settings in pom.xml
    } else {
      username = dbSettings.getUserName();
      password = dbSettings.getPassword();
    }

    // make sure the driver is good
    try {
      Class.forName(dbSettings.getJdbcDriver());
    } catch(Exception e) {
      throw new MojoFailureException(e.getMessage());
    }

    // consult the driver manager for the connection
    Connection con = DriverManager.getConnection(dbSettings.getJdbcUrl(), username, password);
    // we're good :)
    return con;
  }

  private void checkEncoding() {
    if (getDbConfig().getScriptEncoding() == null) {
      getDbConfig().setScriptEncoding(Charset.defaultCharset().name());
      getLog().warn("Using platform encoding (" + getDbConfig().getScriptEncoding() + ") for executing script, i.e. build is platform dependent!");
    } else {
      getLog().info(" setting encoding for executing script: " + getDbConfig().getScriptEncoding());
    }
  }
}


text:
<?php

namespace DesignPatterns\Behavioral\State;

/**
 * Class OrderInterface.
 */
interface OrderInterface
{
    /**
     * @return mixed
     */
    public function shipOrder();

    /**
     * @return mixed
     */
    public function completeOrder();
}


text:
package com.chaincloud.chaincloudv;

/**
 * Created by zhumingu on 16/6/20.
 */
public interface ConstantValue {

    boolean LOG_DEBUG = true;
}


text:
@(message: String)

@main("Frontoffice")(breadcrum(collection.immutable.HashMap("Accueil frontoffice" -> "/"))) {

@message

C'est ici que nous mettrons en place le frontoffice

En attendant, nous travaillons sur le backoffice pour la mise en place de l'API RESTFul:

    	Allez voir le backoffice

}


text:
package mcjty.theoneprobe.api;

import net.minecraft.util.math.Vec3d;

/**
 * Access information about where the probe hit the entity
 */
public interface IProbeHitEntityData {

    Vec3d getHitVec();
}


text:
FROM scratch

ENV WHOISD_LOCAL_HOST 0.0.0.0
ENV WHOISD_LOCAL_PORT 43
ENV WHOISD_LOG_LEVEL 0

EXPOSE $WHOISD_LOCAL_PORT

COPY examples/elastic/mapping.json /etc/whoisd/conf.d/
COPY bin/linux-amd64/whoisd /

CMD ["/whoisd"]


text:
package org.kie.workbench.common.services.refactoring.backend.server.query.findresourceparts;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import org.junit.Test;
import org.kie.workbench.common.services.refactoring.backend.server.BaseIndexingTest;
import org.kie.workbench.common.services.refactoring.backend.server.TestIndexer;
import org.kie.workbench.common.services.refactoring.backend.server.drl.TestDrlFileIndexer;
import org.kie.workbench.common.services.refactoring.backend.server.drl.TestDrlFileTypeDefinition;
import org.kie.workbench.common.services.refactoring.backend.server.query.NamedQuery;
import org.kie.workbench.common.services.refactoring.backend.server.query.response.DefaultResponseBuilder;
import org.kie.workbench.common.services.refactoring.backend.server.query.response.ResponseBuilder;
import org.kie.workbench.common.services.refactoring.backend.server.query.standard.FindResourcePartsQuery;
import org.kie.workbench.common.services.refactoring.model.index.terms.valueterms.ValueIndexTerm;
import org.kie.workbench.common.services.refactoring.model.index.terms.valueterms.ValuePartIndexTerm;
import org.kie.workbench.common.services.refactoring.model.index.terms.valueterms.ValueReferenceIndexTerm;
import org.kie.workbench.common.services.refactoring.model.query.RefactoringPageRequest;
import org.kie.workbench.common.services.refactoring.service.ResourceType;

import static org.junit.Assert.*;

public class FindResourcePartsQueryInvalidIndexTermsTest extends BaseIndexingTest<TestDrlFileTypeDefinition> {

    protected Set<NamedQuery> getQueries() {
        return new HashSet<NamedQuery>() {{
            add( new FindResourcePartsQuery() {
                @Override
                public ResponseBuilder getResponseBuilder() {
                    return new DefaultResponseBuilder( ioService() );
                }
            } );
        }};
    }

    @Test
    public void testFindResourcePartsQueryInvalidIndexTerms() throws IOException, InterruptedException {
        {
            final RefactoringPageRequest request = new RefactoringPageRequest( "FindResourcePartsQuery",
                                                                               new HashSet<ValueIndexTerm>(),
                                                                               0,
                                                                               -1 );

            try {
                service.query( request );
                fail();
            } catch ( IllegalArgumentException e ) {
                assertTrue( "Unexpected exception: " + e.getMessage(),
                        e.getMessage().startsWith("Expected '" + ValuePartIndexTerm.class.getSimpleName() + "' term was not found") );
                // and Swallow. Expected
            }
        }

        ValueIndexTerm ruleRefTerm = new ValueReferenceIndexTerm( "myRule", ResourceType.RULE );
        {
            final RefactoringPageRequest request = new RefactoringPageRequest( "FindResourcePartsQuery",
                                                                               new HashSet<ValueIndexTerm>() {{
                                                                                add( ruleRefTerm );
                                                                               }},
                                                                               0,
                                                                               -1 );

            try {
                service.query( request );
                fail();
            } catch ( IllegalArgumentException e ) {
                assertTrue( "Unexpected exception: " + e.getMessage(),
                        e.getMessage().startsWith( "Index term '" +  ruleRefTerm.getTerm() + "' can not be used with") );
                // and Swallow. Expected
            }
        }

        {
            final RefactoringPageRequest request = new RefactoringPageRequest( "FindResourcePartsQuery",
                                                                               new HashSet<ValueIndexTerm>() {{
                                                                                add( new ValueReferenceIndexTerm( "org.kie.workbench.common.services.refactoring.backend.server.drl.classes.Applicant", ResourceType.JAVA ) );
                                                                                add( ruleRefTerm );
                                                                               }},
                                                                               0,
                                                                               -1 );

            try {
                service.query( request );
                fail();
            } catch ( IllegalArgumentException e ) {
                assertTrue( "Unexpected exception: " + e.getMessage(),
                        e.getMessage().contains(" can not be used with the " + FindResourcePartsQuery.NAME) );
                // and Swallow. Expected
            }
        }

    }

    @Override
    protected TestIndexer getIndexer() {
        return new TestDrlFileIndexer();
    }

    @Override
    protected TestDrlFileTypeDefinition getResourceTypeDefinition() {
        return new TestDrlFileTypeDefinition();
    }

    @Override
    protected String getRepositoryName() {
        return testName.getMethodName();
    }

}


text:
"use strict";
var mt = require('marked_types');
var errh = require('ncbt').errh;
var ops = require('ops');
var AuthProblem = require('./auth_problem');

var AuthProvider = function (opt_options) {
	this.options = this.createOptions(opt_options);
	this.type = null;

	this.tokener = null;
	this.adapter = null;
	this.revoker = null;
};

AuthProvider.prototype.createOptions = function (opt_options) {
	return ops.cloneWithDefaults(opt_options, this.getDefaultOptions());
};

AuthProvider.prototype.getDefaultOptions = function () {
	var authMaxAge = 60 * 60 * 24 * 7 * 2 * 1000; // 2 weeks in ms
	return {
		maxAge: authMaxAge,
		useLimitedToken: true, // use limited token cookie CSRF protection (see README for details)
		renewalInterval: Math.round(authMaxAge / 2),

		allowedIssuedClockDeviation: 5 * 60 * 1000, // 5 minites in ms
	};
};

AuthProvider.prototype.setTokener = function (tokener) {
	this.tokener = tokener;
};

AuthProvider.prototype.setAdapter = function (adapter) {
	this.adapter = adapter;
};

AuthProvider.prototype.setRevoker = function (revoker) {
	this.revoker = revoker;
};

AuthProvider.prototype.login = function (res, identity, options, cb) {
	options = options || {};
	var identityStr = this.packIdentity(identity);
	var useCookies = !!options.useCookies;
	var isSessionLifetime = !!options.isSessionLifetime;

	var self = this;
	this.tokener.createToken(identityStr, {
		useLimitedToken: this.options.useLimitedToken,
		useCookies: useCookies,
		isSessionLifetime: isSessionLifetime
	}, errh(function (tokenInfo) {
		if (res != null) {
			self.adapter.applyAuthData(res, tokenInfo, self.getMaxAge(isSessionLifetime), useCookies);
		}
		cb(null, {
			identityStr: identityStr,
			tokenInfo: tokenInfo,
			result: self.prepareTokenResult(tokenInfo)
		});
	}, cb));
};

AuthProvider.prototype.auth = function (req, res, options, cb) {
	var authData = this.adapter.extractAuthData(req);
	this.authByData(authData, res, options, cb);
};

AuthProvider.prototype.authByData = function (authData, res, options, cb) {
	options = options || {};
	var allowUnprotected = !!options.allowUnprotected;
	// allowed values: null (auto), 'skip', 'force'
	var renewalMode = options.renewalMode || null;

	var self = this;
	var result = {
		authData: authData,
	};
	if (authData == null) {
		this.authProblem('NoAuthData', null, cb);
	}
	else if (!allowUnprotected && !authData.isCsrfProtected) {
		this.authProblem('CSRF', result, cb);
	}
	else {
		this.tokener.parseToken(authData.token, authData.additionalToken, errh(function (tokenData) {
			result.tokenData = tokenData;
			if (tokenData == null) {
				self.authProblem('InvalidToken', result, cb);
			}
			else if (!self.isValidIssued(tokenData)) {
				self.authProblem('InvalidIssued', result, cb);
			}
			else if (self.isExpired(tokenData)) {
				self.authProblem('Expired', result, cb);
			}
			else if (!self.isExpectedIdentity(tokenData, authData)) {
				self.authProblem('UnexpectedIdentity', result, cb);
			}
			else {
				self.checkRevoked(tokenData, errh(function (isRevoked) {
					if (isRevoked) {
						self.authProblem('Revoked', result, cb);
					}
					else if (renewalMode == 'force' || renewalMode != 'skip' && self.needRenew(tokenData)) {
						self.renew(res, tokenData, errh(function (renewalInfo) {
							result.renewalTokenInfo = renewalInfo.renewalTokenInfo;
							result.renewal = renewalInfo.renewal;
							self.prepareAuthResult(res, options, result, cb);
						}, cb));
					}
					else {
						self.prepareAuthResult(res, options, result, cb);
					}
				}, cb));
			}
		}, cb));
	}
};

AuthProvider.prototype.renew = function (res, tokenData, cb) {
	var self = this;
	this.tokener.renewToken(tokenData, self.options.useLimitedToken, errh(function (renewalTokenInfo) {
		if (res != null) {
			self.adapter.applyRenewal(res, renewalTokenInfo, self.getMaxAge(tokenData.isSessionLifetime), tokenData.useCookies);
		}
		cb(null, {
			renewalTokenInfo: renewalTokenInfo,
			renewal: self.prepareTokenResult(renewalTokenInfo, tokenData.isSessionLifetime)
		});
	}, cb));
};

AuthProvider.prototype.needRenew = function (tokenData) {
	// tokenData: as encoded to token by tokener
	return tokenData.issued + this.options.renewalInterval < Date.now();
};

AuthProvider.prototype.clearCookies = function (res) {
	this.adapter.clearCookies(res);
};

// deprecated and will be removed in next version, use marked types directly instead
AuthProvider.prototype.isAuthProblem = function (err) {
	return mt.is(err, AuthProblem);
};

// override

AuthProvider.prototype.packIdentity = function (identity) {
	return identity;
};

AuthProvider.prototype.unpackIdentity = function (identityStr) {
	return identityStr;
};

AuthProvider.prototype.authProblem = function (code, result, cb) {
	cb(new AuthProblem(code, result));
};

AuthProvider.prototype.prepareAuthResult = function (res, options, result, cb) {
	cb(null, {
		type: this.type,
		identity: this.getIdentity(result),
		authResult: result
	});
};

// internal

AuthProvider.prototype.getIdentity = function (result) {
	return this.unpackIdentity(result.tokenData.identityStr);
};

AuthProvider.prototype.prepareTokenResult = function (tokenInfo, opt_isSessionLifetime) {
	// tokenInfo: token, limitedToken, issued
	var isLimited = (tokenInfo.limitedToken != null);
	var result = {
		issued: tokenInfo.issued,
		token: isLimited ? tokenInfo.limitedToken : tokenInfo.token,
	};
	result.maxAge = this.getMaxAge();
	if (isLimited) {
		result.isLimited = true;
	}
	return result;
};

AuthProvider.prototype.getMaxAge = function (opt_isSessionLifetime) {
	return opt_isSessionLifetime ? null : this.options.maxAge;
};

AuthProvider.prototype.isValidIssued = function (tokenData) {
	return this.tokener.isValidIssued(tokenData.issued, this.options.allowedIssuedClockDeviation);
};

AuthProvider.prototype.isExpired = function (tokenData) {
	return this.tokener.isExpired(tokenData.issued, this.options.maxAge);
};

AuthProvider.prototype.isExpectedIdentity = function (tokenData, authData) {
	var result;
	if (authData.expectedIdentityStr == null) {
		result = true;
	}
	else {
		result = (tokenData.identityStr == authData.expectedIdentityStr);
	}
	return result;
};

AuthProvider.prototype.checkRevoked = function (tokenData, cb) {
	if (this.revoker != null) {
		this.revoker.checkRevoked(tokenData, cb);
	}
	else {
		cb(null, false);
	}
};

module.exports = AuthProvider;


text:
#ifndef MANCHESTER_H
#define MANCHESTER_H

/* Includes */
#include "stdint.h"
#include "stdio.h"

/* Types */
typedef uint8_t Manchester_Bit_t;

/* Constants */
static const Manchester_Bit_t Low   = 0U;
static const Manchester_Bit_t High  = 1U;
static const Manchester_Bit_t Undef = 2U;

/* Prototypes */
Manchester_Bit_t Manchester_Process_Edge( const Manchester_Bit_t clock,
                                          const Manchester_Bit_t data );

#endif /* MANCHESTER_H */


text:
<Alloy>
    <Collection src="teams"/>
    <Tab id="teamsTab" title="Teams" icon="KS_nav_views.png">
        <Window title="Teams">
            <ListView id='teamTable' defaultItemTemplate="teamItem" onItemclick="selectTeam">
                <Templates>
                    <ItemTemplate bindId="teamItem" name="teamItem" id="teamRow" height="60">
                        <ImageView bindId="leftImage" id="leftImage"/>
                        <View left="60" class="divider vertical"/>
                        <View class='center'>

                        </View>
                        <View right="60" class="divider vertical"/>
                        <ImageView bindId="rightImage" id="rightImage"/>
                    </ItemTemplate>
                </Templates>
                <SearchBar></SearchBar>

                <ListSection id="teamSection" dataCollection="teams">
                    <HeaderView>
                        <View layout='vertical' backgroundColor="#fff">
                            <View top="0" class="divider horizontal"/>
                            <View height="Ti.UI.SIZE">
                                Nation
                                Team
                            </View>
                            <View bottom="0" class="divider horizontal"/>
                        </View>
                    </HeaderView>
                    <ListItem
                    template="teamItem"
                    teamItem:id = "{id}"
                    leftImage:image="{TeamLogoPath}"
                    heading:text="{TeamName}"
                    subheading:text="{TeamType}"
                    rightImage:image="{TeamFlagPath}"
                    searchableText="{TeamName}"></ListItem>
                </ListSection>
            </ListView>
        </Window>
    </Tab>
</Alloy>


text:
package org.sleuthkit.autopsy.ingest;

import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
import org.openide.util.lookup.ServiceProvider;
import org.sleuthkit.autopsy.coreutils.ModuleSettings;
import org.sleuthkit.datamodel.Content;

@ServiceProvider(service = IngestConfigurator.class)
public class GeneralIngestConfigurator implements IngestConfigurator {

    public static final String ENABLED_INGEST_MODULES_KEY = "Enabled_Ingest_Modules";
    public static final String PARSE_UNALLOC_SPACE_KEY = "Process_Unallocated_Space";
    private List<Content> contentToIngest;
    private IngestManager manager;
    private IngestDialogPanel ingestDialogPanel;
    private String moduleContext;

    public GeneralIngestConfigurator() {
        this.moduleContext = IngestManager.MODULE_PROPERTIES;
        ingestDialogPanel = new IngestDialogPanel();
        ingestDialogPanel.setContext(moduleContext);
        manager = IngestManager.getDefault();
    }

    @Override
    public List<String> setContext(String context) {
        moduleContext = context;
        ingestDialogPanel.setContext(moduleContext);
        return loadSettingsForContext();
    }

    private List<String> loadSettingsForContext() {
        List<String> messages = new ArrayList<>();

        // If there is no enabled ingest modules setting for this user, default to enabling all
        // of the ingest modules the IngestManager has loaded.
        if (ModuleSettings.settingExists(moduleContext, ENABLED_INGEST_MODULES_KEY) == false) {
            String defaultSetting = moduleListToCsv(IngestManager.getDefault().enumerateAllModules());
            ModuleSettings.setConfigSetting(moduleContext, ENABLED_INGEST_MODULES_KEY, defaultSetting);
        }

        // Get the enabled ingest modules setting, check for missing modules, and pass the setting to
        // the UI component.
        List<IngestModuleAbstract> allModules = IngestManager.getDefault().enumerateAllModules();
        String[] enabledModuleNames = ModuleSettings.getConfigSetting(moduleContext, ENABLED_INGEST_MODULES_KEY).split(", ");
        List<IngestModuleAbstract> enabledModules = new ArrayList<>();
        for (String moduleName : enabledModuleNames) {
            // if no modules were enabled, we get an empty string in here
            if (moduleName.trim().equals("")) {
                continue;
            }
            // we renamed this module in 3.0.9 -> update it to prevent an error message
            if (moduleName.equals("Thunderbird Parser")) {
                moduleName = "MBox Parser";
            }

            IngestModuleAbstract moduleFound =  null;
            for (IngestModuleAbstract module : allModules) {
                if (moduleName.equals(module.getName())) {
                    moduleFound = module;
                    break;
                }
            }
            if (moduleFound != null) {
                enabledModules.add(moduleFound);
            }
            else {
                messages.add(moduleName + " was previously enabled, but could not be found");
            }
        }
        ingestDialogPanel.setEnabledIngestModules(enabledModules);

        // If there is no process unallocated space flag setting, default it to false.
        if (ModuleSettings.settingExists(moduleContext, PARSE_UNALLOC_SPACE_KEY) == false) {
            ModuleSettings.setConfigSetting(moduleContext, PARSE_UNALLOC_SPACE_KEY, "false");
        }

        // Get the process unallocated space flag setting and pass it to the UI component.
        boolean processUnalloc = Boolean.parseBoolean(ModuleSettings.getConfigSetting(moduleContext, PARSE_UNALLOC_SPACE_KEY));
        ingestDialogPanel.setProcessUnallocSpaceEnabled(processUnalloc);

        return messages;
    }

   @Override
    public JPanel getIngestConfigPanel() {
       // Note that this panel allows for selecting modules for the ingest process,
       // specifying the process unallocated space flag, and also specifying settings
       // for a selected ingest module.
       return ingestDialogPanel;
    }

    @Override
    public void save() {
        // Save the user's configuration of the set of enabled ingest modules.
        String enabledModulesCsvList = moduleListToCsv(ingestDialogPanel.getModulesToStart());
        ModuleSettings.setConfigSetting(moduleContext, ENABLED_INGEST_MODULES_KEY, enabledModulesCsvList);

        // Save the user's setting for the process unallocated space flag.
        String processUnalloc = Boolean.toString(ingestDialogPanel.processUnallocSpaceEnabled());
        ModuleSettings.setConfigSetting(moduleContext, PARSE_UNALLOC_SPACE_KEY, processUnalloc);

        // Save the user's configuration of the currently selected ingest module.
        IngestModuleAbstract currentModule = ingestDialogPanel.getCurrentIngestModule();
        if (currentModule != null && currentModule.hasSimpleConfiguration()) {
            currentModule.saveSimpleConfiguration();
        }
    }

    private static String moduleListToCsv(List<IngestModuleAbstract> lst) {
        if (lst == null || lst.isEmpty()) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < lst.size() - 1; ++i) {
            sb.append(lst.get(i).getName()).append(", ");
        }

        // and the last one
        sb.append(lst.get(lst.size() - 1).getName());

        return sb.toString();
    }

    @Override
    public void setContent(List<Content> inputContent) {
        this.contentToIngest = inputContent;
    }

    @Override
    public void start() {
        // Get the list of ingest modules selected by the user.
        List<IngestModuleAbstract> modulesToStart = ingestDialogPanel.getModulesToStart();

        // Get the user's selection of whether or not to process unallocated space.
        manager.setProcessUnallocSpace(ingestDialogPanel.processUnallocSpaceEnabled());

        if (!modulesToStart.isEmpty() && contentToIngest != null) {
            // Queue the ingest process.
            manager.execute(modulesToStart, contentToIngest);
        }
    }

    @Override
    public boolean isIngestRunning() {
        return manager.isIngestRunning();
    }
}


text:
<?php

namespace Back\BackBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class UserType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstname')
            ->add('lastname')
            ->add('username')
            ->add('email')
            ->add('enabled')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Back\BackBundle\Entity\User'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'back_backbundle_user';
    }
}


text:
from django.apps import AppConfig

from .helpers.admin import AppAdminHelper
from .helpers.discovery import AppDiscoveryHelper
from .helpers.migration import AppMigrationHelper
from .helpers.models import AppModelHelper

_REQUEST_STARTED_UID='ce23b028-1ac1-4e3d-b51a-55e9e6aa2399'

_is_initialized = False
admin_helper = AppAdminHelper()
discovery_helper = AppDiscoveryHelper()
migration_helper = AppMigrationHelper()
model_helper = AppModelHelper()

def _initialize(app_configs, messages):
    global _is_initialized
    global admin_helper
    global discovery_helper
    global model_helper

    if not _is_initialized:
        _is_initialized = True
        discovery_helper.discover_permission_models(app_configs, messages)
        model_helper.patch_existing_model_managers(app_configs, messages)
        admin_helper.patch_existing_inline_admin(app_configs, messages)

def _pre_migrate(app_config, **kwargs):
    global migration_helper

    migration_helper.suppress_auth_models(app_config, **kwargs)

def _post_migrate(app_config, **kwargs):
    global migration_helper

    if migration_helper.can_migrate(app_config, **kwargs):
        migration_helper.create_application_dynamic_privileges(app_config, **kwargs)
        migration_helper.create_application_dynamic_permissions(app_config, **kwargs)
        migration_helper.create_standard_objects(app_config, **kwargs)

def _request_started(sender, **kwargs):
    from django.apps import apps
    from django.core.signals import request_started
    from logging import getLogger

    request_started.disconnect(dispatch_uid=_REQUEST_STARTED_UID)

    app_configs = apps.get_app_configs()
    messages = []

    _initialize(app_configs, messages)

    if messages:
        logger = getLogger(__name__)

        for message in messages:
            logger.critical(message)

def _model_checks(app_configs, **kwargs):
    from django.apps import apps
    from django.core.signals import request_started

    request_started.disconnect(dispatch_uid=_REQUEST_STARTED_UID)

    if app_configs is None:
        app_configs = apps.get_app_configs()

    messages = []

    _initialize(app_configs, messages)

    return messages

class TalosAppConfig(AppConfig):
    name = 'talos'
    verbose_name = 'Talos'
    privileges = [
        ('django.contrib.talos.all_permissions', 'Superuser, has all permissions without explicitly assigning them.'),
        ('django.contrib.admin.web_access', 'Stuff, access admin site.')]

    def ready(self, *args, **kwargs):
        from django.core import checks
        from django.core.signals import request_started
        from django.db.models.signals import post_migrate
        from django.db.models.signals import pre_migrate

        super(TalosAppConfig, self).ready(*args, **kwargs)

        post_migrate.disconnect(dispatch_uid='django.contrib.auth.management.create_permissions')
        pre_migrate.connect(_pre_migrate, dispatch_uid='{0}.{1}'.format(_pre_migrate.__module__, _pre_migrate.__name__))
        post_migrate.connect(_post_migrate, dispatch_uid='{0}.{1}'.format(_post_migrate.__module__, _post_migrate.__name__))
        checks.register(_model_checks, checks.Tags.models)
        request_started.connect(_request_started, dispatch_uid=_REQUEST_STARTED_UID)


text:
import {createPrivateSymbol, getPrivate, setPrivate} from '../private.js';

var $TypeError = TypeError;
var {
  create,
  defineProperties,
  defineProperty,
} = Object;

function nonEnum(value) {
  return {
    configurable: true,
    enumerable: false,
    value: value,
    writable: true
  };
}

// Generator states. Terminology roughly matches that of
//   http://wiki.ecmascript.org/doku.php?id=harmony:generators
// Since 'state' is already taken, use 'GState' instead to denote what's
// referred to as "G.[[State]]" on that page.
var ST_NEWBORN = 0;
var ST_EXECUTING = 1;
var ST_SUSPENDED = 2;
var ST_CLOSED = 3;

var END_STATE = -2;
var RETHROW_STATE = -3;

function getInternalError(state) {
  return new Error('Traceur compiler bug: invalid state in state machine: ' +
                    state);
}

// The following unique object serves as a non-catchable exception raised by
// the implementation of Generator.prototype.return
var RETURN_SENTINEL = {};

function GeneratorContext() {
  this.state = 0;
  this.GState = ST_NEWBORN;
  this.storedException = undefined;
  this.finallyFallThrough = undefined;
  this.sent_ = undefined;
  this.returnValue = undefined;
  this.oldReturnValue = undefined;
  this.tryStack_ = [];
}
GeneratorContext.prototype = {
  pushTry: function(catchState, finallyState) {
    if (finallyState !== null) {
      var finallyFallThrough = null;
      for (var i = this.tryStack_.length - 1; i >= 0; i--) {
        if (this.tryStack_[i].catch !== undefined) {
          finallyFallThrough = this.tryStack_[i].catch;
          break;
        }
      }
      if (finallyFallThrough === null)
        finallyFallThrough = RETHROW_STATE;

      this.tryStack_.push({
        finally: finallyState,
        finallyFallThrough: finallyFallThrough
      });
    }

    if (catchState !== null) {
      this.tryStack_.push({catch: catchState});
    }
  },
  popTry: function() {
    this.tryStack_.pop();
  },
  maybeUncatchable: function () {
    if (this.storedException === RETURN_SENTINEL) {
      throw RETURN_SENTINEL;
    }
  },
  get sent() {
    this.maybeThrow();
    return this.sent_;
  },
  set sent(v) {
    this.sent_ = v;
  },
  get sentIgnoreThrow() {
    return this.sent_;
  },
  maybeThrow: function() {
    if (this.action === 'throw') {
      this.action = 'next';
      throw this.sent_;
    }
  },
  end: function() {
    switch (this.state) {
      case END_STATE:
        return this;
      case RETHROW_STATE:
        throw this.storedException;
      default:
        throw getInternalError(this.state);
    }
  },
  handleException: function(ex) {
    this.GState = ST_CLOSED;
    this.state = END_STATE;
    throw ex;
  },
  wrapYieldStar: function(iterator) {
    var ctx = this;
    return {
      next: function (v) {
        return iterator.next(v);
      },
      throw: function (e) {
        var result;
        if (e === RETURN_SENTINEL) {
          if (iterator.return) {
            result = iterator.return(ctx.returnValue);
            if (!result.done) {
              ctx.returnValue = ctx.oldReturnValue;
              return result;
            }
            ctx.returnValue = result.value;
          }
          throw e;
        }
        if (iterator.throw) {
          return iterator.throw(e);
        }
        // 14.4 "YieldExpression: yield * AssignmentExpression" 1.6.b.iv
        iterator.return && iterator.return();
        throw $TypeError('Inner iterator does not have a throw method');
      }
    };
  }
};

function nextOrThrow(ctx, moveNext, action, x) {
  switch (ctx.GState) {
    case ST_EXECUTING:
      throw new Error(`"${action}" on executing generator`);

    case ST_CLOSED:
      if (action == 'next') {
        return {
          value: undefined,
          done: true
        };
      }
      if (x === RETURN_SENTINEL) {
        return {
          value: ctx.returnValue,
          done: true
        };
      }
      throw x;

    case ST_NEWBORN:
      if (action === 'throw') {
        ctx.GState = ST_CLOSED;
        if (x === RETURN_SENTINEL) {
          return {value: ctx.returnValue, done: true};
        }
        throw x;
      }
      if (x !== undefined)
        throw $TypeError('Sent value to newborn generator');
      // fall through

    case ST_SUSPENDED:
      ctx.GState = ST_EXECUTING;
      ctx.action = action;
      ctx.sent = x;
      var value;
      try {
        value = moveNext(ctx);
      } catch (ex) {
        if (ex === RETURN_SENTINEL) {
          value = ctx;
        } else {
          throw ex;
        }
      }
      var done = value === ctx;
      if (done)
        value = ctx.returnValue;
      ctx.GState = done ? ST_CLOSED : ST_SUSPENDED;
      return {value: value, done: done};
  }
}

var ctxName = createPrivateSymbol();
var moveNextName = createPrivateSymbol();

function GeneratorFunction() {}

function GeneratorFunctionPrototype() {}

GeneratorFunction.prototype = GeneratorFunctionPrototype;

defineProperty(GeneratorFunctionPrototype, 'constructor',
    nonEnum(GeneratorFunction));

GeneratorFunctionPrototype.prototype = {
  constructor: GeneratorFunctionPrototype,
  next: function(v) {
    return nextOrThrow(getPrivate(this, ctxName), getPrivate(this, moveNextName), 'next', v);
  },
  throw: function(v) {
    return nextOrThrow(getPrivate(this, ctxName), getPrivate(this, moveNextName), 'throw', v);
  },
  return: function (v) {
    let ctx = getPrivate(this, ctxName);
    ctx.oldReturnValue = ctx.returnValue;
    ctx.returnValue = v;
    return nextOrThrow(ctx, getPrivate(this, moveNextName), 'throw', RETURN_SENTINEL);
  }
};

defineProperties(GeneratorFunctionPrototype.prototype, {
  constructor: {enumerable: false},
  next: {enumerable: false},
  throw: {enumerable: false},
  return: {enumerable: false}
});

Object.defineProperty(GeneratorFunctionPrototype.prototype, Symbol.iterator,
    nonEnum(function() {
      return this;
    }));

export function createGeneratorInstance(innerFunction, functionObject, self) {
  // TODO(arv): Use [[GeneratorState]]
  var moveNext = getMoveNext(innerFunction, self);
  var ctx = new GeneratorContext();

  var object = create(functionObject.prototype);
  setPrivate(object, ctxName, ctx);
  setPrivate(object, moveNextName, moveNext);
  return object;
}

export function initGeneratorFunction(functionObject) {
  functionObject.prototype = create(GeneratorFunctionPrototype.prototype);
  functionObject.__proto__ = GeneratorFunctionPrototype;
  return functionObject;
}

function AsyncFunctionContext() {
  GeneratorContext.call(this);
  this.err = undefined;
  var ctx = this;
  ctx.result = new Promise(function(resolve, reject) {
    ctx.resolve = resolve;
    ctx.reject = reject;
  });
}
AsyncFunctionContext.prototype = create(GeneratorContext.prototype);
AsyncFunctionContext.prototype.end = function() {
  switch (this.state) {
    case END_STATE:
      this.resolve(this.returnValue);
      break;
    case RETHROW_STATE:
      this.reject(this.storedException);
      break;
    default:
      this.reject(getInternalError(this.state));
  }
};
AsyncFunctionContext.prototype.handleException = function() {
  this.state = RETHROW_STATE;
};

export function asyncWrap(innerFunction, self) {
  var moveNext = getMoveNext(innerFunction, self);
  var ctx = new AsyncFunctionContext();
  ctx.createCallback = function(newState) {
    return function (value) {
      ctx.state = newState;
      ctx.value = value;
      moveNext(ctx);
    };
  }

  ctx.errback = function(err) {
    handleCatch(ctx, err);
    moveNext(ctx);
  };

  moveNext(ctx);
  return ctx.result;
}

function getMoveNext(innerFunction, self) {
  return function(ctx) {
    while (true) {
      try {
        return innerFunction.call(self, ctx);
      } catch (ex) {
        handleCatch(ctx, ex);
      }
    }
  };
}

function handleCatch(ctx, ex) {
  ctx.storedException = ex;
  var last = ctx.tryStack_[ctx.tryStack_.length - 1];
  if (!last) {
    ctx.handleException(ex);
    return;
  }

  ctx.state = last.catch !== undefined ? last.catch : last.finally;

  if (last.finallyFallThrough !== undefined)
    ctx.finallyFallThrough = last.finallyFallThrough;
}


text:
INF1715
=======

Repositório Criado Para execução do trabalho da disciplina INF1715 (Compiladores) da PUC-Rio.


text:
double alhood(double a, double ss, int D, int K);
double d_alhood(double a, double ss, int D, int K);
double d2_alhood(double a, int D, int K);
double opt_alpha(double ss, int D, int K);
void maximize_alpha(double** gamma, mmlda_model* model, int num_docs);

#endif


text:
package com.tapglue.exampleapp;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.tapglue.Tapglue;
import com.tapglue.model.TGEvent;
import com.tapglue.model.TGFeed;
import com.tapglue.networking.requests.TGRequestCallback;
import com.tapglue.networking.requests.TGRequestErrorType;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class FeedActivity extends AppCompatActivity {

    boolean callbackEnabled;
    @Bind(R.id.posts_list)
    ListView mPosts;

    protected void loadData() {
        Tapglue.feed().retrieveNewsFeedForCurrentUser(new TGRequestCallback<TGFeed>() {
            @Override
            public boolean callbackIsEnabled() {
                return callbackEnabled;
            }

            @Override
            public void onRequestError(TGRequestErrorType tgRequestErrorType) {
                Toast.makeText(FeedActivity.this, tgRequestErrorType.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onRequestFinished(final TGFeed tgFeed, boolean b) {
                mPosts.post(new Runnable() {
                    @Override
                    public void run() {

                        if (tgFeed != null && tgFeed.getEvents() != null && tgFeed.getEvents().size() > 0) {
                            showData(tgFeed.getEvents());
                        } else {
                            Toast.makeText(FeedActivity.this, "Feed is empty", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feed);
        ButterKnife.bind(this);
        Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);
        if (getSupportActionBar() == null) return;
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        callbackEnabled = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        callbackEnabled = true;
        loadData();
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

    void showData(List<TGEvent> events) {
        List<String> items = new ArrayList<>();
        List<Long> ids = new ArrayList<>();
        if (events == null)
            return;
        for (TGEvent event : events) {
            items.add("Event from user: " + event.getUserId() + " visibility:" + event.getVisibility());
            ids.add(event.getID());
        }
        StableArrayAdapter adapter = new StableArrayAdapter(this, android.R.layout.simple_list_item_1, items, ids);
        mPosts.setAdapter(adapter);
    }

    /**
     * Simple array adapter showing string data
     */
    private class StableArrayAdapter extends ArrayAdapter<String> {

        HashMap<String, Long> mIdMap = new HashMap<>();

        public StableArrayAdapter(Context context, int textViewResourceId,
                                  List<String> objects, List<Long> ids) {
            super(context, textViewResourceId, objects);
            for (int i = 0; i < objects.size(); ++i) {
                mIdMap.put(objects.get(i), ids.get(i));
            }
        }

        @Override
        public long getItemId(int position) {
            String item = getItem(position);
            return mIdMap.get(item);
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

    }
}


text:
<?php

namespace App\Model;

use Nette\Database\Context;
use Nette\Http\Request;
use Nette\Utils\FileSystem;
use Nette\Utils\Json;

/**
 * @author Martin Bažík <martin@bazik.sk>
 */
class PackageManager
{

	const TABLE_NAME = 'packages';

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

	/** @var array */
	private $parameters;

	/** @var Context */
	private $db;

	/** @var Request */
	private $httpRequest;

	function __construct($configFile, $parameters, Context $db, Request $httpRequest)
	{
		$this->configFile = $configFile;
		$this->parameters = $parameters;
		$this->db = $db;
		$this->httpRequest = $httpRequest;
	}

	public function add($type, $url)
	{
		$this->db->table(self::TABLE_NAME)->insert([
			'type' => $type,
			'url' => $url
		]);
	}

	public function getAll()
	{
		return $this->db->table(self::TABLE_NAME);
	}

	public function delete($id)
	{
		$this->db->table(self::TABLE_NAME)->get($id)->delete();
	}

	public function compileConfig()
	{
		$repositories = $this->getAll();

		$domain = $this->httpRequest->getUrl()->getHostUrl();

		$config = [
			'homepage' => $domain,
			'repositories' => [
			]
		];

		foreach ($this->parameters as $property => $value) {
			$config[$property] = $value;
		}

		foreach ($repositories as $repository) {
			$config['repositories'][] = [
				'type' => $repository->type,
				'url' => $repository->url
			];
		}

		$json = Json::encode($config, Json::PRETTY);

		FileSystem::write($this->configFile, $json);
	}

}


text:
package freemarker.core;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import freemarker.template.SimpleNumber;
import freemarker.template.TemplateBooleanModel;
import freemarker.template.TemplateCollectionModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelIterator;
import freemarker.template.TemplateSequenceModel;

/**
 * A #list or #foreach element.
 */
final class IteratorBlock extends TemplateElement {

    private Expression listExpression;
    private String loopVariableName;
    private boolean isForEach;

    /**
     * @param listExpression a variable referring to a sequence or collection
     * @param loopVariableName an arbitrary index variable name
     * @param nestedBlock the nestedBlock to iterate over
     */
    IteratorBlock(Expression listExpression,
                  String loopVariableName,
                  TemplateElement nestedBlock,
                  boolean isForEach)
    {
        this.listExpression = listExpression;
        this.loopVariableName = loopVariableName;
        this.nestedBlock = nestedBlock;
        this.isForEach = isForEach;
    }

    void accept(Environment env) throws TemplateException, IOException
    {
        TemplateModel listValue = listExpression.eval(env);
        if (listValue == null) {
            if (env.isClassicCompatible()) {
                // Classic behavior of simply ignoring null references.
                return;
            }
            listExpression.assertNonNull(null, env);
        }

        env.visitIteratorBlock(new Context(listValue));
    }

    protected String dump(boolean canonical) {
        StringBuffer buf = new StringBuffer();
        if (canonical) buf.append('<');
        buf.append(getNodeTypeSymbol());
        buf.append(' ');
        if (isForEach) {
            buf.append(_CoreStringUtils.toFTLTopLevelIdentifierReference(loopVariableName));
            buf.append(" in ");
            buf.append(listExpression.getCanonicalForm());
        }
        else {
            buf.append(listExpression.getCanonicalForm());
            buf.append(" as ");
            buf.append(_CoreStringUtils.toFTLTopLevelIdentifierReference(loopVariableName));
        }
        if (canonical) {
            buf.append(">");
            if (nestedBlock != null) {
                buf.append(nestedBlock.getCanonicalForm());
            }
            buf.append("</");
            buf.append(getNodeTypeSymbol());
            buf.append('>');
        }
        return buf.toString();
    }

    int getParameterCount() {
        return 2;
    }

    Object getParameterValue(int idx) {
        switch (idx) {
        case 0: return listExpression;
        case 1: return loopVariableName;
        default: throw new IndexOutOfBoundsException();
        }
    }

    ParameterRole getParameterRole(int idx) {
        switch (idx) {
        case 0: return ParameterRole.LIST_SOURCE;
        case 1: return ParameterRole.TARGET_LOOP_VARIABLE;
        default: throw new IndexOutOfBoundsException();
        }
    }

    String getNodeTypeSymbol() {
        return isForEach ? "#foreach" : "#list";
    }

    /**
     * A helper class that holds the context of the loop.
     */
    class Context implements LocalContext {

        private static final String LOOP_STATE_HAS_NEXT = "_has_next"; // lenght: 9
        private static final String LOOP_STATE_INDEX = "_index"; // length 6

        private boolean hasNext;
        private TemplateModel loopVar;
        private int index;
        private Collection variableNames = null;
        private TemplateModel listValue;

        Context(TemplateModel listValue) {
            this.listValue = listValue;
        }

        void runLoop(Environment env) throws TemplateException, IOException {
            if (listValue instanceof TemplateCollectionModel) {
                final TemplateCollectionModel tcm = (TemplateCollectionModel)listValue;
                final TemplateModelIterator it = tcm.iterator();
                hasNext = it.hasNext();
                while (hasNext) {
                    loopVar = it.next();
                    hasNext = it.hasNext();
                    if (nestedBlock != null) {
                        env.visitByHiddingParent(nestedBlock);  // TODO why not visitByHiddingParent?
                    }
                    index++;
                }
            } else if (listValue instanceof TemplateSequenceModel) {
                final TemplateSequenceModel tsm = (TemplateSequenceModel) listValue;
                final int size = tsm.size();
                for (index = 0; index < size; index++) {
                    loopVar = tsm.get(index);
                    hasNext = (size > index + 1);
                    if (nestedBlock != null) {
                        env.visitByHiddingParent(nestedBlock);
                    }
                }
            } else if (env.isClassicCompatible()) {
                loopVar = listValue;
                if (nestedBlock != null) {
                    env.visitByHiddingParent(nestedBlock);
                }
            } else {
                throw new NonSequenceOrCollectionException(
                        listExpression, listValue, env);
            }
        }

        public TemplateModel getLocalVariable(String name) {
            if (name.startsWith(loopVariableName)) {
                switch(name.length() - loopVariableName.length()) {
                    case 0:
                        return loopVar;
                    case 6:
                        if(name.endsWith(LOOP_STATE_INDEX)) {
                            return new SimpleNumber(index);
                        }
                        break;
                    case 9:
                        if(name.endsWith(LOOP_STATE_HAS_NEXT)) {
                            return hasNext ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
                        }
                        break;
                }
            }
            return null;
        }

        public Collection getLocalVariableNames() {
            if (variableNames == null) {
                variableNames = new ArrayList(3);
                variableNames.add(loopVariableName);
                variableNames.add(loopVariableName + LOOP_STATE_INDEX);
                variableNames.add(loopVariableName + LOOP_STATE_HAS_NEXT);
            }
            return variableNames;
        }
    }

    boolean isNestedBlockRepeater() {
        return true;
    }

}


text:
package com.bupt.poirot.pattern.factoryPattern;

/**
 * Created by hui.chen on 11/25/16.
 */
public interface IAnimal {
    void speak();
}


text:
__author__ = 'wilson.sumanang@gmail.com'

# External Imports
import os
from flask import Flask, render_template, session, flash

# Internal Imports
from app.account import account
from app.media import media
from app.views import views
from photodl.settings import get_config

app_dir = os.path.dirname(os.path.realpath(__file__))

def create_flask_app():
    app = Flask(__name__)

    server_settings = get_config(app_dir, 'photodl')
    app.config['server_settings'] = server_settings
    app.config.update(**server_settings.flask_config)

    app.register_blueprint(account, url_prefix='/account')
    app.register_blueprint(views, url_prefix='/views')
    app.register_blueprint(media, url_prefix='/media')

    @app.route('/')
    @app.route('/index')
    def index():
        if 'access_token' in session:
            flash('you are already signed-in')
        return render_template('index.html')

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('404.html'), 404

    return app