text:
package com.impetus.client.esindexer;

import java.nio.ByteBuffer;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import junit.framework.Assert;

import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.Compression;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.Mutation;
import org.apache.cassandra.thrift.SchemaDisagreementException;
import org.apache.cassandra.thrift.TimedOutException;
import org.apache.cassandra.thrift.UnavailableException;
import org.apache.thrift.TException;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.impetus.client.cassandra.common.CassandraConstants;
import com.impetus.client.cassandra.thrift.CQLTranslator;
import com.impetus.client.crud.BaseTest;
import com.impetus.kundera.client.cassandra.persistence.CassandraCli;
import com.impetus.kundera.property.PropertyAccessorFactory;

/**
 * Test case to perform simple CRUD operation.(insert, delete, merge, and select)
 *
 * @author kuldeep.mishra
 *
 *         Run this script to create column family in cassandra with indexes. create column family PERSON_ESINDEXER with
 *         comparator=UTF8Type and column_metadata=[{column_name: PERSON_NAME, validation_class: UTF8Type, index_type:
 *         KEYS}, {column_name: AGE, validation_class: IntegerType, index_type: KEYS}];
 *
 */
public class PersonCassandraESIndexerTest extends BaseTest {

    /** The Constant _PU. */
    private static final String _PU = "esIndexerTest";

    /** The Constant USE_CQL. */
    protected static boolean USE_CQL = false;

    /** The emf. */
    private EntityManagerFactory emf;

    /** The em. */
    private EntityManager em;

    /** The col. */
    private Map<Object, Object> col;

    /** The node. */
    private static Node node = null;

    /**
     * Sets the up before class.
     *
     * @throws Exception
     *             the exception
     */
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        ImmutableSettings.Builder builder = ImmutableSettings.settingsBuilder();
        builder.put("path.data", "target/data");
        node = new NodeBuilder().settings(builder).node();
    }

    /**
     * Tear down after class.
     *
     * @throws Exception
     *             the exception
     */
    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        node.close();
    }

    /**
     * Sets the up.
     *
     * @throws Exception
     *             the exception
     */
    @Before
    public void setUp() throws Exception {

        Map propertyMap = new HashMap();
        if (USE_CQL) {
            propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);
        }
        emf = Persistence.createEntityManagerFactory(_PU, propertyMap);
        em = emf.createEntityManager();
        col = new java.util.HashMap<Object, Object>();
    }

    @Test
    public void indexDeletionTest() throws Exception
    {
        em.createQuery("DELETE FROM PersonESIndexerCassandra p").executeUpdate();
        Thread.sleep(1000);
        Object p1 = prepare("1", 10);
        Object p2 = prepare("2", 20);
        Object p3 = prepare("3", 30);
        Object p4 = prepare("4", 40);
        em.persist(p1);
        em.persist(p2);
        em.persist(p3);
        em.persist(p4);
        Thread.sleep(1000);
        String query = "Select min(p.age) from PersonESIndexerCassandra p";
        List resultList = em.createQuery(query).getResultList();
        Assert.assertEquals(1, resultList.size());
        Assert.assertEquals(10.0, resultList.get(0));

        em.remove(p1);
        Thread.sleep(1000);
        query = "Select min(p.age) from PersonESIndexerCassandra p";
        resultList = em.createQuery(query).getResultList();
        Assert.assertEquals(1, resultList.size());
        Assert.assertEquals(20.0, resultList.get(0));;

        em.remove(p2);
        Thread.sleep(1000);
        query = "Select min(p.age) from PersonESIndexerCassandra p";
        resultList = em.createQuery(query).getResultList();
        Assert.assertEquals(1, resultList.size());
        Assert.assertEquals(30.0, resultList.get(0));

        em.createQuery("DELETE FROM PersonESIndexerCassandra p").executeUpdate();
    }

    /**
     * On insert cassandra.
     *
     * @throws Exception
     *             the exception
     */
    @Test
    public void onInsertCassandra() throws Exception {
        Object p1 = prepare("1", 10);
        Object p2 = prepare("2", 20);
        Object p3 = prepare("3", 15);
        em.persist(p1);
        em.persist(p2);
        em.persist(p3);
        col.put("1", p1);
        col.put("2", p2);
        col.put("3", p3);
        waitThread();
        em.clear();
        PersonESIndexerCassandra p = findById(PersonESIndexerCassandra.class, "1", em);
        Assert.assertNotNull(p);
        Assert.assertEquals("vivek", p.getPersonName());

        em.clear();
        String qry = "Select p.personId,p.personName from PersonESIndexerCassandra p where p.personId >= 1";
        Query q = em.createQuery(qry);
        List<PersonESIndexerCassandra> persons = q.getResultList();

        assertFindByName(em, "PersonESIndexerCassandra", PersonESIndexerCassandra.class, "vivek", "personName");
        assertFindByNameAndAge(em, "PersonESIndexerCassandra", PersonESIndexerCassandra.class, "vivek", "10",
            "personName");
        assertFindByNameAndAgeGTAndLT(em, "PersonESIndexerCassandra", PersonESIndexerCassandra.class, "vivek", "10",
            "20", "personName");
        assertFindByNameAndAgeBetween(em, "PersonESIndexerCassandra", PersonESIndexerCassandra.class, "vivek", "10",
            "15", "personName");
        assertFindByRange(em, "PersonESIndexerCassandra", PersonESIndexerCassandra.class, "1", "2", "personId", false);
        assertFindWithoutWhereClause(em, "PersonESIndexerCassandra", PersonESIndexerCassandra.class, false);

        // OR clause test case.
        String orClauseQuery = "Select p from PersonESIndexerCassandra p where p.personName = 'vivek1' OR p.age = 10";

        q = em.createQuery(orClauseQuery);

        List<PersonESIndexerCassandra> results = q.getResultList();

        Assert.assertEquals(1, results.size());
        // perform merge after query.
        for (PersonESIndexerCassandra person : persons) {
            person.setPersonName("after merge");
            em.merge(person);
        }
        em.clear();

        p = findById(PersonESIndexerCassandra.class, "1", em);
        Assert.assertNotNull(p);
        Assert.assertEquals("after merge", p.getPersonName());

        // Delete without WHERE clause.

        String deleteQuery = "DELETE from PersonESIndexerCassandra";
        q = em.createQuery(deleteQuery);
        Assert.assertEquals(3, q.executeUpdate());
    }

    /**
     * On merge cassandra.
     *
     * @throws Exception
     *             the exception
     */
    @Test
    public void onMergeCassandra() throws Exception {
        Object p1 = prepare("1", 10);
        Object p2 = prepare("2", 20);
        Object p3 = prepare("3", 15);
        em.persist(p1);
        em.persist(p2);
        em.persist(p3);
        waitThread();
        em.clear();
        col.put("1", p1);
        col.put("2", p2);
        col.put("3", p3);
        PersonESIndexerCassandra p = findById(PersonESIndexerCassandra.class, "1", em);
        Assert.assertNotNull(p);
        Assert.assertEquals("vivek", p.getPersonName());
        // modify record.
        p.setPersonName("newvivek");
        em.merge(p);
        waitThread();
        assertOnMerge(em, "PersonESIndexerCassandra", "vivek", "newvivek", "personName");
    }

    /**
     * On delete then insert cassandra.
     *
     * @throws Exception
     *             the exception
     */
    @Test
    public void onDeleteThenInsertCassandra() throws Exception {
        Object p1 = prepare("1", 10);
        Object p2 = prepare("2", 20);
        Object p3 = prepare("3", 15);
        em.persist(p1);
        em.persist(p2);
        em.persist(p3);
        waitThread();
        col.put("1", p1);
        col.put("2", p2);
        col.put("3", p3);
        PersonESIndexerCassandra p = findById(PersonESIndexerCassandra.class, "1", em);
        Assert.assertNotNull(p);
        Assert.assertEquals("vivek", p.getPersonName());
        em.remove(p);
        em.clear();
        waitThread();
        TypedQuery<PersonESIndexerCassandra> query =
            em.createQuery("Select p from PersonESIndexerCassandra p", PersonESIndexerCassandra.class);

        List<PersonESIndexerCassandra> results = query.getResultList();
        Assert.assertNotNull(query);
        Assert.assertNotNull(results);
        Assert.assertEquals(2, results.size());

        p1 = prepare("1", 10);
        em.persist(p1);

        waitThread();

        query = em.createQuery("Select p from PersonESIndexerCassandra p", PersonESIndexerCassandra.class);

        results = query.getResultList();
        Assert.assertNotNull(query);
        Assert.assertNotNull(results);
        Assert.assertEquals(3, results.size());

    }

    /**
     * On refresh cassandra.
     *
     * @throws Exception
     *             the exception
     */
    @Test
    public void onRefreshCassandra() throws Exception {
        CassandraCli.cassandraSetUp();
        // loadData();
        CassandraCli.client.set_keyspace("KunderaExamples");
        Object p1 = prepare("1", 10);
        Object p2 = prepare("2", 20);
        Object p3 = prepare("3", 15);
        em.persist(p1);
        em.persist(p2);
        em.persist(p3);
        col.put("1", p1);
        col.put("2", p2);
        col.put("3", p3);
        waitThread();
        // Check for contains
        Object pp1 = prepare("1", 10);
        Object pp2 = prepare("2", 20);
        Object pp3 = prepare("3", 15);
        Assert.assertTrue(em.contains(pp1));
        Assert.assertTrue(em.contains(pp2));
        Assert.assertTrue(em.contains(pp3));

        // Check for detach
        em.detach(pp1);
        em.detach(pp2);
        Assert.assertFalse(em.contains(pp1));
        Assert.assertFalse(em.contains(pp2));
        Assert.assertTrue(em.contains(pp3));

        // Modify value in database directly, refresh and then check PC
        em.clear();
        em = emf.createEntityManager();
        Object o1 = em.find(PersonESIndexerCassandra.class, "1");

        if (!USE_CQL) {
            // Create Insertion List
            List<Mutation> insertionList = new ArrayList<Mutation>();
            List<Column> columns = new ArrayList<Column>();
            Column column = new Column();
            column.setName(PropertyAccessorFactory.STRING.toBytes("PERSON_NAME"));
            column.setValue(PropertyAccessorFactory.STRING.toBytes("Amry"));
            column.setTimestamp(System.currentTimeMillis());
            columns.add(column);
            Mutation mut = new Mutation();
            mut.setColumn_or_supercolumn(new ColumnOrSuperColumn().setColumn(column));
            insertionList.add(mut);
            // Create Mutation Map
            Map<String, List<Mutation>> columnFamilyValues = new HashMap<String, List<Mutation>>();
            columnFamilyValues.put("PERSON_ESINDEXER", insertionList);
            Map<ByteBuffer, Map<String, List<Mutation>>> mulationMap =
                new HashMap<ByteBuffer, Map<String, List<Mutation>>>();
            mulationMap.put(ByteBuffer.wrap("1".getBytes()), columnFamilyValues);
            CassandraCli.client.batch_mutate(mulationMap, ConsistencyLevel.ONE);
        } else {
            CQLTranslator translator = new CQLTranslator();
            String query =
                "insert into \"PERSON_ESINDEXER\" (\"personId\",\"PERSON_NAME\",\"AGE\") values ('1','Amry','10')";
            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(query.getBytes()), Compression.NONE,
                ConsistencyLevel.ONE);
        }

        em.refresh(o1);
        Object oo1 = em.find(PersonESIndexerCassandra.class, "1");
        Assert.assertTrue(em.contains(o1));
        Assert.assertEquals("Amry", ((PersonESIndexerCassandra) oo1).getPersonName());
    }

    /**
     * On typed create query.
     *
     * @throws TException
     *             the t exception
     * @throws InvalidRequestException
     *             the invalid request exception
     * @throws UnavailableException
     *             the unavailable exception
     * @throws TimedOutException
     *             the timed out exception
     * @throws SchemaDisagreementException
     *             the schema disagreement exception
     */
    @Test
    public void onTypedQuery() throws TException, InvalidRequestException, UnavailableException, TimedOutException,
        SchemaDisagreementException {
        Object p1 = prepare("1", 10);
        Object p2 = prepare("2", 20);
        Object p3 = prepare("3", 15);
        em.persist(p1);
        em.persist(p2);
        em.persist(p3);
        waitThread();
        TypedQuery<PersonESIndexerCassandra> query =
            em.createQuery("Select p from PersonESIndexerCassandra p", PersonESIndexerCassandra.class);

        List<PersonESIndexerCassandra> results = query.getResultList();
        Assert.assertNotNull(query);
        Assert.assertNotNull(results);
        Assert.assertEquals(3, results.size());
    }

    /**
     * On typed create query.
     *
     * @throws TException
     *             the t exception
     * @throws InvalidRequestException
     *             the invalid request exception
     * @throws UnavailableException
     *             the unavailable exception
     * @throws TimedOutException
     *             the timed out exception
     * @throws SchemaDisagreementException
     *             the schema disagreement exception
     */
    @Test
    public void onGenericTypedQuery() throws TException, InvalidRequestException, UnavailableException,
        TimedOutException, SchemaDisagreementException {
        Object p1 = prepare("1", 10);
        Object p2 = prepare("2", 20);
        Object p3 = prepare("3", 15);
        em.persist(p1);
        em.persist(p2);
        em.persist(p3);
        waitThread();
        TypedQuery<Object> query = em.createQuery("Select p from PersonESIndexerCassandra p", Object.class);

        List<Object> results = query.getResultList();
        Assert.assertNotNull(query);
        Assert.assertNotNull(results);
        Assert.assertEquals(3, results.size());
        Assert.assertEquals(PersonESIndexerCassandra.class, results.get(0).getClass());
    }

    /**
     * On ghost rows.
     *
     * @throws TException
     *             the t exception
     * @throws InvalidRequestException
     *             the invalid request exception
     * @throws UnavailableException
     *             the unavailable exception
     * @throws TimedOutException
     *             the timed out exception
     * @throws SchemaDisagreementException
     *             the schema disagreement exception
     */
    @Test
    public void onGhostRows() throws TException, InvalidRequestException, UnavailableException, TimedOutException,
        SchemaDisagreementException {
        Object p1 = prepare("1", 10);
        Object p2 = prepare("2", 20);
        Object p3 = prepare("3", 15);
        em.persist(p1);
        em.persist(p2);
        em.persist(p3);
        em.clear();
        waitThread();
        PersonESIndexerCassandra person = em.find(PersonESIndexerCassandra.class, "1");
        em.remove(person);
        em.clear(); // just to make sure that not to be picked up from cache.
        waitThread();
        TypedQuery<PersonESIndexerCassandra> query =
            em.createQuery("Select p from PersonESIndexerCassandra p", PersonESIndexerCassandra.class);

        List<PersonESIndexerCassandra> results = query.getResultList();
        Assert.assertNotNull(results);
        Assert.assertEquals(2, results.size());
    }

    // added, test for like queries and matchmode with '%'
    /**
     * Test like query.
     *
     * @throws TException
     *             the t exception
     * @throws InvalidRequestException
     *             the invalid request exception
     * @throws UnavailableException
     *             the unavailable exception
     * @throws TimedOutException
     *             the timed out exception
     * @throws SchemaDisagreementException
     *             the schema disagreement exception
     */
    @Test
    public void testLikeQuery() throws TException, InvalidRequestException, UnavailableException, TimedOutException,
        SchemaDisagreementException {
        // CassandraCli.createKeySpace("KunderaExamples");
        // loadData();
        Object p1 = prepare(10, "karthik");
        Object p2 = prepare(20, "viveek");
        Object p3 = prepare(15, "kartheek");
        em.persist(p1);
        em.persist(p2);
        em.persist(p3);
        em.clear();
        waitThread();
        // test left
        TypedQuery<PersonESIndexerCassandraUUID> query =
            em.createQuery("Select p from PersonESIndexerCassandraUUID p where p.personName like :name",
                PersonESIndexerCassandraUUID.class);
        query.setParameter("name", "%eek");

        List<PersonESIndexerCassandraUUID> results = query.getResultList();

        Assert.assertNotNull(results);
        Assert.assertEquals(2, results.size());
        Assert.assertNotSame("karthik", results.get(0).getPersonName());
        Assert.assertNotSame("karthik", results.get(1).getPersonName());

        if (results.get(0).getAge().equals("20")) {
            Assert.assertEquals("viveek", results.get(0).getPersonName());
            Assert.assertEquals("kartheek", results.get(1).getPersonName());
        } else {
            Assert.assertEquals("kartheek", results.get(0).getPersonName());
            Assert.assertEquals("viveek", results.get(1).getPersonName());
        }

        // test right
        query =
            em.createQuery("Select p from PersonESIndexerCassandraUUID p where p.personName like :name",
                PersonESIndexerCassandraUUID.class);
        query.setParameter("name", "kar%");

        results = query.getResultList();

        Assert.assertNotNull(results);
        Assert.assertEquals(2, results.size());
        Assert.assertNotSame("viveek", results.get(0).getPersonName());
        Assert.assertNotSame("viveek", results.get(1).getPersonName());

        if (results.get(0).getAge().equals("10")) {
            Assert.assertEquals("karthik", results.get(0).getPersonName());
            Assert.assertEquals("kartheek", results.get(1).getPersonName());
        } else {
            Assert.assertEquals("kartheek", results.get(0).getPersonName());
            Assert.assertEquals("karthik", results.get(1).getPersonName());
        }

        // test default
        query =
            em.createQuery("Select p from PersonESIndexerCassandraUUID p where p.personName like :name",
                PersonESIndexerCassandraUUID.class);
        query.setParameter("name", "viv");

        results = query.getResultList();
        Assert.assertEquals("viveek", results.get(0).getPersonName());

        Assert.assertNotNull(results);
        Assert.assertEquals(1, results.size());

        // test both
        query =
            em.createQuery("Select p from PersonESIndexerCassandraUUID p where p.personName like :name",
                PersonESIndexerCassandraUUID.class);
        query.setParameter("name", "%art%");

        results = query.getResultList();

        Assert.assertNotNull(results);
        Assert.assertEquals(2, results.size());
        Assert.assertNotSame("viveek", results.get(0).getPersonName());
        Assert.assertNotSame("viveek", results.get(1).getPersonName());

        if (results.get(0).getAge().equals("10")) {
            Assert.assertEquals("karthik", results.get(0).getPersonName());
            Assert.assertEquals("kartheek", results.get(1).getPersonName());
        } else {
            Assert.assertEquals("kartheek", results.get(0).getPersonName());
            Assert.assertEquals("karthik", results.get(1).getPersonName());
        }

    }

    // added, test for '>' on datatype Timestamp
    /**
     * Test operators.
     *
     * @throws TException
     *             the t exception
     * @throws InvalidRequestException
     *             the invalid request exception
     * @throws UnavailableException
     *             the unavailable exception
     * @throws TimedOutException
     *             the timed out exception
     * @throws SchemaDisagreementException
     *             the schema disagreement exception
     */
    @Test
    public void testOperators() throws TException, InvalidRequestException, UnavailableException, TimedOutException,
        SchemaDisagreementException {

        Object p1 = prepare(10, "karthik", new Timestamp(9419290317914l));
        Object p2 = prepare(20, "vivek", new Timestamp(new Date().getTime()));
        Object p3 = prepare(15, "pragalbh", new Timestamp(1418290317914l));

        em.persist(p1);
        em.persist(p2);
        em.persist(p3);
        em.clear();
        waitThread();
        TypedQuery<PersonESIndexerCassandraUUID> query =
            em.createQuery("Select p from PersonESIndexerCassandraUUID p where p.date > :date",
                PersonESIndexerCassandraUUID.class).setParameter("date", new Timestamp(new Date().getTime()).getTime());
        List<PersonESIndexerCassandraUUID> results = query.getResultList();
        java.util.Iterator<PersonESIndexerCassandraUUID> i = results.iterator();
        Assert.assertNotNull(query);
        Assert.assertNotNull(results);
        Assert.assertEquals(1, results.size());
    }

    // added, test for partition keys of type UUID
    /**
     * Test uuid.
     *
     * @throws TException
     *             the t exception
     * @throws InvalidRequestException
     *             the invalid request exception
     * @throws UnavailableException
     *             the unavailable exception
     * @throws TimedOutException
     *             the timed out exception
     * @throws SchemaDisagreementException
     *             the schema disagreement exception
     */
    @Test
    public void testUUID() throws TException, InvalidRequestException, UnavailableException, TimedOutException,
        SchemaDisagreementException {

        Object p1 = prepare(10, "karthik");
        Object p2 = prepare(20, "vivek");
        Object p3 = prepare(15, "pragalbh");
        em.persist(p1);
        em.persist(p2);
        em.persist(p3);
        em.clear();
        waitThread();
        TypedQuery<PersonESIndexerCassandraUUID> query =
            em.createQuery("Select p from PersonESIndexerCassandraUUID p", PersonESIndexerCassandraUUID.class);
        List<PersonESIndexerCassandraUUID> results = query.getResultList();
        java.util.Iterator<PersonESIndexerCassandraUUID> i = results.iterator();
        Assert.assertNotNull(query);
        Assert.assertNotNull(results);
        Assert.assertEquals(3, results.size());
    }

    /**
     * Tear down.
     *
     * @throws Exception
     *             the exception
     */
    @After
    public void tearDown() throws Exception {

        emf.close();
        CassandraCli.dropKeySpace("KunderaExamples");
    }

    /**
     * Prepare data.
     *
     * @param rowKey
     *            the row key
     * @param age
     *            the age
     * @return the person
     */
    private PersonESIndexerCassandra prepare(String rowKey, int age) {
        PersonESIndexerCassandra o = new PersonESIndexerCassandra();
        o.setPersonId(rowKey);
        o.setPersonName("vivek");
        o.setAge(age);
        o.setDay(PersonESIndexerCassandra.Day.MONDAY);
        return o;
    }

    /**
     * Prepare.
     *
     * @param age
     *            the age
     * @param name
     *            the name
     * @return the person es indexer cassandra uuid
     */
    private PersonESIndexerCassandraUUID prepare(int age, String name) {
        PersonESIndexerCassandraUUID o = new PersonESIndexerCassandraUUID();
        UUID z = UUID.randomUUID();
        o.setPersonId(z);
        o.setPersonName(name);
        o.setAge(age + "");
        o.setDay(PersonESIndexerCassandraUUID.Day.MONDAY);
        return o;
    }

    /**
     * Prepare.
     *
     * @param age
     *            the age
     * @param name
     *            the name
     * @return the person es indexer cassandra uuid
     */
    private PersonESIndexerCassandraUUID prepare(int age, String name, Timestamp time) {
        PersonESIndexerCassandraUUID o = new PersonESIndexerCassandraUUID();
        UUID z = UUID.randomUUID();
        o.setPersonId(z);
        o.setPersonName(name);
        o.setDate(time);
        o.setAge(age + "");
        return o;
    }

    /**
     * Assert on merge.
     *
     * @param em
     *            the em
     * @param clazz
     *            the clazz
     * @param oldName
     *            the old name
     * @param newName
     *            the new name
     * @param fieldName
     *            the field name
     */
    private void assertOnMerge(EntityManager em, String clazz, String oldName, String newName, String fieldName) {
        Query q = em.createQuery("Select p from " + clazz + " p where p." + fieldName + " = " + oldName);
        List<PersonESIndexerCassandra> results = q.getResultList();
        Assert.assertNotNull(results);
        Assert.assertEquals(2, results.size());

        q = em.createQuery("Select p from " + clazz + " p where p." + fieldName + " = " + newName);
        results = q.getResultList();
        Assert.assertNotNull(results);
        Assert.assertEquals(1, results.size());
        Assert.assertNotSame(oldName, getPersonName(results.get(0)));
        Assert.assertEquals(newName, getPersonName(results.get(0)));
    }

    /**
     * Gets the person name.
     *
     * @param result
     *            the result
     * @return the person name
     */
    private String getPersonName(Object result) {

        return ((PersonESIndexerCassandra) result).getPersonName();
    }

    /**
     * Wait thread.
     */
    private void waitThread() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {

        }
    }
}


text:
// @flow
// $FlowFixMe useEffect not recognized by flow.
import { useEffect } from 'react'
import { connect } from 'react-redux'

import * as statusActions from '../../manager/actions/status'

/**
 * Retrieves the app info and updates the redux state accordingly.
 */
const AppInfoRetriever = ({ fetchAppInfo }) => {
  // Fetch app info only once.
  useEffect(fetchAppInfo, [])

  // Component renders nothing.
  return null
}

const mapDispatchToProps = {
  fetchAppInfo: statusActions.fetchAppInfo
}

export default connect(null, mapDispatchToProps)(AppInfoRetriever)

redpajama_set_name: RedPajamaGithub


text:
package com.sqisland.android.test_demo;

public class DgMockDemoApplication extends DemoApplication {
  @Override
  protected DemoComponent createComponent() {
    return DaggerDgActivityTest_DgTestComponent.builder()
            .applicationModule(new ApplicationModule(this))
            .build();
  }
}


text:
<!DOCTYPE html>

  {% include head.html %}

    {% include header.html %}

        {{ content }}

              <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

              Description

              <button type="button" class="btn btn-default" data-dismiss="modal">Закрыть</button>

    {% include footer.html %}


text:
Thank you for visiting frapid github repository. Frapid is open source application development
framework released under **Apache v2.0 License**.

# Introduction

Frapid is a multi-tenant application development framework with a basic
built-in CMS (content management system) functionality. Although frapid can be used
to build website, it can do a way much more than that.

# Modules & Applications

Frapid provides you bells and whistles to start building your own application (module).
Any frapid application may target any or all of the following scopes:

* Website (Anonymous. Example: Content, Gallery, Blog, Job Listing, etc.)
* Website (Users. Example: Discussion Boards, QnA Site, etc.)
* Backend (Users & Employees. Example: CRM, HRM, ERP, or any other business application)

# Multi Tenancy Concept & Conventions

Frapid was built from the ground up for the cloud. Not only frapid supports web farm environments,
frapid can also host several (hundred) website and application instances
running as a single IIS Website.

**Documentation**

* [Developer Documentation](docs/developer/README.md)
* [Installation Guide](docs/installation/README.md)
* [Database Naming Convention](docs/concepts/database-naming-convention.md)
* [Credits](docs/credits/README.md)

# Who Is Using Frapid?

* [MixERP Website on PostgreSQL](https://mixerp.org)
* [MixERP Community Forums (Private App)](https://mixerp.org/forums)
* [MixERP 2.0](https://github.com/mixerp/mixerp)
* [Frapid Website on SQL Server](https://frapid.com)


text:
require 'pathname'
load Pathname.new(File.join(File.dirname(__FILE__), ['..'] * 4,
                            'bioruby_test_helper.rb')).cleanpath.to_s

# libraries needed for the tests
require 'test/unit'
require 'bio/appl/meme/mast'

module Bio
module TestMastData

  TEST_DATA = Pathname.new(File.join(BioRubyTestDataPath, 'meme')).cleanpath.to_s

  def self.example_mfile
    File.join TEST_DATA, 'meme.out'
  end

  def self.dummy_binary
    File.join TEST_DATA, 'mast'
  end

  def self.dummy_db
    File.join TEST_DATA, 'db'
  end
end

class TestMast < Test::Unit::TestCase

  TEST_DATA = TestMastData::TEST_DATA

  def setup
    @example_mfile = TestMastData.example_mfile
    @binary = TestMastData.dummy_binary
    @db = TestMastData.dummy_db
    @mast = Meme::Mast.new(@binary)
  end

  def test_config_defaults
    assert_equal(true, @mast.options[:hit_list])
    assert_equal(true, @mast.options[:stdout])
    assert_equal(true, @mast.options[:nostatus])
  end

  def test_minimal_config
    options = {:mfile => @example_mfile, :d => @db}
    @mast.config(options)
    assert_equal(@db, @mast.options[:d])
    assert_equal(@example_mfile, @mast.options[:mfile])
  end

  def test_more_config
    options = {:mfile => @example_mfile, :d => @db, :dna => true}
    @mast.config(options)
    assert_equal(true, @mast.options[:dna])
  end

  def test_check_options_with_valid_opts
    options = {:mfile => @example_mfile, :d => @db}
    @mast.config(options)
    assert_nothing_raised { @mast.check_options }
  end

  def test_check_options_with_invalid_opts
    options = {:mfile => @example_mfile, :d => @db, :bad => "option"}
    @mast.config(options)
    assert_raises(ArgumentError) { @mast.check_options }
  end

  def test_check_options_with_empty_opts
    # <mfile> and <-d> are required
    options = {}
    @mast.config(options)
    assert_raises(ArgumentError) { @mast.check_options }
  end

  # this is ugly
  def test_command_to_be_run
    options = {:mfile => @example_mfile, :d => @db}
    @mast.config(options)
    assert_equal(true, @mast.cmd.include?("#{@binary} #{@example_mfile} -d #{@db}") )
    assert_equal(true, @mast.cmd.include?('-hit_list') )
    assert_equal(true, @mast.cmd.include?('-stdout') )
    assert_equal(true, @mast.cmd.include?('-nostatus') )
  end

  # this would require a working executable and a database
  def test_run
    # options = {:mfile => @example_mfile, :d => @db}
    # @mast.config(options)
    # report = @mast.run
    # assert_kind_of(Meme::Mast::Report, report)
  end

end # TestMast
end # Bio


text:
using Util.Validations;

namespace Util.Tests.Samples {
    /// <summary>
    /// 验证处理器样例 - 什么也不做
    /// </summary>
    public class ValidationHandlerSample : IValidationHandler {
        /// <summary>
        /// 处理错误
        /// </summary>
        /// <param name="results">验证结果集合</param>
        public void Handle( ValidationResultCollection results ) {
        }
    }
}


text:
<?php
namespace oauth;
class Controller_OAuth_LinkedIn extends Controller_OAuth {
    protected $type = "linkedin";
    protected $request_token_baseurl = "https://api.linkedin.com/uas/oauth/requestToken";
    protected $access_token_baseurl = "https://api.linkedin.com/uas/oauth/accessToken";
    protected $authorize_token_baseurl = "https://www.linkedin.com/uas/oauth/authorize";
    protected $obtain_request_token_method = "GET";

  function performLinkedInRequest($url, $post_data = null, $get = false){
        $options = array(
            "oauth_token" => urlencode($this->getAuthToken(false)),
        );
        if ($get){
            return $this->performRequest($url, $options);
        } else {
            return $this->performPostRequest($url, array("Expect:"), $options, $post_data);
        }
    }
    function check($scope=null){
        $this->request_token_extra_auth = array("scope" => $scope);
        return parent::check();
    }
}


text:
package com.handmark.pulltorefresh.samples;

import java.util.Arrays;
import java.util.LinkedList;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.topface.PullToRefreshBase;
import com.topface.PullToRefreshBase.Mode;
import com.topface.PullToRefreshBase.OnRefreshListener2;
import com.topface.PullToRefreshGridView;

public final class PullToRefreshGridActivity extends Activity {

	static final int MENU_SET_MODE = 0;

	private LinkedList<String> mListItems;
	private PullToRefreshGridView mPullRefreshGridView;
	private GridView mGridView;
	private ArrayAdapter<String> mAdapter;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ptr_grid);

		mPullRefreshGridView = (PullToRefreshGridView) findViewById(R.id.pull_refresh_grid);
		mGridView = mPullRefreshGridView.getRefreshableView();

		// Set a listener to be invoked when the list should be refreshed.
		mPullRefreshGridView.setOnRefreshListener(new OnRefreshListener2<GridView>() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
				Toast.makeText(PullToRefreshGridActivity.this, "Pull Down!", Toast.LENGTH_SHORT).show();
				new GetDataTask().execute();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
				Toast.makeText(PullToRefreshGridActivity.this, "Pull Up!", Toast.LENGTH_SHORT).show();
				new GetDataTask().execute();
			}

		});

		mListItems = new LinkedList<String>();

		TextView tv = new TextView(this);
		tv.setGravity(Gravity.CENTER);
		tv.setText("Empty View, Pull Down/Up to Add Items");
		mPullRefreshGridView.setEmptyView(tv);

		mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mListItems);
		mGridView.setAdapter(mAdapter);
	}

	private class GetDataTask extends AsyncTask<Void, Void, String[]> {

		@Override
		protected String[] doInBackground(Void... params) {
			// Simulates a background job.
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
			}
			return mStrings;
		}

		@Override
		protected void onPostExecute(String[] result) {
			mListItems.addFirst("Added after refresh...");
			mListItems.addAll(Arrays.asList(result));
			mAdapter.notifyDataSetChanged();

			// Call onRefreshComplete when the list has been refreshed.
			mPullRefreshGridView.onRefreshComplete();

			super.onPostExecute(result);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_SET_MODE, 0,
				mPullRefreshGridView.getMode() == Mode.BOTH ? "Change to MODE_PULL_DOWN"
						: "Change to MODE_PULL_BOTH");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		MenuItem setModeItem = menu.findItem(MENU_SET_MODE);
		setModeItem.setTitle(mPullRefreshGridView.getMode() == Mode.BOTH ? "Change to MODE_PULL_FROM_START"
				: "Change to MODE_PULL_BOTH");

		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case MENU_SET_MODE:
				mPullRefreshGridView
						.setMode(mPullRefreshGridView.getMode() == Mode.BOTH ? Mode.PULL_FROM_START
								: Mode.BOTH);
				break;
		}

		return super.onOptionsItemSelected(item);
	}

	private String[] mStrings = { "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
			"Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",
			"Allgauer Emmentaler" };
}


text:
import { Component, OnInit, OnDestroy } from '@angular/core';

import { Subscription } from 'rxjs/Subscription';

import { DeckService } from '../deck.service';
import { DeckStoreService } from '../deck-store.service';
import { CardData, Card } from '../model';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, OnDestroy {

  cards: Card[] = [];
  more: boolean = true;
  subscription: Subscription;

  constructor(
    private deckService: DeckService,
    private deckStoreService: DeckStoreService
  ) {}

  ngOnInit() {
    this.subscription = this.deckStoreService.decks.subscribe(deck => {
      console.log('Deck changed. Go get first page.', deck);
      this.deckService.getFirstPage(this.deckStoreService.deck)
                      .then(cardData => {
                        console.log('Got first page.');
                        this.cards = [];
                        this.cards.push(...cardData.data);
                        this.cards[0].current = true;
                      });
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  getNextPage() {
    console.log('Go get next page.');
    this.deckService.getNextPage(this.deckStoreService.deck)
                    .then(cardData => {
                      console.log('Got next page.');
                      this.cards.push(...cardData.data);
                    })
                    .catch((ex) => {
                      console.error('Error fetching next page.', ex);
                      if(ex === 'No more cards.') {
                        this.more = false;
                      }
                    });
  }

}


text:
layout: post
date: 2017-03-22
title: "Liancarlo Style 6818 2015 Fall Sleeveless Chapel Train Ballgown"
category: Liancarlo
tags: [Liancarlo ,Liancarlo,Ballgown,Sweetheart,Chapel Train,Sleeveless,2015,Fall]
---
### Liancarlo Style 6818
Just **$409.99**
### 2015 Fall Sleeveless Chapel Train Ballgown

BRANDS	Liancarlo

Silhouette	Ballgown

Neckline	Sweetheart

Hemline/Train	Chapel Train

Sleeve	Sleeveless

Years	2015

Season	Fall

Buy it: [https://www.readybrides.com/en/liancarlo-/41930-liancarlo-style-6818.html](https://www.readybrides.com/en/liancarlo-/41930-liancarlo-style-6818.html)


text:
package br.com.arbo.steamside.steam.client.localfiles.sharedconfig;

import java.io.File;

import javax.inject.Inject;

import br.com.arbo.steamside.steam.client.localfiles.steamlocation.SteamLocation;

public class Dir_userdata {

	private final SteamLocation steamDirectory;

	@Inject
	public Dir_userdata(final SteamLocation steamDirectory) {
		this.steamDirectory = steamDirectory;
	}

	public File userdata() {
		final File steam = steamDirectory.steam();
		return new File(steam, "userdata");
	}
}


text:
<?php

namespace Zotlabs\Update;

class _1020 {
function run() {
	$r = q("alter table photo drop `contact-id`, drop guid, drop index `resource-id`, add index ( `resource_id` )");
	if($r)
		return UPDATE_SUCCESS;
	return UPDATE_FAILED;
}

}


text:
@font-face {
    font-family: 'FreeUniversal';
    src: url('/pages/fonts/FreeUniversal-Regular.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}
/*@font-face {*/

/*font-family: 'FreeUniversal';*/

/*    src: url('/pages/fonts/FreeUniversal-Italic.ttf') format('truetype');*/

/*font-weight: normal;*/

/*font-style: italic;*/

/*  }*/

/*@font-face {*/

/*font-family: 'FreeUniversal';*/

/*    src: url('/pages/fonts/FreeUniversal-BoldItalic.ttf') format('truetype');*/

/*font-weight: bold;*/

/*font-style: italic;*/

/*  }*/

@font-face {
    font-family: 'FreeUniversal';
    src: url('/pages/fonts/FreeUniversal-Bold.ttf') format('truetype');
    font-weight: bold;
    font-style: normal;
}
@font-face {
    font-family: 'Crimson';
    src: url('/pages/fonts/Crimson-Bold.otf') format('opentype');
    font-weight: bold;
    font-style: normal;
}
@font-face {
    font-family: 'Crimson';
    src: url('/pages/fonts/Crimson-Italic.otf') format('opentype');
    font-weight: normal;
    font-style: italic;
}
@font-face {
    font-family: 'Crimson';
    src: url('/pages/fonts/Crimson-Roman.otf') format('opentype');
    font-weight: normal;
    font-style: normal;
}
.story .summary a {
    word-break: break-all;
}
.story > a.title {
    font-family: 'FreeUniversal';
    font-size: 22px;
    font-weight: bold;
}
.story .summary {
    font-family: 'Crimson';
    font-size: 22px;
    line-height: 1.5;
}
.pageTitle {
    position: absolute;
    display: block;
    left: 0;
    right: 0;
    text-align: center;
}
li.sub {
    position: relative;
}
li.sub .actions {
    float: right;
}
li.sub:hover .actions {} .list-controls {
}
.showAllFeeds {
    padding: 6px;
}
.unreadCount {
    padding: 15px;
    color: #BEBEBE;
}
.unreadCount.total {
    padding: 10px 10px;
}
.list-pager {
    text-align: right;
    clear: both;
}
.subs-list .saved .star {
    font-size: 22px;
    padding: 0px 0px 0px 4px;
}
@media only screen and (min-width: 767px) {
    .subs-list {} .subs-list .showAllFeeds {
        font-weight: bold;
        padding: 8px;
    }
    .subs-list .subs,
    .subs-list .showAllFeeds {
        direction: ltr;
    }
    .subs .title {
        font-size: 14px;
        line-height: 42px;
    }
    .subs .title a {} .news-list {}
}
.favicon img {
    max-height: 16px;
}
.subs .title {} .subs .title a {} .news-list {} .subscribe input {
    text-indent: 4px;
    width: 100%;
    box-sizing: border-box;
}
.subs .byline,
.subs-list .list-pager {
    display: none;
}
.app > .form {
    position: fixed;
    top: 45px;
    bottom: 0px;
    left: 0px;
    width: 250px;
    height: 32px;
    z-index: 2;
    border-bottom: 1px dashed black;
}
.news .story .summary img {
    display: none;
}
.news .story a.title {
    color: rgb(25, 89, 201);
    margin-right: 12px;
    cursor: pointer;
}
.story .rating {
    position: absolute;
    bottom: 0px;
    left: 6px;
}
.news .story .actions {
    position: absolute;
    bottom: 0;
    left: 30px;
    padding: 4px;
    color: #999;
}
.news .story .sharing {
    position: absolute;
    bottom: 4px;
    left: 60px;
    padding: 4px;
    color: #FFFFFF;
    background: #E6E6E6;
}
.news .story .actions .checkbox input {
    display: none;
}
.news .story .actions:hover label {
    display: inline;
}
.news .story .actions .checkbox {
    margin: 0 0;
    opacity: 0.5;
    padding-left: 0px;
    padding-top: 3px;
}
.news .story .actions:hover  .checkbox {
    display: block;
    opacity: 1;
}
ul.news li.story .fromUrl .avatar {
    margin-left: 6px;
    margin-right: 6px;
}
ul.news li.story .fromUrl, .news .story .byline {
    color: #999;
    font-size: 12px;
    margin-right: 0px;
    margin-top: 12px;
    float: right;
}

ul.news li.story[selected] .summary.full,
ul.news.expanded li.story .summary,
ul.news li.story.no-title .summary,
ul.news li.story[selected] .summary iframe,
ul.news.expanded .story .summary iframe {
    padding: 12px 6px 0px;
    display: block;
}
ul.news li.story.no-title .title, ul.news li.story.no-title .summary.full {
    display: none;
}
.news .story .summary p,
.news .story .summary h1,
.news .story .summary h2,
.news .story .summary h3 {
    display: inline;
    font-weight: normal;
    font-size: 1em;
}
ul.news {
    margin-top: 12px;
    clear: both;
}
ul.news li.story {
    position: relative;
    border-bottom: 12px solid #FFF;
    border-top: 1px solid rgb(223, 223, 223);
}
ul.news li.story[selected],
ul.news.expanded li.story {
    height: auto !important;
    padding: 20px 4px 0px;
    overflow: auto;
}
ul.news li.story[selected] a.title,
ul.news.expanded a.title {
    display: block;
    line-height: 28px;
    padding-left: 6px;
}
ul.news li.story[selected] .summary img,
ul.news.expanded .summary img {
    display: inline;
    max-width: 100%;
    height: auto;
}
.news .story .byline {
    margin-left: 111px;
}
ul.news.expanded .summary img.abbrImg {
    float: left;
    padding: 6px 16px 4px 2px;
    height: 120px;
}
ul.news.expanded .summary img[height="1"], ul.news li.story[selected] .summary img[height="1"] {
    display: none;
}
ul.news li.story[selected] .summary p,
ul.news.expanded .summary p,
ul.news li.story[selected] .summary h1,
ul.news.expanded .summary h1,
ul.news li.story[selected] .summary h2,
ul.news.expanded .summary h2,
ul.news li.story[selected] .summary h3,
ul.news.expanded .summary h3,
ul.news li.story[selected] .summary h4,
ul.news.expanded .summary h4 {
    display: block;
    font-weight: initial !important;
    font-size: initial !important;
}
.subs .favicon {
    padding: 6px;
}
li.story .rating {
    cursor: pointer;
}
.rating {
    unicode-bidi: bidi-override;
}
.rating .star {
    font-size: 133%;
    font-weight: bold;
    color: #CCC;
}
.rating.selected .star {
    color: #000;
}
.rating:hover .star {} .rating > span {
    display: inline-block;
    position: relative;
}
.rating > span:hover:before,
.rating > span:hover ~ span:before {
    content: "\2605";
    position: absolute;
    color: rgb(25, 89, 201, 0.5);
}
.rating > span.selected:before,
.rating > span.selected ~ span:before {
    content: "\2605";
    position: absolute;
    color: rgb(25, 89, 201);
}
.rating.selected > span:before,
.rating.selected > span ~ span:before {
    content: "\2605";
    position: absolute;
    color: rgb(25, 89, 201);
}
.rating.selected > span:hover:before,
.rating.selected > span:hover ~ span:before {
    content: "\2605";
    position: absolute;
    color: rgba(25, 89, 201, 0.5);
}
.news .story .summary {
    display: none;
    overflow: visible;
}
ul.news.expanded li.story .summary.full {
    display: none;
}
ul.news.expanded li.story.selected .summary {
    display: none;
}
ul.news.expanded li.story.selected .summary.full {
    display: block;
}
.news .story .summary iframe {
    display: none;
}
.news .story .summary .feedflare, .news .story .summary .yarpp-related-rss {
    display: none;
}
.summary img.enclosureImg {
    float: left;
    margin: 0px 12px 16px 0px;
}
.enclosure {
    margin: 12px 0px 0px 0px;
    display: block;
}
.enclosure audio, .enclosure img {
    width: 100%;
}

.news .story .actions .checkbox label:before {
    border-radius: 50%;
    height: 15px;
    width: 15px;
    border: 1px solid rgb(199, 199, 199);
    display: block;
    color: rgb(10, 10, 156);
    font-size: 24px;
    content: " ";
    line-height: 4px;
    text-align: center;
    text-indent: -1px;
    padding-top: 3px;
}
.news .story .actions .checkbox label:hover:before {
    content: "●";
    color: rgba(10, 10, 156, 0.5);
}
.news .story .actions .checkbox input[type=checkbox]:checked + label:before {
    content: "●";
}
.news:not(.expanded) .story:not(.selected) .actions, .news:not(.expanded) .story:not(.selected) .byline, .news:not(.expanded) .story:not(.selected) .fromUrl, .news:not(.expanded) .story:not(.selected) .rating {
    display: none;
}
.news:not(.expanded) .story:not(.selected) {
    padding: 16px 0px;
}

ul.subs .sub .actions {
    display: none;
}
ul.subs .sub:hover .actions {
    display: block;
}

.sub .title.url {
    font-weight: normal;
    padding-left: 28px;
}

.btn-group .dropdown-menu {
    margin-top: 0;
}

#accountNav .dropdown-toggle img.avatar, #accountMenu img.avatar {
    max-height: 18px;
    max-width: 18px;
    margin: 0px 0px 0px 0px;
}
#accountMenu img.avatar {
    margin: 0px 0px 0px 12px;
}
#accountNav .dropdown-toggle .userAvatarName .name {
    display: none;
}


text:
#include "tensorflow/compiler/mlir/quantization/tensorflow/calibrator/calibrator_singleton.h"

#include <algorithm>
#include <string>

namespace tensorflow {
namespace calibrator {

ABSL_CONST_INIT absl::Mutex CalibratorSingleton::lock_(absl::kConstInit);

CalibratorSingleton& CalibratorSingleton::GetInstance() {
  static CalibratorSingleton* calibrator = new CalibratorSingleton();
  return *calibrator;
}

void CalibratorSingleton::ClearCollectedInformation() {
  absl::MutexLock lock(&lock_);

  CalibratorSingleton& instance = GetInstance();
  instance.id_to_min_.clear();
  instance.id_to_max_.clear();
}

void CalibratorSingleton::ClearData(absl::string_view id) {
  absl::MutexLock lock(&lock_);

  CalibratorSingleton& instance = GetInstance();

  const std::string id_str{id};
  instance.id_to_min_.erase(id_str);
  instance.id_to_max_.erase(id_str);
}

void CalibratorSingleton::ReportMinMax(absl::string_view id,
                                       const float min_val,
                                       const float max_val) {
  absl::MutexLock lock(&lock_);

  CalibratorSingleton& instance = GetInstance();

  const std::string id_str{id};

  // Update the min value.
  if (auto min_itr = instance.id_to_min_.find(id_str);
      min_itr != instance.id_to_min_.end()) {
    min_itr->second = std::min(min_val, min_itr->second);
  } else {
    instance.id_to_min_[id_str] = min_val;
  }

  // Update the max values.
  if (auto max_itr = instance.id_to_max_.find(id_str);
      max_itr != instance.id_to_max_.end()) {
    max_itr->second = std::max(max_val, max_itr->second);
  } else {
    instance.id_to_max_[id_str] = max_val;
  }
}

std::optional<std::pair<float, float>> CalibratorSingleton::GetMinMax(
    absl::string_view id) {
  absl::MutexLock lock(&lock_);

  CalibratorSingleton& instance = GetInstance();

  const std::string id_str{id};
  const auto min_itr = instance.id_to_min_.find(id_str);
  const auto max_itr = instance.id_to_max_.find(id_str);
  if (min_itr == instance.id_to_min_.end() ||
      max_itr == instance.id_to_max_.end()) {
    return std::nullopt;
  }

  return std::pair<float, float>{min_itr->second, max_itr->second};
}

}  // namespace calibrator
}  // namespace tensorflow


text:
layout: post
title: "#NowPlaying: A Tracker Built on Last.FM's API"
description: "Yesterday I made a #nowplaying tracker. It looks at a user profile and pulls the latest scrobbled track. I built it to play around with a pretty simple API - the goal of which is to eventually learn some more mainstream API"
date: 2017-01-13
tags: [my2017, music]
comments: false
share: true
---

Yesterday I made a #nowplaying tracker powered by Last.fm's API. It looks at a user profile (mine - [@stalkadam](http://www.last.fm/user/stalkadam)) and pulls the latest "scrobbled" track.

A 'scrobble' is what last.fm calls a 'play'. A scrobbl*er* sends metadata - the name of artist, track name, album - to their servers. Once you've played 50% of the track, it triggers a public display of what you're listening to.

[This website](http://adamstoner.com/nowplaying) pulls my latest public scrobble and displays it on its own dedicated page. Cute, 'ey?

I built it to play around with a pretty simple API - the goal of which is to eventually learn some more mainstream API: Twitter, Facebook. In the lack of a #nowplaying function for my [old student radio station](http://toneradio.co.uk), I've let them borrow the code until they can work on something more permanent.

The tracker is 38 lines of [Babel](https://babeljs.io/) but, as usual, you can compile and compress it to one line of Javascript. All we do is request a JSON every second:

```javascript
class NowPlaying {
	constructor(opt) {
		this.el = opt.el
		this.url = `//ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=${opt.user}&api_key=${opt.apiKey}&format=json&limit=1`
	}
```

Then we parse it to pull the information we need - song name and artist - and format it.

```javascript
parse(json) {
    const track = json.recenttracks.track[0]
    const name = track.name
    const artist = track.artist['#text']

    const template =
      `<p class="recent-track__name">${name} by ${artist}`

    this.el.innerHTML = template
  }
```

You can [see the full code on Github](http://github.com/stalkadam/nowplaying) although I kindly ask you do not use my API key. You can [get your own here](http://www.last.fm/api).

In all honesty, I don't really see the value in Last.fm anymore. The service was all about discovery - music suggestions based on what you had been playing across your machine - but with so many people simply using Spotify or YouTube, each with their own discovery algorithms, Last.fm now seems somewhat redundant.

I see the value if you're an advertiser or a record label but not if you're a consumer - and without consumers, the value in the entire platform diminishes. It's that merciless nose-dive where social networks we were once loyal to suffer when something new supersedes them. (See also: Bebo, MSN, Digg, MySpace, Friendster. In ten years, Twitter, Snapchat...)

Nevertheless, for the foreseeable future, I'll be scrobbling my music to Last.fm, if only to see how well I built it. (Hopefully it doesn't out any guilty pleasures of mine...)

[Check it out here](http://adamstoner.com/nowplaying).


text:
XOS exposes a gRPC API, here is the guide to generate `.proto` files starting from `xproto` files.

## Considerations

The XOS data model is defined through `xProto` (you can read more on it [here](./xproto.md))
and services load their models at runtime, so the corresponding gRPC API is subject to changes.

There is a set of gRPC API that is stable and defined in [xos/coreapi/protos/utility.proto](https://github.com/opencord/xos/blob/master/xos/coreapi/protos/utility.proto)

The way we address this is to generate the proto files at runtime when a client connects.
You can find an example of this in the `xos-tosca` container, but here a short description of the workflow:

- Load the xProto files using the [GetXproto](https://github.com/opencord/xos/blob/master/xos/coreapi/protos/utility.proto#L100) rpc call
- Generate the `.proto` files using the [xosgenx](./xosgenx.md) toolchain with the [protoapi](https://github.com/opencord/xos/blob/master/lib/xos-genx/xosgenx/targets/protoapi.xtarget) .xtarget

> NOTE: if your are developing against a fixed version you don't need to do this

## Generate proto files

The models that XOS uses are spread in few places:

- core models are in the `xos` repo: [xos/core/models/core.xproto](https://github.com/opencord/xos/tree/master/xos/core/models/core.xproto)
- service models are in the service repo: `xos/synchronizer/models/<service-name>.xproto`

Once you have located the models you need and you have the [virtualenv](./unittest.html#setting-up-a-unit-testing-environment) installed,
you can use this command to generate the `.proto` files:

```bash
xosgenx --target=protoapi.xtarget --write-to-file=single --output=. --dest-file=xos.proto hippie-oss/xos/synchronizer/models/hippie-oss.xproto olt-service/xos/synchronizer/models/volt.xproto
```

> NOTE: in the above command we are passing two files to the `xproto` toolchain:
> `hippie-oss/xos/synchronizer/models/hippie-oss.xproto` and `olt-service/xos/synchronizer/models/volt.xproto`
> we are also storing the output in a file called `xos.proto` in the current workdir

After generating the `.proto` files you need to grab:

- xos/coreapi/protos/annotations.proto
- xos/coreapi/protos/common.proto
- xos/coreapi/protos/xosoptions.proto
- xos/coreapi/protos/http.proto

before generating code using the gRPC toolchain


text:
class Fhir::Base < ActiveRecord::Base
  self.table_name_prefix = 'fhir.'
  self.abstract_class = true
end


text:
package connect

import (
	context "context"
	reflect "reflect"

	gomock "github.com/golang/mock/gomock"
)

// MockConnect is a mock of Connect interface.
type MockConnect struct {
	ctrl     *gomock.Controller
	recorder *MockConnectMockRecorder
}

// MockConnectMockRecorder is the mock recorder for MockConnect.
type MockConnectMockRecorder struct {
	mock *MockConnect
}

// NewMockConnect creates a new mock instance.
func NewMockConnect(ctrl *gomock.Controller) *MockConnect {
	mock := &MockConnect{ctrl: ctrl}
	mock.recorder = &MockConnectMockRecorder{mock}
	return mock
}

// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockConnect) EXPECT() *MockConnectMockRecorder {
	return m.recorder
}

// Connect mocks base method.
func (m *MockConnect) Connect(arg0 context.Context, arg1 string, arg2 DestinationHash) (Destination, error) {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "Connect", arg0, arg1, arg2)
	ret0, _ := ret[0].(Destination)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

// Connect indicates an expected call of Connect.
func (mr *MockConnectMockRecorder) Connect(arg0, arg1, arg2 interface{}) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Connect", reflect.TypeOf((*MockConnect)(nil).Connect), arg0, arg1, arg2)
}

// MockDestination is a mock of Destination interface.
type MockDestination struct {
	ctrl     *gomock.Controller
	recorder *MockDestinationMockRecorder
}

// MockDestinationMockRecorder is the mock recorder for MockDestination.
type MockDestinationMockRecorder struct {
	mock *MockDestination
}

// NewMockDestination creates a new mock instance.
func NewMockDestination(ctrl *gomock.Controller) *MockDestination {
	mock := &MockDestination{ctrl: ctrl}
	mock.recorder = &MockDestinationMockRecorder{mock}
	return mock
}

// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockDestination) EXPECT() *MockDestinationMockRecorder {
	return m.recorder
}

// Close mocks base method.
func (m *MockDestination) Close() {
	m.ctrl.T.Helper()
	m.ctrl.Call(m, "Close")
}

// Close indicates an expected call of Close.
func (mr *MockDestinationMockRecorder) Close() *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockDestination)(nil).Close))
}

// SendChannel mocks base method.
func (m *MockDestination) SendChannel() chan<- SendRequest {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "SendChannel")
	ret0, _ := ret[0].(chan<- SendRequest)
	return ret0
}

// SendChannel indicates an expected call of SendChannel.
func (mr *MockDestinationMockRecorder) SendChannel() *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendChannel", reflect.TypeOf((*MockDestination)(nil).SendChannel))
}

// MockDestinationHash is a mock of DestinationHash interface.
type MockDestinationHash struct {
	ctrl     *gomock.Controller
	recorder *MockDestinationHashMockRecorder
}

// MockDestinationHashMockRecorder is the mock recorder for MockDestinationHash.
type MockDestinationHashMockRecorder struct {
	mock *MockDestinationHash
}

// NewMockDestinationHash creates a new mock instance.
func NewMockDestinationHash(ctrl *gomock.Controller) *MockDestinationHash {
	mock := &MockDestinationHash{ctrl: ctrl}
	mock.recorder = &MockDestinationHashMockRecorder{mock}
	return mock
}

// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockDestinationHash) EXPECT() *MockDestinationHashMockRecorder {
	return m.recorder
}

// ConnectionClosed mocks base method.
func (m *MockDestinationHash) ConnectionClosed() {
	m.ctrl.T.Helper()
	m.ctrl.Call(m, "ConnectionClosed")
}

// ConnectionClosed indicates an expected call of ConnectionClosed.
func (mr *MockDestinationHashMockRecorder) ConnectionClosed() *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConnectionClosed", reflect.TypeOf((*MockDestinationHash)(nil).ConnectionClosed))
}

// RemoveDestination mocks base method.
func (m *MockDestinationHash) RemoveDestination(arg0 string) {
	m.ctrl.T.Helper()
	m.ctrl.Call(m, "RemoveDestination", arg0)
}

// RemoveDestination indicates an expected call of RemoveDestination.
func (mr *MockDestinationHashMockRecorder) RemoveDestination(arg0 interface{}) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveDestination", reflect.TypeOf((*MockDestinationHash)(nil).RemoveDestination), arg0)
}


text:
#include "config.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>

#include "backtrace.h"
#include "internal.h"

#ifndef HAVE_GETEXECNAME
#define getexecname() NULL
#endif

/* Initialize the fileline information from the executable.  Returns 1
   on success, 0 on failure.  */

static int
fileline_initialize (struct backtrace_state *state,
		     backtrace_error_callback error_callback, void *data)
{
  int failed;
  fileline fileline_fn;
  int pass;
  int called_error_callback;
  int descriptor;

  failed = state->fileline_initialization_failed;

  if (state->threaded)
    {
      /* Use __sync_bool_compare_and_swap to do an atomic load.  */
      while (!__sync_bool_compare_and_swap
	     (&state->fileline_initialization_failed, failed, failed))
	failed = state->fileline_initialization_failed;
    }

  if (failed)
    {
      error_callback (data, "failed to read executable information", -1);
      return 0;
    }

  fileline_fn = state->fileline_fn;
  if (state->threaded)
    {
      while (!__sync_bool_compare_and_swap (&state->fileline_fn, fileline_fn,
					    fileline_fn))
	fileline_fn = state->fileline_fn;
    }
  if (fileline_fn != NULL)
    return 1;

  /* We have not initialized the information.  Do it now.  */

  descriptor = -1;
  called_error_callback = 0;
  for (pass = 0; pass < 4; ++pass)
    {
      const char *filename;
      int does_not_exist;

      switch (pass)
	{
	case 0:
	  filename = state->filename;
	  break;
	case 1:
	  filename = getexecname ();
	  break;
	case 2:
	  filename = "/proc/self/exe";
	  break;
	case 3:
	  filename = "/proc/curproc/file";
	  break;
	default:
	  abort ();
	}

      if (filename == NULL)
	continue;

      descriptor = backtrace_open (filename, error_callback, data,
				   &does_not_exist);
      if (descriptor < 0 && !does_not_exist)
	{
	  called_error_callback = 1;
	  break;
	}
      if (descriptor >= 0)
	break;
    }

  if (descriptor < 0)
    {
      if (!called_error_callback)
	{
	  if (state->filename != NULL)
	    error_callback (data, state->filename, ENOENT);
	  else
	    error_callback (data,
			    "libbacktrace could not find executable to open",
			    0);
	}
      failed = 1;
    }

  if (!failed)
    {
      if (!backtrace_initialize (state, descriptor, error_callback, data,
				 &fileline_fn))
	failed = 1;
    }

  if (failed)
    {
      if (!state->threaded)
	state->fileline_initialization_failed = 1;
      else
	__sync_bool_compare_and_swap (&state->fileline_initialization_failed,
				      0, failed);
      return 0;
    }

  if (!state->threaded)
    state->fileline_fn = fileline_fn;
  else
    {
      __sync_bool_compare_and_swap (&state->fileline_fn, NULL, fileline_fn);

      /* At this point we know that state->fileline_fn is not NULL.
	 Either we stored our value, or some other thread stored its
	 value.  If some other thread stored its value, we leak the
	 one we just initialized.  Either way, state->fileline_fn is
	 initialized.  The compare_and_swap is a full memory barrier,
	 so we should have full access to that value even if it was
	 created by another thread.  */
    }

  return 1;
}

/* Given a PC, find the file name, line number, and function name.  */

int
backtrace_pcinfo (struct backtrace_state *state, uintptr_t pc,
		  backtrace_full_callback callback,
		  backtrace_error_callback error_callback, void *data)
{
  if (!fileline_initialize (state, error_callback, data))
    return 0;

  if (state->fileline_initialization_failed)
    return 0;

  return state->fileline_fn (state, pc, callback, error_callback, data);
}

/* Given a PC, find the symbol for it, and its value.  */

int
backtrace_syminfo (struct backtrace_state *state, uintptr_t pc,
		   backtrace_syminfo_callback callback,
		   backtrace_error_callback error_callback, void *data)
{
  if (!fileline_initialize (state, error_callback, data))
    return 0;

  if (state->fileline_initialization_failed)
    return 0;

  state->syminfo_fn (state, pc, callback, error_callback, data);
  return 1;
}


text:
package com.github.wesleyegberto.message;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Message {
	private int code;
	private String message;

	public Message() {
	}

	public Message(int code, String message) {
		this.code = code;
		this.message = message;
	}

	public int getCode() {
		return code;
	}

	public String getMessage() {
		return message;
	}

	public static Message build(int code, String message) {
		return new Message(code, message);
	}
}


text:
from celeryutils import task
import commonware.log

from django.db.models.signals import post_save

from versions.models import Version, update_status
from apps.addons.models import version_changed
from apps.addons.signals import version_changed as version_changed_signal

task_log = commonware.log.getLogger('z.task')

# TODO(andym): remove this when versions all done.
@task(rate_limit='10/m')
def add_version_int(pks, **kw):
    task_log.info("[%d@%s] Adding version_int for versions staring at id=%d" %
                  (len(pks), add_version_int.rate_limit, pks[0]))

    version_changed_signal.disconnect(version_changed,
                                      dispatch_uid='version_changed')
    post_save.disconnect(update_status, sender=Version,
                         dispatch_uid='version_update_status')

    versions = Version.objects.filter(pk__in=pks)
    for version in versions:
        version.save()


text:
package com.github.dddpaul.connectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplicationBuilder parentBuilder = new SpringApplicationBuilder(Application.class);
        parentBuilder.child(ServiceOneConfiguration.class).properties("server.port:8081").run(args);
        parentBuilder.child(ServiceTwoConfiguration.class).properties("server.port:8082").run(args);
    }

    @Service
    static class SharedService {
        public String getMessage(String name) {
            return String.format("Hello, %s, I'm shared service", name);
        }
    }

    @Configuration
    @EnableAutoConfiguration
    static class ServiceOneConfiguration {
        @Controller
        @RequestMapping("/one")
        static class ControllerOne {
            @Autowired
            private SharedService service;

            @RequestMapping(produces = "text/plain;charset=utf-8")
            @ResponseBody
            public String getMessage(String name) {
                return "ControllerOne says \"" + service.getMessage(name) + "\"";
            }
        }
    }

    @Configuration
    @EnableAutoConfiguration
    static class ServiceTwoConfiguration {
        @Bean
        EmbeddedServletContainerFactory servletContainer() {
            TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
            tomcat.setUriEncoding("cp1251");
            return tomcat;
        }

        @Controller
        @RequestMapping("/two")
        static class ControllerTwo {
            @Autowired
            private SharedService service;

            @RequestMapping(produces = "text/plain;charset=utf-8")
            @ResponseBody
            public String getMessage(String name) {
                return "ControllerTwo says \"" + service.getMessage(name) + "\"";
            }
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="../dist/css/paper.min.css">
  <link rel="stylesheet" href="css/demo.css">

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
          Toggle navigation

        </button>

          <form role="form">

              Name
              <input type="email" class="form-control" id="exampleInputName" placeholder="Name">

              Email address
              <input type="email" class="form-control" id="exampleInputEmail" placeholder="Email">

              Password
              <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">

            <button type="submit" class="btn btn-success btn-block">Sign me up</button>
          </form>


text:
package consulo.diagram.builder;

import consulo.ui.image.Image;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.swing.*;

/**
 * @author VISTALL
 * @since 22:36/15.10.13
 */
public interface GraphBuilder {
  @Nonnull
  JComponent getComponent();

  @Nonnull
  <E> GraphNode<E> createNode(@Nonnull String name, @Nullable Image icon, @Nullable E value, GraphPositionStrategy strategy);
}


text:
(function() {
    "use strict";
    load("jstests/replsets/rslib.js");

    var st = new ShardingTest({shards: {rs0: {nodes: 2}}, mongos: 1});

    // Stop balancer to eliminate weird conn stuff
    st.stopBalancer();

    var mongos = st.s0;
    var coll = mongos.getCollection("foo.bar");
    var db = coll.getDB();

    // Test is not valid for Win32
    var is32Bits = (db.serverBuildInfo().bits == 32);
    if (is32Bits && _isWindows()) {
        // Win32 doesn't provide the polling interface we need to implement the check tested here
        jsTest.log("Test is not valid on Win32 platform.");

    } else {
        // Non-Win32 platform

        var primary = st.rs0.getPrimary();
        var secondary = st.rs0.getSecondary();

        jsTest.log("Creating new connections...");

        // Create a bunch of connections to the primary node through mongos.
        // jstest ->(x10)-> mongos ->(x10)-> primary
        var conns = [];
        for (var i = 0; i < 50; i++) {
            conns.push(new Mongo(mongos.host));
            conns[i].getCollection(coll + "").findOne();
        }

        jsTest.log("Returning the connections back to the pool.");

        for (var i = 0; i < conns.length; i++) {
            conns[i] = null;
        }
        // Make sure we return connections back to the pool
        gc();

        // Don't make test fragile by linking to format of shardConnPoolStats, but this is useful if
        // something goes wrong.
        var connPoolStats = mongos.getDB("admin").runCommand({shardConnPoolStats: 1});
        printjson(connPoolStats);

        jsTest.log("Stepdown primary and then step back up...");

        var stepDown = function(node, timeSecs) {
            var result = null;
            try {
                result = node.getDB("admin").runCommand({replSetStepDown: timeSecs, force: true});
                // Should not get here
            } catch (e) {
                printjson(e);
            }

            if (result != null)
                printjson(result);
            assert.eq(null, result);
        };

        stepDown(primary, 0);

        jsTest.log("Waiting for mongos to acknowledge stepdown...");

        awaitRSClientHosts(mongos,
                           secondary,
                           {ismaster: true},
                           st.rs0,
                           2 * 60 * 1000);  // slow hosts can take longer to recognize sd

        jsTest.log("Stepping back up...");

        stepDown(secondary, 10000);

        jsTest.log("Waiting for mongos to acknowledge step up...");

        awaitRSClientHosts(mongos, primary, {ismaster: true}, st.rs0, 2 * 60 * 1000);

        jsTest.log("Waiting for socket timeout time...");

        // Need to wait longer than the socket polling time.
        sleep(2 * 5000);

        jsTest.log("Run queries using new connections.");

        var numErrors = 0;
        for (var i = 0; i < conns.length; i++) {
            var newConn = new Mongo(mongos.host);
            try {
                printjson(newConn.getCollection("foo.bar").findOne());
            } catch (e) {
                printjson(e);
                numErrors++;
            }
        }

        assert.eq(0, numErrors);

    }  // End Win32 check

    jsTest.log("DONE!");

    st.stop();
}());


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace OpenHab.Wpf.ViewModel.Helper
{
    public static class EnumerableExtensions
    {
        [DebuggerStepThrough]
        public static void Each<T>(this IEnumerable<T> self, Action<T> action)
        {
            foreach (var item in self) action(item);
        }

        [DebuggerStepThrough]
        public static bool IsNullOrEmpty<T>(this IEnumerable<T> self)
        {
            return self == null || self.IsEmpty();
        }

        [DebuggerStepThrough]
        public static bool IsEmpty<T>(this IEnumerable<T> self)
        {
            return !self.Any();
        }

        [DebuggerStepThrough]
        public static T[] EnumToArray<T>()
        {
            return (T[])Enum.GetValues(typeof(T));
        }
    }
}


text:
import { EventEmitter, Injectable, Output } from '@angular/core';

import { App } from '../app/app';
import { isPresent } from '../../util/util';
import { NavOptions } from '../nav/nav-interfaces';
import { PickerCmp } from './picker-component';
import { PickerOptions, PickerColumn } from './picker-options';
import { ViewController } from '../nav/view-controller';

/**
 * @private
 */
export class Picker extends ViewController {
  private _app: App;

  @Output() ionChange: EventEmitter<any>;

  constructor(app: App, opts: PickerOptions = {}) {
    opts.columns = opts.columns || [];
    opts.buttons = opts.buttons || [];
    opts.enableBackdropDismiss = isPresent(opts.enableBackdropDismiss) ? !!opts.enableBackdropDismiss : true;

    super(PickerCmp, opts);
    this._app = app;
    this.isOverlay = true;

    this.ionChange = new EventEmitter<any>();

    // by default, pickers should not fire lifecycle events of other views
    // for example, when an picker enters, the current active view should
    // not fire its lifecycle events because it's not conceptually leaving
    this.fireOtherLifecycles = false;
  }

  /**
  * @private
  */
  getTransitionName(direction: string) {
    let key = (direction === 'back' ? 'pickerLeave' : 'pickerEnter');
    return this._nav && this._nav.config.get(key);
  }

  /**
   * @param {any} button Picker toolbar button
   */
  addButton(button: any) {
    this.data.buttons.push(button);
  }

  /**
   * @param {any} button Picker toolbar button
   */
  addColumn(column: PickerColumn) {
    this.data.columns.push(column);
  }

  getColumns(): PickerColumn[] {
    return this.data.columns;
  }

  refresh() {
    this.instance.refresh && this.instance.refresh();
  }

  /**
   * @param {string} cssClass CSS class name to add to the picker's outer wrapper.
   */
  setCssClass(cssClass: string) {
    this.data.cssClass = cssClass;
  }

  /**
   * Present the picker instance.
   *
   * @param {NavOptions} [opts={}] Nav options to go with this transition.
   * @returns {Promise} Returns a promise which is resolved when the transition has completed.
   */
  present(navOptions: NavOptions = {}) {
    return this._app.present(this, navOptions);
  }

  /**
   * @private
   * DEPRECATED: Please inject PickerController instead
   */
  private static create(opt: any) {
    // deprecated warning: added beta.11 2016-06-27
    console.warn('Picker.create(..) has been deprecated. Please inject PickerController instead');
  }

}

/**
 * @private
 * @name PickerController
 * @description
 *
 */
@Injectable()
export class PickerController {

  constructor(private _app: App) {}

  /**
   * Open a picker.
   */
  create(opts: PickerOptions = {}): Picker {
    return new Picker(this._app, opts);
  }

}


text:
<?php

/**
 * ckObjectWrapper provides methods to wrap objects, so they can be included in a SOAP response,
 * and provides methods to unwrap objects, if they are loaded from a SOAP request.
 *
 * @package    ckWebServicePlugin
 * @subpackage adapter
 * @author     Christian Kerl <christian-kerl@web.de>
 */
abstract class ckObjectWrapper
{
  const MODE_WRAP = 1;
  const MODE_UNWRAP = 2;

  protected static $wrappers = array();

  /**
   * Prepends a given ckObjectWrapper object to the registry list.
   *
   * @param ckObjectWrapper $wrapper A ckObjectWrapper instance
   */
  public static function addObjectWrapper(ckObjectWrapper $wrapper)
  {
    array_unshift(self::$wrappers, $wrapper);
  }

  /**
   * Gets a ckObjectWrapper, which can be used to wrap a given object with the given wrap mode.
   *
   * @param $object The object to wrap.
   * @param $mode The wrap mode.
   *
   * @return ckObjectWrapper The ckObjectWrapper, which can be used to wrap the object
   */
  protected static function getObjectWrapper($object, $mode)
  {
    foreach(self::$wrappers as $wrapper)
    {
      if(($mode == self::MODE_WRAP && $wrapper->canWrap($object)) || ($mode == self::MODE_UNWRAP && $wrapper->canUnwrap($object)))
      {
        return $wrapper;
      }
    }

    throw new RuntimeException('NoObjectWrapperFoundException');
  }

  /**
   * Wraps a given object so it can be included in a SOAP response.
   *
   * @param $object The plain object to wrap
   *
   * @return mixed The wrapped version of the given object, processable by the SOAP server
   */
  public static function wrap($object)
  {
    return self::getObjectWrapper($object, self::MODE_WRAP)->wrapObject($object);
  }

  /**
   * Unwraps a given object, which was loaded from a SOAP request.
   *
   * @param $object The wrapped object from a SOAP request
   *
   * @return mixed The plain object
   */
  public static function unwrap($object)
  {
    return self::getObjectWrapper($object, self::MODE_UNWRAP)->unwrapObject($object);
  }

  /**
   * Checks if the ckObjectWrapper can be used to wrap the given object.
   *
   * @param $object The object to wrap
   *
   * @return bool True, if the ckObjectWrapper can be used to wrap the given object, false otherwise
   */
  public abstract function canWrap($object);

  /**
   * Checks if the ckObjectWrapper can be used to unwrap the given object.
   *
   * @param $object The object to unwrap
   *
   * @return bool True, if the ckObjectWrapper can be used to unwrap the given object, false otherwise
   */
  public abstract function canUnwrap($object);

  /**
   * Wraps a given object.
   *
   * @param $object The object to wrap
   *
   * @return mixed The wrapped object
   */
  public abstract function wrapObject($object);

  /**
   * Unwraps a given object.
   *
   * @param $object The object to unwrap
   *
   * @return mixed The unwrapped object
   */
  public abstract function unwrapObject($object);
}


text:
from django.contrib import admin

from .models import BootstrapForm, BootstrapFormResponses

class BootstrapFormResponsesInline(admin.TabularInline):
    model = BootstrapFormResponses
    extra = 0
    can_delete = False
    readonly_fields = ('created', 'data', )

class BootstrapFormAdmin(admin.ModelAdmin):
    inlines = [
        BootstrapFormResponsesInline,
    ]

admin.site.register(BootstrapForm, BootstrapFormAdmin)


text:
<?php

class RSS
{
	public function parse ( $url )
	{
		$result = CURL::run( $url );

		if ( !$result )
			throw new Exception( 'Invalid result.' );

		$result = new SimpleXMLElement( $result );

		if ( !$result || empty( $result->channel ) )
			throw new Exception( 'Invalid XML format.' );

		$items = array();
		foreach ( $result->channel->item as $item )
			$items[] = $item;
		return $items;
	}
}


text:
require 'spec_helper'

class Scripter::IterationHistoryTestable
  include Scripter::IterationHistory
  attr_accessor :use_cache
end

class Scripter::IterationHistoryTestable2
  include Scripter::IterationHistory
  attr_accessor :use_cache
end

describe Scripter::IterationHistory do
  before(:each) do
    @it = Scripter::IterationHistoryTestable.new
    @it.use_cache = true
  end

  it "should be able to set custom cache store" do
    @it.cache_store = 'My custom cache_store'
    expect(@it.cache_store).to eq 'My custom cache_store'
  end

  describe "#iteration_processed! and #iteration_processed?" do
    it "should share cache between instances of the same class" do
      expect(@it.iteration_processed?(1)).to be false

      another_it = Scripter::IterationHistoryTestable.new
      another_it.iteration_processed!(1)

      expect(@it.iteration_processed?(1)).to be true
    end

    it "should not share cache between instances of different classes" do
      expect(@it.iteration_processed?(1)).to be false

      another_class_it = Scripter::IterationHistoryTestable2.new
      another_class_it.use_cache = true
      another_class_it.iteration_processed!(1)

      expect(another_class_it.iteration_processed?(1)).to be true
      expect(@it.iteration_processed?(1)).to be false
    end

    it "should remember results for 24 hours" do
      @it.iteration_processed!(1)
      expect(@it.iteration_processed?(1)).to be true

      Timecop.travel(Time.now + 24.hours) do
        expect(@it.iteration_processed?(1)).to be false
      end
    end

    it "should be different for different iteration_id" do
      expect(@it.iteration_processed?(1)).to be false
      expect(@it.iteration_processed?(2)).to be false
      @it.iteration_processed!(1)
      expect(@it.iteration_processed?(1)).to be true
      expect(@it.iteration_processed?(2)).to be false
    end

    it "should always be unprocessed if #use_cache is false" do
      @it.use_cache = false
      expect(@it.iteration_processed?(1)).to be false
      @it.iteration_processed!(1)
      expect(@it.iteration_processed?(1)).to be false
    end
  end

end


text:
*by <%= author %>*

<%= description %>

## Dependencies

* [pygments](http://pygments.org/) ([Docco documentation](http://jashkenas.github.com/docco/))
* [Yeoman](http://yeoman.io) (Building)
<% if (coverage) { %>
* [jscoverage](https://github.com/visionmedia/node-jscoverage) (Code coverage, docs)
<% } %>
<% if (mit) { %>

## License

MIT
<% } %>


text:
/* $Id: pjsua2_demo.cpp 5313 2016-05-24 07:13:44Z nanang $ */
/*
 * Copyright (C) 2008-2013 Teluu Inc. (http://www.teluu.com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#include <pjsua2.hpp>
#include <iostream>
#include <memory>
#include <pj/file_access.h>

#define THIS_FILE 	"pjsua2_demo.cpp"

using namespace pj;

class MyAccount;

class MyCall : public Call
{
private:
    MyAccount *myAcc;

public:
    MyCall(Account &acc, int call_id = PJSUA_INVALID_ID)
    : Call(acc, call_id)
    {
        myAcc = (MyAccount *)&acc;
    }

    virtual void onCallState(OnCallStateParam &prm);
};

class MyAccount : public Account
{
public:
    std::vector<Call *> calls;

public:
    MyAccount()
    {}

    ~MyAccount()
    {
        std::cout << "*** Account is being deleted: No of calls="
                  << calls.size() << std::endl;
    }

    void removeCall(Call *call)
    {
        for (std::vector<Call *>::iterator it = calls.begin();
             it != calls.end(); ++it)
        {
            if (*it == call) {
                calls.erase(it);
                break;
            }
        }
    }

    virtual void onRegState(OnRegStateParam &prm)
    {
	AccountInfo ai = getInfo();
	std::cout << (ai.regIsActive? "*** Register: code=" : "*** Unregister: code=")
		  << prm.code << std::endl;
    }

    virtual void onIncomingCall(OnIncomingCallParam &iprm)
    {
        Call *call = new MyCall(*this, iprm.callId);
        CallInfo ci = call->getInfo();
        CallOpParam prm;

        std::cout << "*** Incoming Call: " <<  ci.remoteUri << " ["
                  << ci.stateText << "]" << std::endl;

        calls.push_back(call);
        prm.statusCode = (pjsip_status_code)200;
        call->answer(prm);
    }
};

void MyCall::onCallState(OnCallStateParam &prm)
{
    PJ_UNUSED_ARG(prm);

    CallInfo ci = getInfo();
    std::cout << "*** Call: " <<  ci.remoteUri << " [" << ci.stateText
              << "]" << std::endl;

    if (ci.state == PJSIP_INV_STATE_DISCONNECTED) {
        myAcc->removeCall(this);
        /* Delete the call */
        delete this;
    }
}

static void mainProg1(Endpoint &ep) throw(Error)
{
    // Init library
    EpConfig ep_cfg;
    ep_cfg.logConfig.level = 4;
    ep.libInit( ep_cfg );

    // Transport
    TransportConfig tcfg;
    tcfg.port = 5060;
    ep.transportCreate(PJSIP_TRANSPORT_UDP, tcfg);

    // Start library
    ep.libStart();
    std::cout << "*** PJSUA2 STARTED ***" << std::endl;

    // Add account
    AccountConfig acc_cfg;
    acc_cfg.idUri = "sip:test1@pjsip.org";
    acc_cfg.regConfig.registrarUri = "sip:pjsip.org";
    acc_cfg.sipConfig.authCreds.push_back( AuthCredInfo("digest", "*",
                                                        "test1", 0, "test1") );
    std::auto_ptr<MyAccount> acc(new MyAccount);
    acc->create(acc_cfg);

    pj_thread_sleep(2000);

    // Make outgoing call
    Call *call = new MyCall(*acc);
    acc->calls.push_back(call);
    CallOpParam prm(true);
    prm.opt.audioCount = 1;
    prm.opt.videoCount = 0;
    call->makeCall("sip:test1@pjsip.org", prm);

    // Hangup all calls
    pj_thread_sleep(8000);
    ep.hangupAllCalls();
    pj_thread_sleep(4000);

    // Destroy library
    std::cout << "*** PJSUA2 SHUTTING DOWN ***" << std::endl;
}

static void mainProg2() throw(Error)
{
    string json_str;
    {
	EpConfig epCfg;
	JsonDocument jDoc;

	epCfg.uaConfig.maxCalls = 61;
	epCfg.uaConfig.userAgent = "Just JSON Test";
	epCfg.uaConfig.stunServer.push_back("stun1.pjsip.org");
	epCfg.uaConfig.stunServer.push_back("stun2.pjsip.org");
	epCfg.logConfig.filename = "THE.LOG";

	jDoc.writeObject(epCfg);
	json_str = jDoc.saveString();
	std::cout << json_str << std::endl << std::endl;
    }

    {
	EpConfig epCfg;
	JsonDocument rDoc;
	string output;

	rDoc.loadString(json_str);
	rDoc.readObject(epCfg);

	JsonDocument wDoc;

	wDoc.writeObject(epCfg);
	json_str = wDoc.saveString();
	std::cout << json_str << std::endl << std::endl;

	wDoc.saveFile("jsontest.js");
    }

    {
	EpConfig epCfg;
	JsonDocument rDoc;

	rDoc.loadFile("jsontest.js");
	rDoc.readObject(epCfg);
	pj_file_delete("jsontest.js");
    }
}

static void mainProg3(Endpoint &ep) throw(Error)
{
    const char *paths[] = { "../../../../tests/pjsua/wavs/input.16.wav",
			    "../../tests/pjsua/wavs/input.16.wav",
			    "input.16.wav"};
    unsigned i;
    const char *filename = NULL;

    // Init library
    EpConfig ep_cfg;
    ep.libInit( ep_cfg );

    for (i=0; i<PJ_ARRAY_SIZE(paths); ++i) {
       if (pj_file_exists(paths[i])) {
          filename = paths[i];
          break;
       }
    }

    if (!filename) {
	PJSUA2_RAISE_ERROR3(PJ_ENOTFOUND, "mainProg3()",
			   "Could not locate input.16.wav");
    }

    // Start library
    ep.libStart();
    std::cout << "*** PJSUA2 STARTED ***" << std::endl;

    // Create player and recorder
    {
	AudioMediaPlayer amp;
	amp.createPlayer(filename);

	AudioMediaRecorder amr;
	amr.createRecorder("recorder_test_output.wav");

	amp.startTransmit(ep.audDevManager().getPlaybackDevMedia());
	amp.startTransmit(amr);

	pj_thread_sleep(5000);
    }
}

static void mainProg() throw(Error)
{
    string json_str;

    {
	JsonDocument jdoc;
	AccountConfig accCfg;

	accCfg.idUri = "\"Just Test\" <sip:test@pjsip.org>";
	accCfg.regConfig.registrarUri = "sip:pjsip.org";
	SipHeader h;
	h.hName = "X-Header";
	h.hValue = "User header";
	accCfg.regConfig.headers.push_back(h);

	accCfg.sipConfig.proxies.push_back("<sip:sip.pjsip.org;transport=tcp>");
	accCfg.sipConfig.proxies.push_back("<sip:sip.pjsip.org;transport=tls>");

	accCfg.mediaConfig.transportConfig.tlsConfig.ciphers.push_back(1);
	accCfg.mediaConfig.transportConfig.tlsConfig.ciphers.push_back(2);
	accCfg.mediaConfig.transportConfig.tlsConfig.ciphers.push_back(3);

	AuthCredInfo aci;
	aci.scheme = "digest";
	aci.username = "test";
	aci.data = "passwd";
	aci.realm = "*";
	accCfg.sipConfig.authCreds.push_back(aci);

	jdoc.writeObject(accCfg);
	json_str = jdoc.saveString();
	std::cout << "Original:" << std::endl;
	std::cout << json_str << std::endl << std::endl;
    }

    {
	JsonDocument rdoc;

	rdoc.loadString(json_str);
	AccountConfig accCfg;
	rdoc.readObject(accCfg);

	JsonDocument wdoc;
	wdoc.writeObject(accCfg);
	json_str = wdoc.saveString();

	std::cout << "Parsed:" << std::endl;
	std::cout << json_str << std::endl << std::endl;
    }
}

static void mainProg4(Endpoint &ep) throw(Error)
{
    // Init library
    EpConfig ep_cfg;
    ep.libInit( ep_cfg );

    // Create transport
    TransportConfig tcfg;
    tcfg.port = 5060;
    ep.transportCreate(PJSIP_TRANSPORT_UDP, tcfg);
    ep.transportCreate(PJSIP_TRANSPORT_TCP, tcfg);

    // Add account
    AccountConfig acc_cfg;
    acc_cfg.idUri = "sip:localhost";
    std::auto_ptr<MyAccount> acc(new MyAccount);
    acc->create(acc_cfg);

    // Start library
    ep.libStart();
    std::cout << "*** PJSUA2 STARTED ***" << std::endl;

    // Just wait for ENTER key
    std::cout << "Press ENTER to quit..." << std::endl;
    std::cin.get();
}

int main()
{
    int ret = 0;
    Endpoint ep;

    try {
	ep.libCreate();

	mainProg4(ep);
	ret = PJ_SUCCESS;
    } catch (Error & err) {
	std::cout << "Exception: " << err.info() << std::endl;
	ret = 1;
    }

    try {
	ep.libDestroy();
    } catch(Error &err) {
	std::cout << "Exception: " << err.info() << std::endl;
	ret = 1;
    }

    if (ret == PJ_SUCCESS) {
	std::cout << "Success" << std::endl;
    } else {
	std::cout << "Error Found" << std::endl;
    }

    return ret;
}


text:
<% extends 'layouts/default.html' %>
<% block title %><<site_name>> | Remove Post type? <% endblock %>

<% block content %>

<< site_name >> Change

Create a new Post Type

    <form action="/admin/delete/post_types/<< slug >>" method="POST">

 Confirm removal of Post type with slug << slug >> ?

      <button class="button-primary" type="submit">Remove post type</button>
    </form>

<% endblock %>


text:
=========
 Usage
=========

To use oslo.utils in a project, import the individual module you
need. For example::

	from oslo_utils import strutils

    slug = strutils.to_slug('input value')


text:
package dmax.dialog;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.StringRes;
import android.support.annotation.StyleRes;
import android.view.View;
import android.widget.TextView;

/**
 * Created by Maxim Dybarsky | maxim.dybarskyy@gmail.com
 * on 13.01.15 at 14:22
 */
public class SpotsDialog extends AlertDialog {

    public static class Builder {

        private Context context;
        private String message;
        private int messageId;
        private int themeId;
        private boolean cancelable = true; // default dialog behaviour
        private OnCancelListener cancelListener;

        public Builder setContext(Context context) {
            this.context = context;
            return this;
        }

        public Builder setMessage(String message) {
            this.message = message;
            return this;
        }

        public Builder setMessage(@StringRes int messageId) {
            this.messageId = messageId;
            return this;
        }

        public Builder setTheme(@StyleRes int themeId) {
            this.themeId = themeId;
            return this;
        }

        public Builder setCancelable(boolean cancelable) {
            this.cancelable = cancelable;
            return this;
        }

        public Builder setCancelListener(OnCancelListener cancelListener) {
            this.cancelListener = cancelListener;
            return this;
        }

        public AlertDialog build() {
            return new SpotsDialog(
                    context,
                    messageId != 0 ? context.getString(messageId) : message,
                    themeId != 0 ? themeId : R.style.SpotsDialogDefault,
                    cancelable,
                    cancelListener
            );
        }
    }

    private static final int DELAY = 150;
    private static final int DURATION = 1500;

    private int size;
    private AnimatedView[] spots;
    private AnimatorPlayer animator;
    private CharSequence message;

    private SpotsDialog(Context context, String message, int theme, boolean cancelable, OnCancelListener cancelListener) {
        super(context, theme);
        this.message = message;

        setCancelable(cancelable);
        if (cancelListener != null) setOnCancelListener(cancelListener);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.dmax_spots_dialog);
        setCanceledOnTouchOutside(false);

        initMessage();
        initProgress();
    }

    @Override
    protected void onStart() {
        super.onStart();

        for (AnimatedView view : spots) view.setVisibility(View.VISIBLE);

        animator = new AnimatorPlayer(createAnimations());
        animator.play();
    }

    @Override
    protected void onStop() {
        super.onStop();

        animator.stop();
    }

    @Override
    public void setMessage(CharSequence message) {
        this.message = message;
        if (isShowing()) initMessage();
    }

    //~

    private void initMessage() {
        if (message != null && message.length() > 0) {
            ((TextView) findViewById(R.id.dmax_spots_title)).setText(message);
        }
    }

    private void initProgress() {
        ProgressLayout progress = findViewById(R.id.dmax_spots_progress);
        size = progress.getSpotsCount();

        spots = new AnimatedView[size];
        int size = getContext().getResources().getDimensionPixelSize(R.dimen.spot_size);
        int progressWidth = getContext().getResources().getDimensionPixelSize(R.dimen.progress_width);
        for (int i = 0; i < spots.length; i++) {
            AnimatedView v = new AnimatedView(getContext());
            v.setBackgroundResource(R.drawable.dmax_spots_spot);
            v.setTarget(progressWidth);
            v.setXFactor(-1f);
            v.setVisibility(View.INVISIBLE);
            progress.addView(v, size, size);
            spots[i] = v;
        }
    }

    private Animator[] createAnimations() {
        Animator[] animators = new Animator[size];
        for (int i = 0; i < spots.length; i++) {
            final AnimatedView animatedView = spots[i];
            Animator move = ObjectAnimator.ofFloat(animatedView, "xFactor", 0, 1);
            move.setDuration(DURATION);
            move.setInterpolator(new HesitateInterpolator());
            move.setStartDelay(DELAY * i);
            move.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    animatedView.setVisibility(View.INVISIBLE);
                }

                @Override
                public void onAnimationStart(Animator animation) {
                    animatedView.setVisibility(View.VISIBLE);
                }
            });
            animators[i] = move;
        }
        return animators;
    }
}


text:
<?php
namespace Menus\Model\Entity;

use Cake\ORM\Entity;

/**
 * Menu Entity.
 *
 * @property int $id
 * @property int $status
 * @property string $language
 * @property string $alias
 * @property \Cake\I18n\Time $modified
 * @property \Cake\I18n\Time $created
 */
class Menu extends Entity
{

    /**
     * Fields that can be mass assigned using newEntity() or patchEntity().
     *
     * Note that when '*' is set to true, this allows all unspecified fields to
     * be mass assigned. For security purposes, it is advised to set '*' to false
     * (or remove it), and explicitly make individual fields accessible as needed.
     *
     * @var array
     */
    protected $_accessible = [
        '*' => true,
        'id' => false,
    ];
}