text:
package org.elasticsearch.xpack.search;

import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.OriginalIndices;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchShard;
import org.elasticsearch.action.search.ShardSearchFailure;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.search.aggregations.InternalAggregations;
import org.elasticsearch.search.internal.InternalSearchResponse;
import org.elasticsearch.tasks.TaskId;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.client.NoOpClient;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.xpack.core.async.AsyncExecutionId;
import org.elasticsearch.xpack.core.search.action.AsyncSearchResponse;
import org.junit.After;
import org.junit.Before;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;

public class AsyncSearchTaskTests extends ESTestCase {
    private ThreadPool threadPool;

    @Before
    public void beforeTest() {
        threadPool = new TestThreadPool(getTestName());
    }

    @After
    public void afterTest() {
        threadPool.shutdownNow();
    }

    private AsyncSearchTask createAsyncSearchTask() {
        return new AsyncSearchTask(0L, "", "", new TaskId("node1", 0), () -> false, TimeValue.timeValueHours(1),
            Collections.emptyMap(), Collections.emptyMap(), new AsyncExecutionId("0", new TaskId("node1", 1)),
            new NoOpClient(threadPool), threadPool, null);
    }

    public void testWaitForInit() throws InterruptedException {
        AsyncSearchTask task = new AsyncSearchTask(0L, "", "", new TaskId("node1", 0), () -> false, TimeValue.timeValueHours(1),
            Collections.emptyMap(), Collections.emptyMap(), new AsyncExecutionId("0", new TaskId("node1", 1)),
            new NoOpClient(threadPool), threadPool, null);
        int numShards = randomIntBetween(0, 10);
        List<SearchShard> shards = new ArrayList<>();
        for (int i = 0; i < numShards; i++) {
            shards.add(new SearchShard(null, new ShardId("0", "0", 1)));
        }
        List<SearchShard> skippedShards = new ArrayList<>();
        int numSkippedShards = randomIntBetween(0, 10);
        for (int i = 0; i < numSkippedShards; i++) {
            skippedShards.add(new SearchShard(null, new ShardId("0", "0", 1)));
        }

        int numThreads = randomIntBetween(1, 10);
        CountDownLatch latch = new CountDownLatch(numThreads);
        for (int i = 0; i < numThreads; i++) {
            Thread thread = new Thread(() -> task.addCompletionListener(new ActionListener<>() {
                @Override
                public void onResponse(AsyncSearchResponse resp) {
                    assertThat(numShards + numSkippedShards, equalTo(resp.getSearchResponse().getTotalShards()));
                    assertThat(numSkippedShards, equalTo(resp.getSearchResponse().getSkippedShards()));
                    assertThat(0, equalTo(resp.getSearchResponse().getFailedShards()));
                    latch.countDown();
                }

                @Override
                public void onFailure(Exception e) {
                    throw new AssertionError(e);

                }
            }, TimeValue.timeValueMillis(1)));
            thread.start();
        }
        assertFalse(latch.await(numThreads*2, TimeUnit.MILLISECONDS));
        task.getSearchProgressActionListener().onListShards(shards, skippedShards, SearchResponse.Clusters.EMPTY, false);
        latch.await();
    }

    public void testWithFailure() throws InterruptedException {
        AsyncSearchTask task = createAsyncSearchTask();
        int numThreads = randomIntBetween(1, 10);
        CountDownLatch latch = new CountDownLatch(numThreads);
        for (int i = 0; i < numThreads; i++) {
            Thread thread = new Thread(() -> task.addCompletionListener(new ActionListener<>() {
                @Override
                public void onResponse(AsyncSearchResponse resp) {
                    assertNull(resp.getSearchResponse());
                    assertNotNull(resp.getFailure());
                    assertTrue(resp.isPartial());
                    latch.countDown();
                }

                @Override
                public void onFailure(Exception e) {
                    throw new AssertionError(e);
                }
            }, TimeValue.timeValueMillis(1)));
            thread.start();
        }
        assertFalse(latch.await(numThreads*2, TimeUnit.MILLISECONDS));
        task.getSearchProgressActionListener().onFailure(new Exception("boom"));
        latch.await();
    }

    public void testWaitForCompletion() throws InterruptedException {
        AsyncSearchTask task = createAsyncSearchTask();
        int numShards = randomIntBetween(0, 10);
        List<SearchShard> shards = new ArrayList<>();
        for (int i = 0; i < numShards; i++) {
            shards.add(new SearchShard(null, new ShardId("0", "0", 1)));
        }
        List<SearchShard> skippedShards = new ArrayList<>();
        int numSkippedShards = randomIntBetween(0, 10);
        for (int i = 0; i < numSkippedShards; i++) {
            skippedShards.add(new SearchShard(null, new ShardId("0", "0", 1)));
        }
        int totalShards = numShards + numSkippedShards;
        task.getSearchProgressActionListener().onListShards(shards, skippedShards, SearchResponse.Clusters.EMPTY, false);
        for (int i = 0; i < numShards; i++) {
            task.getSearchProgressActionListener().onPartialReduce(shards.subList(i, i+1),
                new TotalHits(0, TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO), null, 0);
            assertCompletionListeners(task, totalShards, 1 + numSkippedShards, numSkippedShards, 0, true);
        }
        task.getSearchProgressActionListener().onFinalReduce(shards,
            new TotalHits(0, TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO), null, 0);
        assertCompletionListeners(task, totalShards, totalShards, numSkippedShards, 0, true);
        ((AsyncSearchTask.Listener)task.getProgressListener()).onResponse(
            newSearchResponse(totalShards, totalShards, numSkippedShards));
        assertCompletionListeners(task, totalShards, totalShards, numSkippedShards, 0, false);
    }

    public void testWithFetchFailures() throws InterruptedException {
        AsyncSearchTask task = createAsyncSearchTask();
        int numShards = randomIntBetween(2, 10);
        List<SearchShard> shards = new ArrayList<>();
        for (int i = 0; i < numShards; i++) {
            shards.add(new SearchShard(null, new ShardId("0", "0", 1)));
        }
        List<SearchShard> skippedShards = new ArrayList<>();
        int numSkippedShards = randomIntBetween(0, 10);
        for (int i = 0; i < numSkippedShards; i++) {
            skippedShards.add(new SearchShard(null, new ShardId("0", "0", 1)));
        }
        int totalShards = numShards + numSkippedShards;
        task.getSearchProgressActionListener().onListShards(shards, skippedShards, SearchResponse.Clusters.EMPTY, false);
        for (int i = 0; i < numShards; i++) {
            task.getSearchProgressActionListener().onPartialReduce(shards.subList(i, i+1),
                new TotalHits(0, TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO), null, 0);
            assertCompletionListeners(task, totalShards, 1 + numSkippedShards, numSkippedShards, 0, true);
        }
        task.getSearchProgressActionListener().onFinalReduce(shards,
            new TotalHits(0, TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO), null, 0);
        int numFetchFailures = randomIntBetween(1, numShards - 1);
        ShardSearchFailure[] shardSearchFailures = new ShardSearchFailure[numFetchFailures];
        for (int i = 0; i < numFetchFailures; i++) {
            IOException failure = new IOException("boum");
            task.getSearchProgressActionListener().onFetchFailure(i,
                new SearchShardTarget("0", new ShardId("0", "0", 1), null, OriginalIndices.NONE),
                failure);
            shardSearchFailures[i] = new ShardSearchFailure(failure);
        }
        assertCompletionListeners(task, totalShards, totalShards, numSkippedShards, numFetchFailures, true);
        ((AsyncSearchTask.Listener)task.getProgressListener()).onResponse(
            newSearchResponse(totalShards, totalShards - numFetchFailures, numSkippedShards, shardSearchFailures));
        assertCompletionListeners(task, totalShards, totalShards - numFetchFailures, numSkippedShards, numFetchFailures, false);
    }

    public void testFatalFailureDuringFetch() throws InterruptedException {
        AsyncSearchTask task = createAsyncSearchTask();
        int numShards = randomIntBetween(0, 10);
        List<SearchShard> shards = new ArrayList<>();
        for (int i = 0; i < numShards; i++) {
            shards.add(new SearchShard(null, new ShardId("0", "0", 1)));
        }
        List<SearchShard> skippedShards = new ArrayList<>();
        int numSkippedShards = randomIntBetween(0, 10);
        for (int i = 0; i < numSkippedShards; i++) {
            skippedShards.add(new SearchShard(null, new ShardId("0", "0", 1)));
        }
        int totalShards = numShards + numSkippedShards;
        task.getSearchProgressActionListener().onListShards(shards, skippedShards, SearchResponse.Clusters.EMPTY, false);
        for (int i = 0; i < numShards; i++) {
            task.getSearchProgressActionListener().onPartialReduce(shards.subList(0, i+1),
                new TotalHits(0, TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO), null, 0);
            assertCompletionListeners(task, totalShards, i + 1 + numSkippedShards, numSkippedShards, 0, true);
        }
        task.getSearchProgressActionListener().onFinalReduce(shards,
            new TotalHits(0, TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO), null, 0);
        for (int i = 0; i < numShards; i++) {
            task.getSearchProgressActionListener().onFetchFailure(i,
                new SearchShardTarget("0", new ShardId("0", "0", 1), null, OriginalIndices.NONE),
                new IOException("boum"));
        }
        assertCompletionListeners(task, totalShards, totalShards, numSkippedShards, numShards, true);
        ((AsyncSearchTask.Listener)task.getProgressListener()).onFailure(new IOException("boum"));
        assertCompletionListeners(task, totalShards, totalShards, numSkippedShards, numShards, true);
    }

    private static SearchResponse newSearchResponse(int totalShards, int successfulShards, int skippedShards,
            ShardSearchFailure... failures) {
        InternalSearchResponse response = new InternalSearchResponse(SearchHits.empty(),
            InternalAggregations.EMPTY, null, null, false, null, 1);
        return new SearchResponse(response, null, totalShards, successfulShards, skippedShards,
            100, failures, SearchResponse.Clusters.EMPTY);
    }

    private static void assertCompletionListeners(AsyncSearchTask task,
                                           int expectedTotalShards,
                                           int expectedSuccessfulShards,
                                           int expectedSkippedShards,
                                           int expectedShardFailures,
                                           boolean isPartial) throws InterruptedException {
        int numThreads = randomIntBetween(1, 10);
        CountDownLatch latch = new CountDownLatch(numThreads);
        for (int i = 0; i < numThreads; i++) {
            Thread thread = new Thread(() -> task.addCompletionListener(new ActionListener<>() {
                @Override
                public void onResponse(AsyncSearchResponse resp) {
                    assertThat(resp.getSearchResponse().getTotalShards(), equalTo(expectedTotalShards));
                    assertThat(resp.getSearchResponse().getSuccessfulShards(), equalTo(expectedSuccessfulShards));
                    assertThat(resp.getSearchResponse().getSkippedShards(), equalTo(expectedSkippedShards));
                    assertThat(resp.getSearchResponse().getFailedShards(), equalTo(expectedShardFailures));
                    assertThat(resp.isPartial(), equalTo(isPartial));
                    if (expectedShardFailures > 0) {
                        assertThat(resp.getSearchResponse().getShardFailures().length, equalTo(expectedShardFailures));
                        for (ShardSearchFailure failure : resp.getSearchResponse().getShardFailures()) {
                            assertThat(failure.getCause(), instanceOf(IOException.class));
                            assertThat(failure.getCause().getMessage(), equalTo("boum"));
                        }
                    }
                    latch.countDown();
                }

                @Override
                public void onFailure(Exception e) {
                    throw new AssertionError(e);
                }
            }, TimeValue.timeValueMillis(1)));
            thread.start();
        }
        latch.await();
    }
}


text:
.right-side {
    padding-top :0;
}
.movable-header .rightsidebar-without-nav {
    padding-top : 20px !important
}
@media screen and (max-width : 560px) {
    body {
        padding-top : 0 !important;
    }
    /*fixednav pages*/
    .fixednav_right {
        padding-top : 112px;
    }
}
@media screen and (max-width : 992px) {
    .fixed-menu #menu {
        padding-top : 0;
    }
    .movable-header #right {
        padding-top : 0;
    }
}
@media screen and (max-width : 560px) {
    .fixed-menu #menu {
        padding-top : 90px;
    }
    .movable-header .rightsidebar-without-nav-small {
        padding-top : 70px !important
    }
}
.movable-header #menu {
    padding-top : 0;
}
/*==== layout fixed ====*/
.slimScrollBar {
    width      : 3px !important;
    opacity    : 0.5 !important;
    background : rgb(130, 194, 224) !important;
}
.menu_align {
    margin-bottom : 50px;
}
.full_img {
    width: 100%;
    height: 150px;
    border-radius: 5px;
}
/*movable header page*/
.header_movable {
    position : relative !important;
}

/*====End of layout fixed ====*/

redpajama_set_name: RedPajamaGithub


text:
package org.addhen.birudo;

import android.app.Application;

import net.danlew.android.joda.JodaTimeAndroid;

import org.addhen.birudo.module.BirudoModule;

import java.util.List;

import dagger.ObjectGraph;
import timber.log.Timber;

public class BirudoApplication extends Application {

    private ObjectGraph mObjectGraph;

    @Override
    public void onCreate() {
        super.onCreate();

        // It's important to initialize the ResourceZoneInfoProvider; otherwise
        // joda-time-android will not work.
        JodaTimeAndroid.init(this);
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        } else {
            Timber.plant(new CrashReportingTree());
        }
        initializeDependencyInjector();
    }

    /**
     * Extend the dependency container graph with new dependencies provided by the modules passed as
     * arguments.
     *
     * @param modules used to populate the dependency container.
     */
    public ObjectGraph add(List<Object> modules) {
        if (modules == null) {
            throw new IllegalArgumentException(
                    "You can't add a null module, review your getModules() implementation");
        }
        return mObjectGraph.plus(modules.toArray());
    }

    private void initializeDependencyInjector() {
        mObjectGraph = ObjectGraph.create(new BirudoModule(this));
        mObjectGraph.inject(this);
        mObjectGraph.injectStatics();
    }

    /**
     * Inject the supplied {@code object} using the activity-specific graph.
     */
    public void inject(Object object) {
        mObjectGraph.inject(object);
    }

    /**
     * A tree which logs important information for crash reporting.
     */
    private static class CrashReportingTree extends Timber.HollowTree {

        @Override
        public void i(String message, Object... args) {
            // TODO Setup Crashlytics.log(String.format(message, args));
        }

        @Override
        public void i(Throwable t, String message, Object... args) {
            i(message, args); // Just add to the log.
        }

        @Override
        public void e(String message, Object... args) {
            i("ERROR: " + message, args); // Just add to the log.
        }

        @Override
        public void e(Throwable t, String message, Object... args) {
            e(message, args);

            // TODO Setup Crashlytics.logException(t);
        }

    }
}


text:
from thrift.Thrift import TType, TMessageType, TException, TApplicationException
from ttypes import *
from thrift.Thrift import TProcessor
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol, TProtocol
try:
  from thrift.protocol import fastbinary
except:
  fastbinary = None

class Iface:
  def ping(self):
    pass

  def setValue(self, key, value):
    """
    Parameters:
     - key
     - value
    """
    pass

  def add(self, a, b):
    """
    Parameters:
     - a
     - b
    """
    pass

class Client(Iface):
  def __init__(self, iprot, oprot=None):
    self._iprot = self._oprot = iprot
    if oprot is not None:
      self._oprot = oprot
    self._seqid = 0

  def ping(self):
    self.send_ping()
    self.recv_ping()

  def send_ping(self):
    self._oprot.writeMessageBegin('ping', TMessageType.CALL, self._seqid)
    args = ping_args()
    args.write(self._oprot)
    self._oprot.writeMessageEnd()
    self._oprot.trans.flush()

  def recv_ping(self):
    iprot = self._iprot
    (fname, mtype, rseqid) = iprot.readMessageBegin()
    if mtype == TMessageType.EXCEPTION:
      x = TApplicationException()
      x.read(iprot)
      iprot.readMessageEnd()
      raise x
    result = ping_result()
    result.read(iprot)
    iprot.readMessageEnd()
    return

  def setValue(self, key, value):
    """
    Parameters:
     - key
     - value
    """
    self.send_setValue(key, value)
    self.recv_setValue()

  def send_setValue(self, key, value):
    self._oprot.writeMessageBegin('setValue', TMessageType.CALL, self._seqid)
    args = setValue_args()
    args.key = key
    args.value = value
    args.write(self._oprot)
    self._oprot.writeMessageEnd()
    self._oprot.trans.flush()

  def recv_setValue(self):
    iprot = self._iprot
    (fname, mtype, rseqid) = iprot.readMessageBegin()
    if mtype == TMessageType.EXCEPTION:
      x = TApplicationException()
      x.read(iprot)
      iprot.readMessageEnd()
      raise x
    result = setValue_result()
    result.read(iprot)
    iprot.readMessageEnd()
    return

  def add(self, a, b):
    """
    Parameters:
     - a
     - b
    """
    self.send_add(a, b)
    return self.recv_add()

  def send_add(self, a, b):
    self._oprot.writeMessageBegin('add', TMessageType.CALL, self._seqid)
    args = add_args()
    args.a = a
    args.b = b
    args.write(self._oprot)
    self._oprot.writeMessageEnd()
    self._oprot.trans.flush()

  def recv_add(self):
    iprot = self._iprot
    (fname, mtype, rseqid) = iprot.readMessageBegin()
    if mtype == TMessageType.EXCEPTION:
      x = TApplicationException()
      x.read(iprot)
      iprot.readMessageEnd()
      raise x
    result = add_result()
    result.read(iprot)
    iprot.readMessageEnd()
    if result.success is not None:
      return result.success
    raise TApplicationException(TApplicationException.MISSING_RESULT, "add failed: unknown result");

class Processor(Iface, TProcessor):
  def __init__(self, handler):
    self._handler = handler
    self._processMap = {}
    self._processMap["ping"] = Processor.process_ping
    self._processMap["setValue"] = Processor.process_setValue
    self._processMap["add"] = Processor.process_add

  def process(self, iprot, oprot):
    (name, type, seqid) = iprot.readMessageBegin()
    if name not in self._processMap:
      iprot.skip(TType.STRUCT)
      iprot.readMessageEnd()
      x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name))
      oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid)
      x.write(oprot)
      oprot.writeMessageEnd()
      oprot.trans.flush()
      return
    else:
      self._processMap[name](self, seqid, iprot, oprot)
    return True

  def process_ping(self, seqid, iprot, oprot):
    args = ping_args()
    args.read(iprot)
    iprot.readMessageEnd()
    result = ping_result()
    self._handler.ping()
    oprot.writeMessageBegin("ping", TMessageType.REPLY, seqid)
    result.write(oprot)
    oprot.writeMessageEnd()
    oprot.trans.flush()

  def process_setValue(self, seqid, iprot, oprot):
    args = setValue_args()
    args.read(iprot)
    iprot.readMessageEnd()
    result = setValue_result()
    self._handler.setValue(args.key, args.value)
    oprot.writeMessageBegin("setValue", TMessageType.REPLY, seqid)
    result.write(oprot)
    oprot.writeMessageEnd()
    oprot.trans.flush()

  def process_add(self, seqid, iprot, oprot):
    args = add_args()
    args.read(iprot)
    iprot.readMessageEnd()
    result = add_result()
    result.success = self._handler.add(args.a, args.b)
    oprot.writeMessageBegin("add", TMessageType.REPLY, seqid)
    result.write(oprot)
    oprot.writeMessageEnd()
    oprot.trans.flush()

# HELPER FUNCTIONS AND STRUCTURES

class ping_args:

  thrift_spec = (
  )

  def read(self, iprot):
    if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
      fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
      return
    iprot.readStructBegin()
    while True:
      (fname, ftype, fid) = iprot.readFieldBegin()
      if ftype == TType.STOP:
        break
      else:
        iprot.skip(ftype)
      iprot.readFieldEnd()
    iprot.readStructEnd()

  def write(self, oprot):
    if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
      oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
      return
    oprot.writeStructBegin('ping_args')
    oprot.writeFieldStop()
    oprot.writeStructEnd()

  def validate(self):
    return

  def __hash__(self):
    value = 17
    return value

  def __repr__(self):
    L = ['%s=%r' % (key, value)
      for key, value in self.__dict__.iteritems()]
    return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

  def __eq__(self, other):
    return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

  def __ne__(self, other):
    return not (self == other)

class ping_result:

  thrift_spec = (
  )

  def read(self, iprot):
    if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
      fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
      return
    iprot.readStructBegin()
    while True:
      (fname, ftype, fid) = iprot.readFieldBegin()
      if ftype == TType.STOP:
        break
      else:
        iprot.skip(ftype)
      iprot.readFieldEnd()
    iprot.readStructEnd()

  def write(self, oprot):
    if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
      oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
      return
    oprot.writeStructBegin('ping_result')
    oprot.writeFieldStop()
    oprot.writeStructEnd()

  def validate(self):
    return

  def __hash__(self):
    value = 17
    return value

  def __repr__(self):
    L = ['%s=%r' % (key, value)
      for key, value in self.__dict__.iteritems()]
    return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

  def __eq__(self, other):
    return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

  def __ne__(self, other):
    return not (self == other)

class setValue_args:
  """
  Attributes:
   - key
   - value
  """

  thrift_spec = (
    None, # 0
    (1, TType.I32, 'key', None, None, ), # 1
    (2, TType.STRING, 'value', None, None, ), # 2
  )

  def __init__(self, key=None, value=None,):
    self.key = key
    self.value = value

  def read(self, iprot):
    if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
      fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
      return
    iprot.readStructBegin()
    while True:
      (fname, ftype, fid) = iprot.readFieldBegin()
      if ftype == TType.STOP:
        break
      if fid == 1:
        if ftype == TType.I32:
          self.key = iprot.readI32();
        else:
          iprot.skip(ftype)
      elif fid == 2:
        if ftype == TType.STRING:
          self.value = iprot.readString();
        else:
          iprot.skip(ftype)
      else:
        iprot.skip(ftype)
      iprot.readFieldEnd()
    iprot.readStructEnd()

  def write(self, oprot):
    if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
      oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
      return
    oprot.writeStructBegin('setValue_args')
    if self.key is not None:
      oprot.writeFieldBegin('key', TType.I32, 1)
      oprot.writeI32(self.key)
      oprot.writeFieldEnd()
    if self.value is not None:
      oprot.writeFieldBegin('value', TType.STRING, 2)
      oprot.writeString(self.value)
      oprot.writeFieldEnd()
    oprot.writeFieldStop()
    oprot.writeStructEnd()

  def validate(self):
    return

  def __hash__(self):
    value = 17
    value = (value * 31) ^ hash(self.key)
    value = (value * 31) ^ hash(self.value)
    return value

  def __repr__(self):
    L = ['%s=%r' % (key, value)
      for key, value in self.__dict__.iteritems()]
    return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

  def __eq__(self, other):
    return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

  def __ne__(self, other):
    return not (self == other)

class setValue_result:

  thrift_spec = (
  )

  def read(self, iprot):
    if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
      fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
      return
    iprot.readStructBegin()
    while True:
      (fname, ftype, fid) = iprot.readFieldBegin()
      if ftype == TType.STOP:
        break
      else:
        iprot.skip(ftype)
      iprot.readFieldEnd()
    iprot.readStructEnd()

  def write(self, oprot):
    if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
      oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
      return
    oprot.writeStructBegin('setValue_result')
    oprot.writeFieldStop()
    oprot.writeStructEnd()

  def validate(self):
    return

  def __hash__(self):
    value = 17
    return value

  def __repr__(self):
    L = ['%s=%r' % (key, value)
      for key, value in self.__dict__.iteritems()]
    return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

  def __eq__(self, other):
    return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

  def __ne__(self, other):
    return not (self == other)

class add_args:
  """
  Attributes:
   - a
   - b
  """

  thrift_spec = (
    None, # 0
    (1, TType.I32, 'a', None, None, ), # 1
    (2, TType.I32, 'b', None, None, ), # 2
  )

  def __init__(self, a=None, b=None,):
    self.a = a
    self.b = b

  def read(self, iprot):
    if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
      fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
      return
    iprot.readStructBegin()
    while True:
      (fname, ftype, fid) = iprot.readFieldBegin()
      if ftype == TType.STOP:
        break
      if fid == 1:
        if ftype == TType.I32:
          self.a = iprot.readI32();
        else:
          iprot.skip(ftype)
      elif fid == 2:
        if ftype == TType.I32:
          self.b = iprot.readI32();
        else:
          iprot.skip(ftype)
      else:
        iprot.skip(ftype)
      iprot.readFieldEnd()
    iprot.readStructEnd()

  def write(self, oprot):
    if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
      oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
      return
    oprot.writeStructBegin('add_args')
    if self.a is not None:
      oprot.writeFieldBegin('a', TType.I32, 1)
      oprot.writeI32(self.a)
      oprot.writeFieldEnd()
    if self.b is not None:
      oprot.writeFieldBegin('b', TType.I32, 2)
      oprot.writeI32(self.b)
      oprot.writeFieldEnd()
    oprot.writeFieldStop()
    oprot.writeStructEnd()

  def validate(self):
    return

  def __hash__(self):
    value = 17
    value = (value * 31) ^ hash(self.a)
    value = (value * 31) ^ hash(self.b)
    return value

  def __repr__(self):
    L = ['%s=%r' % (key, value)
      for key, value in self.__dict__.iteritems()]
    return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

  def __eq__(self, other):
    return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

  def __ne__(self, other):
    return not (self == other)

class add_result:
  """
  Attributes:
   - success
  """

  thrift_spec = (
    (0, TType.I32, 'success', None, None, ), # 0
  )

  def __init__(self, success=None,):
    self.success = success

  def read(self, iprot):
    if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
      fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
      return
    iprot.readStructBegin()
    while True:
      (fname, ftype, fid) = iprot.readFieldBegin()
      if ftype == TType.STOP:
        break
      if fid == 0:
        if ftype == TType.I32:
          self.success = iprot.readI32();
        else:
          iprot.skip(ftype)
      else:
        iprot.skip(ftype)
      iprot.readFieldEnd()
    iprot.readStructEnd()

  def write(self, oprot):
    if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
      oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
      return
    oprot.writeStructBegin('add_result')
    if self.success is not None:
      oprot.writeFieldBegin('success', TType.I32, 0)
      oprot.writeI32(self.success)
      oprot.writeFieldEnd()
    oprot.writeFieldStop()
    oprot.writeStructEnd()

  def validate(self):
    return

  def __hash__(self):
    value = 17
    value = (value * 31) ^ hash(self.success)
    return value

  def __repr__(self):
    L = ['%s=%r' % (key, value)
      for key, value in self.__dict__.iteritems()]
    return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

  def __eq__(self, other):
    return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

  def __ne__(self, other):
    return not (self == other)


text:
"""Collection of Keras models for hierarchical GANs."""

# Imports
from keras.layers.core import Dense, Reshape, Dropout
from keras.layers import Input, merge
from keras.models import Model
from keras.layers.wrappers import TimeDistributed, Bidirectional
from keras.layers.recurrent import LSTM
from keras import backend as K
from keras.constraints import maxnorm

# Embedding layers
def geometry_embedder(n_nodes=10, embedding_dim=100):
    """
    Embedding of geometric coordinates of nodes.

    Parameters
    ----------
    n_nodes: int
        number of nodes
    embedding_dim: int
        embedding_dimension

    Returns
    -------
    geometry_input: keras layer object
        input layer
    geometry_embedding: keras layer object
        embedding layer
    """
    geometry_input = Input(shape=(n_nodes - 1, 3))
    geometry_reshaped = \
        Reshape(target_shape=(1, (n_nodes - 1) * 3))(geometry_input)
    geometry_embedding = Dense(input_dim=(n_nodes - 1) * 3,
                               output_dim=embedding_dim,
                               name='geometry_embedding')(geometry_reshaped)
    return geometry_input, geometry_embedding

def morphology_embedder(n_nodes=10, embedding_dim=100):
    """
    Embedding of tree morphology (softmax Prufer code).

    Parameters
    ----------
    n_nodes: int
        number of nodes
    embedding_dim: int
        embedding_dimension

    Returns
    -------
    morphology_input: keras layer object
        input layer
    morphology_embedding: keras layer object
        embedding layer
    """
    morphology_input = Input(shape=(n_nodes - 2, n_nodes))
    morphology_reshaped = \
        Reshape(target_shape=(1, n_nodes * (n_nodes - 2)))(morphology_input)
    morphology_embedding = \
        Dense(input_dim=(n_nodes - 2) * n_nodes,
              output_dim=embedding_dim,
              name='morphology_embedding')(morphology_reshaped)
    return morphology_input, morphology_embedding

# Generators
def generator(n_nodes_in=10,
              n_nodes_out=20,
              noise_dim=100,
              embedding_dim=100,
              hidden_dim=20,
              use_context=True):
    """
    Generator network.

    Parameters
    ----------
    n_nodes_in: int
        number of nodes in the tree providing context input
    n_nodes_out: int
        number of nodes in the output tree
    noise_dim: int
        dimensionality of noise input
    embedding_dim: int
        dimensionality of embedding for context input
    use_context: bool
        if True, use context, else only noise input

    Returns
    -------
    geometry_model: keras model object
        model of geometry generator
    morphology_model: keras model object
        model of morphology generator
    """
    # Embed contextual information
    if use_context is True:
        geometry_input, geometry_embedding = \
            geometry_embedder(n_nodes=n_nodes_in,
                              embedding_dim=embedding_dim)
        morphology_input, morphology_embedding = \
            morphology_embedder(n_nodes=n_nodes_in,
                                embedding_dim=embedding_dim)

    # Generate noise input
    noise_input = Input(shape=(1, noise_dim), name='noise_input')

    # Concatenate context and noise inputs
    if use_context is True:
        all_inputs = merge([geometry_embedding,
                            morphology_embedding,
                            noise_input], mode='concat')
    else:
        all_inputs = noise_input

    # -------------------
    # Geometry model
    # -------------------
    # Synthesize output
    geometry_hidden_dim = (n_nodes_out - 1) * 3
    geometry_hidden1 = Dense(geometry_hidden_dim)(all_inputs)
    geometry_hidden2 = Dense(geometry_hidden_dim)(geometry_hidden1)

    # Reshape
    geometry_reshaped = \
        Reshape(target_shape=(n_nodes_out - 1, 3))(geometry_hidden2)

    # LSTM
    geometry_lstm = \
        Bidirectional(LSTM(input_dim=3,
                           input_length=n_nodes_out - 1,
                           output_dim=3,
                           return_sequences=True))(geometry_reshaped)

    # TimeDistributed
    geometry_output = \
        TimeDistributed(Dense(input_dim=3,
                              output_dim=3,
                              activation='linear'))(geometry_lstm)

    #geometry_output = \
    #    Reshape(target_shape=(n_nodes_out - 1, 3))(geometry_hidden2)

    # Assign inputs and outputs of the model
    if use_context is True:
        geometry_model = Model(input=[geometry_input,
                                      morphology_input,
                                      noise_input],
                               output=[geometry_output])
    else:
        geometry_model = Model(input=[noise_input],
                               output=[geometry_output])

    # -------------------
    # Morphology model
    # -------------------
    # Synthesize output
    morphology_hidden_dim = hidden_dim * (n_nodes_out - 2)
    morphology_hidden1 = Dense(morphology_hidden_dim)(all_inputs)
    morphology_hidden2 = Dense(morphology_hidden_dim)(morphology_hidden1)
    # Reshape
    morphology_reshaped = \
        Reshape(target_shape=(n_nodes_out - 2, hidden_dim))(morphology_hidden2)

    # LSTM
    morphology_lstm = \
        Bidirectional(LSTM(input_dim=hidden_dim,
                           input_length=n_nodes_out - 2,
                           output_dim=hidden_dim,
                           return_sequences=True))(morphology_reshaped)

    # TimeDistributed
    morphology_output = \
        TimeDistributed(Dense(input_dim=hidden_dim,
                              output_dim=n_nodes_out,
                              activation='softmax'))(morphology_lstm)

    # Assign inputs and outputs of the model
    if use_context is True:
        morphology_model = \
            Model(input=[geometry_input,
                         morphology_input,
                         noise_input],
                  output=[morphology_output])
    else:
        morphology_model = Model(input=[noise_input],
                                 output=[morphology_output])

    return geometry_model, morphology_model

# Discriminator
def discriminator(n_nodes_in=10,
                  embedding_dim=100,
                  hidden_dim=50):
    """
    Discriminator network.

    Parameters
    ----------
    n_nodes_in: int
        number of nodes in the tree providing context input
    embedding_dim: int
        dimensionality of embedding for context input
    hidden_dim: int
        dimensionality of hidden layers

    Returns
    -------
    discriminator_model: keras model object
        model of discriminator
    """
    # Embed geometry
    geometry_input, geometry_embedding = \
        geometry_embedder(n_nodes=n_nodes_in,
                          embedding_dim=embedding_dim)

    # Embed morphology
    morphology_input, morphology_embedding = \
        morphology_embedder(n_nodes=n_nodes_in,
                            embedding_dim=embedding_dim)

    # Concatenate embeddings
    all_inputs = merge([geometry_embedding, morphology_embedding],
                       mode='concat')

    # --------------------
    # Discriminator model
    # -------------------=
    discriminator_hidden1 = \
        Dense(hidden_dim)(all_inputs)
    discriminator_hidden2 = \
        Dense(hidden_dim)(discriminator_hidden1)
    discriminator_output = \
        Dense(1, activation='linear')(discriminator_hidden2)

    discriminator_model = Model(input=[geometry_input,
                                       morphology_input],
                                output=[discriminator_output])

    return discriminator_model

def wasserstein_loss(y_true, y_pred):
    """
    Custom loss function for Wasserstein critic.

    Parameters
    ----------
    y_true: keras tensor
        true labels: -1 for data and +1 for generated sample
    y_pred: keras tensor
        predicted EM score
    """
    return K.mean(y_true * y_pred)

# Discriminator on generators
def discriminator_on_generators(geometry_model,
                                morphology_model,
                                discriminator_model,
                                input_dim=100,
                                n_nodes_in=10,
                                use_context=True):
    """
    Discriminator stacked on the generators.

    Parameters
    ----------
    geometry_model: keras model object
        model object that generates the geometry
    morphology_model: keras model object
        model object that generates the morphology
    discriminator_model: keras model object
        model object for the discriminator
    input_dim: int
        dimensionality of noise input
    n_nodes_in: int
        number of nodes in the tree providing
        context input for the generators
    use_context: bool
        if True, use context, else only noise input for the generators

    Returns
    -------
    gan_model: keras model object
        model of the discriminator stacked on the generator
    """
    # Inputs
    if use_context is True:
        geometry_input = Input(shape=(n_nodes_in - 1, 3))
        morphology_input = Input(shape=(n_nodes_in - 2, n_nodes_in))

    noise_input = Input(shape=(1, input_dim), name='noise_input')

    # Generator outputs
    if use_context is True:
        geometry_output = geometry_model([geometry_input,
                                          morphology_input,
                                          noise_input])
        morphology_output = morphology_model([geometry_input,
                                              morphology_input,
                                              noise_input])
    else:
        geometry_output = geometry_model(noise_input)
        morphology_output = morphology_model(noise_input)

    # Discriminator output
    discriminator_output = \
        discriminator_model([geometry_output,
                             morphology_output])

    # Stack discriminator on generator
    if use_context is True:
        gan_model = Model([geometry_input,
                           morphology_input,
                           noise_input],
                          [discriminator_output])
    else:
        gan_model = Model([noise_input],
                          [discriminator_output])
    return gan_model


text:
/*global window, document */
'use strict';
var views = require('./views');
var Router = require('routes');
var ad = require('./ad');
var $ = require('jquery');
var Promise = require('promise-polyfill');

//In general please use exports.name for simplicity
//unless otherwise necessary not to.

/**
 * Sets up routes and deals with click hijacking and
 * adding content to the DOM.
 * @module router
 */
module.exports = (function() {
  var router = new Router();
  router.addRoute("\/?:slug(politics|media|environment)\/?$", views.displayMainContent);
  router.addRoute("\/?:schema/:slug", views.displayMainContent);
  router.addRoute("\/?:section/[0-9]+/[0-9]+/:slug", views.displayMainContent);
  router.addRoute("^\/$", views.displayMainContent);
  return router;
})();

/**
  * Takes path and runs view
  * @alias pop
  * @memberof module:router
  * @param {string} path - Url to lookup.
  * @return {returned} Promise returned by view.
  */
module.exports.pop = function(path) {
  var match = module.exports.match(path);
  var returned = '';
  if(match) {
    returned = match.fn(match, module.exports.callback);
  }
  return returned;
};

/**
  * Overwrite DEPENDING ON IF I'M IN A BROWSER OR NOT
  * Called after a view gets rendered html
  * @alias callback
  * @abstract
  * @memberof module:router
  * @param {object} data - Data returned mostly for testing.
  * @param {object} html - HTML to be inserted in DOM/string.
  */
module.exports.callback = function() {
  return null;
};

/**
  * Set up click and callback events for the browser
  * @alias browserStart
  * @memberof module:router
  */
module.exports.browserStart = function() {
  $('body').on("click", "[href^='/']", module.exports.browserClick );
  $(window).on('popstate', function() {
    module.exports.pop(document.location.pathname);
  });
  ad.setAdListener();
  module.exports.callback = module.exports.browserCallback;
  module.exports.pop(document.location.pathname);
};

/**
  * Handles the hyperlink click events for browsers
  * @alias browserClick
  * @memberof module:router
  * @param {event} e - The click event
  * @return {promise} Promise resolved the router runs the appropriate function
  */
module.exports.browserClick = function(e) {
  e.preventDefault();
  var promise = new Promise(function(resolve) {
    module.exports.pop($(e.target).attr('href'));
    window.history.pushState(0, 'Mother Jones', $(e.target).attr('href'));
    resolve();
  });
  return promise;
};

/**
  * Method called after the page html has been constructed
  * @alias browserCallback
  * @memberof module:router
  * @param {data} object - the page data
  * @param {html} string - the rendered page html
  */
module.exports.browserCallback = function(data, html) {
  $('body').html(html);
  document.title = 'MotherJones' +
    (data.metadata.title ? ' - ' + data.metadata.title : '');
  ad.reload(data.keywords);
};


text:
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------

namespace think\exception;

use Psr\Container\NotFoundExceptionInterface;
use RuntimeException;
use Throwable;

class ClassNotFoundException extends RuntimeException implements NotFoundExceptionInterface
{
    protected $class;

    public function __construct(string $message, string $class = '', Throwable $previous = null)
    {
        $this->message = $message;
        $this->class   = $class;

        parent::__construct($message, 0, $previous);
    }

    /**
     * 获取类名
     * @access public
     * @return string
     */
    public function getClass()
    {
        return $this->class;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>GIO Reference Manual</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="index.html" title="GIO Reference Manual">
<link rel="next" href="pt01.html" title="Part I. GIO Overview">
<meta name="generator" content="GTK-Doc V1.14 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">

GIO Reference Manual

      for GIO 2.24.1

      The latest version of this documentation can be found on-line at
      http://library.gnome.org/devel/gio/unstable/.

I. GIO Overview

Introduction

Compiling GIO applications

Running GIO applications

Extending GIO

II. API Reference

File Operations

GFile — File and Directory Handling

GFileAttribute — Key-Value Paired File Attributes

GFileInfo — File Information and Attributes

GFileEnumerator — Enumerated Files Routines

GIOError — Error helper functions

GMountOperation — Object used for authentication and user interaction

File System Monitoring

GFileMonitor — File Monitor

Asynchronous I/O

GCancellable — Thread-safe Operation Cancellation Stack

GAsyncResult — Asynchronous Function Results

GIOScheduler — I/O Scheduler

GSimpleAsyncResult — Simple asynchronous results implementation

Data conversion

GConverter — Data conversion interface

GCharsetConverter — Convert between charsets

GZlibCompressor — Zlib compressor

GZlibDecompressor — Zlib decompressor

Streaming I/O

GSeekable — Stream seeking interface

GInputStream — Base class for implementing streaming input

GOutputStream — Base class for implementing streaming output

GIOStream — Base class for implementing read/write streams

GFileInputStream — File input streaming operations

GFileOutputStream — File output streaming operations

GFileIOStream — File read and write streaming operations

GFileDescriptorBased — Interface for file descriptor based IO

GFilterInputStream — Filter Input Stream

GFilterOutputStream — Filter Output Stream

GMemoryInputStream — Streaming input operations on memory chunks

GMemoryOutputStream — Streaming output operations on memory chunks

GBufferedInputStream — Buffered Input Stream

GBufferedOutputStream — Buffered Output Stream

GDataInputStream — Data Input Stream

GDataOutputStream — Data Output Stream

GUnixInputStream — Streaming input operations for UNIX file descriptors

GUnixOutputStream — Streaming output operations for Unix file descriptors

GConverterInputstream — Converter Input Stream

GConverterOutputstream — Converter Output Stream

File types and applications

GContentType — Platform-specific content typing

GAppInfo — Application information and launch contexts

Desktop file based GAppInfo — Application information from desktop files

Volumes and Drives

GVolumeMonitor — Volume Monitor

GVolume — Volume management

GMount — Mount management

GDrive — Drive management

Unix Mounts — Unix Mounts

Icons

GIcon — Interface for icons

GFileIcon — Icons pointing to an image file

GLoadableIcon — Loadable Icons

GThemedIcon — Icon theming support

GEmblemedIcon — Icon with emblems

GEmblem — An object for emblems

Failable Initialization

GInitable — Failable object initialization interface

GAsyncInitable — Asynchronously failable object initialization interface

Lowlevel platform-independent network support

GSocket — Low-level socket object

GInetAddress — An IPv4/IPv6 address

GSocketAddress — Abstract base class representing endpoints for
socket communication

GInetSocketAddress — Internet GSocketAddress

GUnixSocketAddress — UNIX GSocketAddress

GSocketControlMessage — A GSocket control message

GUnixFDList — An object containing a set of file descriptors

GUnixFDMessage — A GSocketControlMessage containing a GUnixFDList

DNS resolution

GResolver — Asynchronous and cancellable DNS resolver

GSocketConnectable — Interface for potential socket endpoints

GNetworkAddress — A GSocketConnectable for resolving hostnames

GNetworkService — A GSocketConnectable for resolving SRV records

GSrvTarget — DNS SRV record target

Highlevel network functionallity

GSocketClient — Helper for connecting to a network service

GSocketConnection — A socket connection

GSocketListener — Helper for accepting network client connections

GSocketService — Make it easy to implement a network service

GThreadedSocketService — A threaded GSocketService

Utilities

GFilenameCompleter — Filename Completer

Extending GIO

GVfs — Virtual File System

GIOModule — Loadable GIO Modules

Extension Points — Extension Points

III. Migrating to GIO

Migrating from POSIX to GIO

Migrating from GnomeVFS to GIO

Trash handling

Operations on multiple files

Mime monitoring

Object Hierarchy

Index

Index of deprecated symbols

Index of new symbols in 2.18

Index of new symbols in 2.20

Index of new symbols in 2.22

Index of new symbols in 2.24

          Generated by GTK-Doc V1.14


text:
(function (angular) {
    var ttAppModule = angular.module('ttApp');
    ttAppModule.service('GreetedPeopleService', ['$http', function($http){
        var peopleWeAlreadyGreeted = [];
        var lastAssignedId = 0;

        function getGreetedPeople(){
            return peopleWeAlreadyGreeted;
        }

        function addGreetedPerson(person){
            peopleWeAlreadyGreeted.push(person);
        }

        function remove(person){
            var index = peopleWeAlreadyGreeted.indexOf(person);
            if(index !== -1){
                peopleWeAlreadyGreeted.splice(index, 1);
            }
        }

        function createPerson(name){
            var newId = lastAssignedId + 1;

            var person = {
                name: name,
                id: newId
            };

            lastAssignedId++;
            return person;
        }

        var address = "http://private-63a58-ttangularjsstart.apiary-mock.com";
        function fetchOnline(){
            return $http.get(address+'/people').success(function(data){
                peopleWeAlreadyGreeted = data;
            });
        }

        return {
            getGreetedPeople: getGreetedPeople,
            addGreetedPerson: addGreetedPerson,
            removeGreetedPerson: remove,
            createGreetedPerson: createPerson,
            fetchOnline: fetchOnline
        };
    }]);

})(angular);


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

<!---   http://www.apache.org/licenses/LICENSE-2.0 -->

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

# TOPI Recipe: TVM Operator Optimization Recipes

TOPI is the operator collection library for TVM intended at sharing the effort of crafting
and optimizing tvm generated kernels. The goal:

- Provide sugars for operator declaration
- Give common primitives for fused op creation.
- Provide commonly used schedules under each architectures

## Guidelines
- Use numpy-style naming convention for known ops
- Seperate operator declaration from schedule when possible.
  - This can be inconvenient but enables more general scheduling across ops.
  - We can always recover the tensors from its outputs by traversing the tree.
- Deliberately assert the requirements
  - Some kernels have requirements on shape and data layout, assert them
- Data layout aware, if not specified in argument or in function, assume NCHW by default.

## Performance Tuning Workflow
Since TVM is work in progress, some optimization might not be perfect.
One quick way I find useful is to do codegen plus manual modification.
The workflow is:

- Generate the GPU kernels, write them into a file, say ```perf/matexp_generated.cu```
- Copy the generated file into another one, say ```perf/matexp_manual.cu```,
  do modifications according to your intuition.
- Set use_manual flag in the script to continue the codegen workflow as normal, but piggy back the manual written code instead.
- Observe the performance difference.
- If the performance improves, mark the manual code and think of optimization pass
  to generate the desired target code.


text:
if ! which brew &> /dev/null
then
	ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)"
fi

# Prepare brew for multi-users setup
if ! sudo dscl . read /Groups/brew &> /dev/null
then
	echo "Now let's make brew useful for all users."
	echo "Create a 'brew' group"
	sudo dscl . create /Groups/brew
	sudo dscl . create /Groups/brew RealName "Homebrew group"
	sudo dscl . create /Groups/brew gid 400
	sudo dscl . create /Groups/brew GroupMembership `whoami`
fi

echo -n "Change the group of homebrew cache directory…"
sudo chgrp -R brew /Library/Caches/Homebrew
echo "done"

echo -n "Allow group members to write inside this directory…"
sudo chmod -R g+w /Library/Caches/Homebrew
echo "done"


text:
namespace tf_opt {
namespace {

using ::testing::AllOf;
using ::testing::HasSubstr;
using ::tf_opt::testing::StatusIs;

constexpr absl::StatusCode kInvalidArgument =
    ::absl::StatusCode::kInvalidArgument;

absl::Status MaybeError(bool is_error) {
  if (is_error) {
    return absl::InvalidArgumentError("Bad argument");
  }
  return absl::OkStatus();
}

absl::Status MaybePropagateError(bool is_error) {
  TFOPT_RETURN_IF_ERROR(MaybeError(is_error));
  return absl::OkStatus();
}

absl::Status MaybePropagateErrorAndAppend(bool is_error) {
  TFOPT_RETURN_IF_ERROR(MaybeError(is_error)) << " Error context";
  return absl::OkStatus();
}

TEST(ExpectOkTest, NoError) { TFOPT_EXPECT_OK(MaybePropagateError(false)); }

TEST(StatusIsTest, Error) {
  EXPECT_THAT(MaybePropagateError(true),
              StatusIs(kInvalidArgument, "Bad argument"));
}

TEST(ExpectOkTest, NoErrorAppend) {
  TFOPT_EXPECT_OK(MaybePropagateErrorAndAppend(false));
}

TEST(StatusIsTest, ErrorAppend) {
  EXPECT_THAT(MaybePropagateErrorAndAppend(true),
              StatusIs(kInvalidArgument, AllOf(HasSubstr("Bad argument"),
                                               HasSubstr("Error context"))));
}

TEST(CheckOkTest, NoError) { TFOPT_CHECK_OK(absl::OkStatus()); }
TEST(QCheckOkTest, NoError) { TFOPT_CHECK_OK(absl::OkStatus()); }
TEST(DCheckOkTest, NoError) { TFOPT_DCHECK_OK(absl::OkStatus()); }

TEST(CheckOkTestDeathTest, NotOk) {
  EXPECT_DEATH(TFOPT_CHECK_OK(absl::InvalidArgumentError("bad arg")),
               HasSubstr("bad arg"));
}
TEST(QCheckOkTestDeathTest, NotOk) {
  EXPECT_DEATH(TFOPT_CHECK_OK(absl::InvalidArgumentError("bad arg")),
               HasSubstr("bad arg"));
}
#ifndef NDEBUG
TEST(DCheckOkTestDeathTest, NotOk) {
  EXPECT_DEATH(TFOPT_DCHECK_OK(absl::InvalidArgumentError("bad arg")),
               HasSubstr("bad arg"));
}
#else
TEST(DCheckOkTest, NotOkNoCrash) {
  TFOPT_DCHECK_OK(absl::InvalidArgumentError("bad arg"));
}
#endif

}  // namespace
}  // namespace tf_opt


text:
require_relative '../../../../test_helper'
require_relative '../endpoint_test_helper'

class WorkspacesTest < Minitest::Test
  extend Smartsheet::Test::EndpointHelper

  attr_accessor :mock_client
  attr_accessor :smartsheet_client

  def category
    smartsheet_client.workspaces
  end

  def self.endpoints
    [
        {
            symbol: :copy,
            method: :post,
            url: ['workspaces', :workspace_id, 'copy'],
            args: {workspace_id: 123, body: {}},
            has_params: true,
            headers: nil
        },
        {
            symbol: :create,
            method: :post,
            url: ['workspaces'],
            args: {body: {}},
            has_params: false,
            headers: nil
        },
        {
            symbol: :delete,
            method: :delete,
            url: ['workspaces', :workspace_id],
            args: {workspace_id: 123},
            has_params: false,
            headers: nil
        },
        {
            symbol: :get,
            method: :get,
            url: ['workspaces', :workspace_id],
            args: {workspace_id: 123},
            has_params: true,
            headers: nil
        },
        {
            symbol: :list,
            method: :get,
            url: ['workspaces'],
            args: {},
            has_params: true,
            headers: nil
        },
        {
            symbol: :update,
            method: :put,
            url: ['workspaces', :workspace_id],
            args: {workspace_id: 123, body: {}},
            has_params: false,
            headers: nil
        },
    ]
  end

  define_setup
  define_endpoints_tests
end


text:
// Copyright (c) Dapplo and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Dapplo.HttpExtensions.Support;

/// <summary>
///     Marker for the response
/// </summary>
public enum HttpParts
{
    /// <summary>
    ///     Default value.
    /// </summary>
    None,

    /// <summary>
    ///     The property specifies the boundary of a multi-part
    /// </summary>
    MultipartBoundary,

    /// <summary>
    ///     The property specifies the name of the content in a multi-part post
    /// </summary>
    RequestMultipartName,

    /// <summary>
    ///     The property specifies the filename of the content in a multi-part post
    /// </summary>
    RequestMultipartFilename,

    /// <summary>
    ///     Specifies the content for uploading
    /// </summary>
    RequestContent,

    /// <summary>
    ///     Specifies the content-type for uploading
    /// </summary>
    RequestContentType,

    /// <summary>
    ///     Specifies the request headers to send on the request, this should be of type IDictionary where key is string and
    ///     value is string
    /// </summary>
    RequestHeaders,

    /// <summary>
    ///     The property will get the response content, HttpResponseMessage can also be used
    /// </summary>
    ResponseContent,

    /// <summary>
    ///     The property will get the response content, when an error occured
    /// </summary>
    ResponseErrorContent,

    /// <summary>
    ///     Specifies the content-type, either for uploading or for the response
    /// </summary>
    ResponseContentType,

    /// <summary>
    ///     The Http-Status code, should be of type HttpStatusCode
    /// </summary>
    ResponseStatuscode,

    /// <summary>
    ///     Marks HttpResponseHeaders,
    /// </summary>
    ResponseHeaders
}


text:
using System;

class PrintCirclePerimeterAndArea
{
    static void Main(string[] args)
    {
        double radius = double.Parse(Console.ReadLine());
        double area = Math.PI * radius * radius;
        double perimeter = 2 * Math.PI * radius;

        Console.WriteLine("The circle's area is: {0}", area);
        Console.WriteLine("The circle's perimeter is: {0}", perimeter);
    }
}


text:
<?php

namespace Ftt\FrontOfficeBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class FttFrontOfficeBundle extends Bundle
{
}


text:
<?php

declare(strict_types=1);

namespace JMS\Serializer\Tests\Fixtures;

use DateTimeInterface;
use JMS\Serializer\Annotation as JMS;

class DateTimeContainer
{
    /**
     * @var DateTimeInterface
     * @JMS\Type("DateTimeInterface<'Y-m-d'>")
     * @JMS\SerializedName("custom")
     */
    public $customDateTime;

    public function __construct(DateTimeInterface $custom)
    {
        $this->customDateTime = $custom;
    }
}


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

@import uk.gov.hmrc.helptosavefrontend.models.HtsContext
@import uk.gov.hmrc.helptosavefrontend.config.FrontendAppConfig

@this(main: uk.gov.hmrc.helptosavefrontend.views.html.main_template)

@()(implicit htsContext: HtsContext, request: Request[_], messages: Messages, appConfig: FrontendAppConfig)

@title = @{
  Messages("hts.iv.locked_out.title.h1")
}

@main(
  title = title
) {

@title

@Messages("hts.iv.locked_out.p1")

@Html(Messages("hts.iv.locked_out.p2"))

@Messages("hts.global.exit.to.gov.uk")

}


text:
<?php

namespace Opstalent\ApiBundle\Serializer;

use Symfony\Component\Serializer\Serializer as BaseSerializer;

/**
 * {@inheritDoc}
 */
class Serializer extends BaseSerializer
{
    /**
     * @param array $context
     * @param $data
     * @return array
     */
    protected function buildContext(array $context = [], $data): array
    {
        if(array_key_exists("top", $context)
            && is_object($data)
        ) {
            unset($context["top"]);
            $context['entity'] = $data;
        }

        return $context;
    }

    /**
     * {@inheritdoc}
     */
    public function normalize($data, $format = null, array $context = array())
    {
        $context = $this->buildContext($context, $data);
        return parent::normalize($data, $format, $context);
    }
}


text:
- **Author**: Josue Negron
- **Email**: jnegron@vmware.com
- **Date Created**: 8/1/2017
- **Supported Platforms**: Windows 7/8.1/10
- **Tested on Windows 10**: 1703

## Purpose
These sets of sample BATCH files will add and delete users and create and downgrade admins.

- **CreateAdmin.bat** - Creates a local admin on the device
- **CreateUser.bat** - Creates a local user on the device
- **DeleteUser.bat** - Deletes a local user or admin on the device
- **DowngradeAdmin.bat** - Removes user/admin from a group e.g. administrators group

## Details
For more information regarding using the Net User command please refer to the [Net User Reference](https://technet.microsoft.com/en-us/library/cc771865(v=ws.11).aspx). You can modify these scripts to support working with domain users by simply adding the **/domain** parameter.

Deploy the .bat file via AirWatch's Product Provisioning.

## Change Log
- 8/1/2017: Created Samples for creating/deleting/modifying users and their permissions

## Additional Resources
* [Net User Reference](https://technet.microsoft.com/en-us/library/cc771865(v=ws.11).aspx)


text:
FROM debian:stable
MAINTAINER Philipp Naderer-Puiu

ENV DEBIAN_FRONTEND noninteractive
ADD context  /opt/context/

RUN apt-get update && apt-get install -y software-properties-common wget gnupg
RUN wget -qO - https://adoptopenjdk.jfrog.io/adoptopenjdk/api/gpg/key/public | apt-key add - \
    && add-apt-repository --yes https://adoptopenjdk.jfrog.io/adoptopenjdk/deb/

RUN apt-get update && apt-get install -y \
    adoptopenjdk-11-hotspot \
    git \
    build-essential \
    dpkg-dev \
    debhelper \
    cdbs \
    jsvc

CMD ["sh", "/opt/context/build-package.sh"]


text:
.class public final Lcom/google/zxing/client/result/SMTPResultParser;
.super Lcom/google/zxing/client/result/ResultParser;

# direct methods
.method public constructor <init>()V
    .locals 0

    invoke-direct {p0}, Lcom/google/zxing/client/result/ResultParser;-><init>()V

    return-void
.end method

# virtual methods
.method public parse(Lcom/google/zxing/Result;)Lcom/google/zxing/client/result/EmailAddressParsedResult;
    .locals 6

    const/16 v5, 0x3a

    const/4 v4, 0x0

    const/4 v0, 0x0

    invoke-virtual {p1}, Lcom/google/zxing/Result;->getText()Ljava/lang/String;

    move-result-object v1

    const-string v2, "smtp:"

    invoke-virtual {v1, v2}, Ljava/lang/String;->startsWith(Ljava/lang/String;)Z

    move-result v2

    if-nez v2, :cond_0

    const-string v2, "SMTP:"

    invoke-virtual {v1, v2}, Ljava/lang/String;->startsWith(Ljava/lang/String;)Z

    move-result v2

    if-nez v2, :cond_0

    :goto_0
    return-object v0

    :cond_0
    const/4 v2, 0x5

    invoke-virtual {v1, v2}, Ljava/lang/String;->substring(I)Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v2, v5}, Ljava/lang/String;->indexOf(I)I

    move-result v3

    if-ltz v3, :cond_2

    add-int/lit8 v1, v3, 0x1

    invoke-virtual {v2, v1}, Ljava/lang/String;->substring(I)Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v2, v4, v3}, Ljava/lang/String;->substring(II)Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v1, v5}, Ljava/lang/String;->indexOf(I)I

    move-result v3

    if-ltz v3, :cond_1

    add-int/lit8 v0, v3, 0x1

    invoke-virtual {v1, v0}, Ljava/lang/String;->substring(I)Ljava/lang/String;

    move-result-object v0

    invoke-virtual {v1, v4, v3}, Ljava/lang/String;->substring(II)Ljava/lang/String;

    move-result-object v1

    :cond_1
    :goto_1
    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "mailto:"

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    new-instance v3, Lcom/google/zxing/client/result/EmailAddressParsedResult;

    invoke-direct {v3, v2, v1, v0, v4}, Lcom/google/zxing/client/result/EmailAddressParsedResult;-><init>(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V

    move-object v0, v3

    goto :goto_0

    :cond_2
    move-object v1, v0

    goto :goto_1
.end method

.method public bridge synthetic parse(Lcom/google/zxing/Result;)Lcom/google/zxing/client/result/ParsedResult;
    .locals 1

    invoke-virtual {p0, p1}, Lcom/google/zxing/client/result/SMTPResultParser;->parse(Lcom/google/zxing/Result;)Lcom/google/zxing/client/result/EmailAddressParsedResult;

    move-result-object v0

    return-object v0
.end method


text:
title: "The Latinx Collective: Issue 19"
date: 2018-09-28
description: The Latinx Collective is a newsletter written by Elisabeth Rosario that offers a refreshing look at the every day contributions and achievements of Latinx people. 💃🏽
link: https://newsletters.thelatinxcollective.com/issues/the-latinx-collective-issue-19-135985
image: https://pbs.twimg.com/media/DjUaM5ZVAAATgZ8.jpg
categories:
  - press
---

If you're a Latinx or person of color in the tech space, or you want to break in, you'll enjoy this Q&A with a Latinx software engineer who works at Slack, the billion dollar tech company. Coronel's parents immigrated to the U.S. in their 20's, earned degrees from schools like MIT and Columbia University, and eventually became educators at the high school and university level. Frances shares how and why she pursued a career in tech, and shared 3 pointers for young people who want to break into tech: 1.) Stay resilient 2.) Find your people and 3.) Respect others


text:
package com.wookler.server.common.counter;

import com.wookler.server.common.ConfigurationException;
import com.wookler.server.common.Heartbeat;
import com.wookler.server.common.HeartbeatLogger;
import com.wookler.server.common.Module;
import com.wookler.server.common.config.ConfigNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.util.List;

/**
 * @author Subho Ghosh (subho dot ghosh at outlook.com)
 * @created 20/08/14
 */
public class LogHeartbeatLogger implements HeartbeatLogger {
	private static final Logger log = LoggerFactory
			.getLogger(LogHeartbeatLogger.class);

	@Override
	public void log(Module info, List<Heartbeat> heartbeats) {
		if (heartbeats != null && !heartbeats.isEmpty()) {
			for (Heartbeat h : heartbeats) {
				log.warn(String.format("[%s] %s", info.toString(),
						h.toString()));
			}
		}
	}

	@Override
	public Heartbeat parse(String value) throws ParseException {
		return null;
	}

	@Override
	public void configure(ConfigNode config) throws ConfigurationException {

	}

	@Override
	public void dispose() {

	}
}


text:
from negotiator import ContentNegotiator, AcceptParameters, ContentType
from .resource import Representor

try:
    from flask import Response
except:
    pass

class HypermediaResponse(object):

    def __init__(self, media_type, resource):
        self.media_type = media_type
        self.body = resource.translate_to(media_type)

class ResponseBuilder(object):

    def __init__(self, default_type):
        self.default_type = default_type

    def build(self, resource, accept):
        adapters = Representor.adapters.all()
        acceptable = [AcceptParameters(ContentType(adapter.media_type)) for adapter in adapters]
        cn = ContentNegotiator(AcceptParameters(ContentType(self.default_type)), acceptable)
        negotiate = cn.negotiate(accept=accept)
        if negotiate:
            return HypermediaResponse(str(negotiate.content_type), resource)
        return HypermediaResponse(self.default_type, resource)

class APIResource(object):

    def default_type(self):
        return "application/hal+json"

    def available_actions(self):
        return [action for action in self.actions().values()
            if hasattr(self, action)]

    def available_methods(self):
        return [method for method, action in self.actions().items()
            if action in self.available_actions()]

    def method_override(self):
        return "_method"

    def actions(self):
        """Defaults Actions"""
        return {
            'GET': 'read',
            'POST': 'process',
            'PATCH': 'partial',
            'PUT': 'save',
            'DELETE': 'remove'
        }

    def build_response(self, resource, accepts):
        response_builder = ResponseBuilder(self.default_type())
        return response_builder.build(resource, accepts)

class FlaskAPIResource(APIResource):

    def flask_response(self, resource, request, *args, **kwargs):
        response = self.build_response(resource, request.headers.get('Accept'))
        return Response(response.body, mimetype=response.media_type, *args, **kwargs)

    def get_method(self, request):
        if request.method != "POST":
            return request.method
        method_override = self.method_override()
        if request.form.has_key(method_override) and request.method == "POST":
            return request.form[method_override]
        return request.method

    def response_for(self, request):
        method = self.get_method(request)
        action_name = self.actions()[method]
        action = getattr(self, action_name)
        resource = action(request)
        response = self.build_response(resource, request.headers.get('Accept'))
        return Response(response.body, mimetype=response.media_type)


text:
<?php

namespace Doctrine\DBAL;

/**
 * Container for all DBAL events.
 *
 * This class cannot be instantiated.
 */
final class Events
{
    /**
     * Private constructor. This class cannot be instantiated.
     *
     * @codeCoverageIgnore
     */
    private function __construct()
    {
    }

    public const postConnect = 'postConnect';

    public const onSchemaCreateTable            = 'onSchemaCreateTable';
    public const onSchemaCreateTableColumn      = 'onSchemaCreateTableColumn';
    public const onSchemaDropTable              = 'onSchemaDropTable';
    public const onSchemaAlterTable             = 'onSchemaAlterTable';
    public const onSchemaAlterTableAddColumn    = 'onSchemaAlterTableAddColumn';
    public const onSchemaAlterTableRemoveColumn = 'onSchemaAlterTableRemoveColumn';
    public const onSchemaAlterTableChangeColumn = 'onSchemaAlterTableChangeColumn';
    public const onSchemaAlterTableRenameColumn = 'onSchemaAlterTableRenameColumn';
    public const onSchemaColumnDefinition       = 'onSchemaColumnDefinition';
    public const onSchemaIndexDefinition        = 'onSchemaIndexDefinition';
}


text:
// Lucene version compatibility level 4.8.1
using J2N.Threading.Atomic;
using Lucene.Net.Diagnostics;
using Lucene.Net.Support.Threading;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;

namespace Lucene.Net.Facet.Taxonomy
{

    /// <summary>
    /// TaxonomyReader is the read-only interface with which the faceted-search
    /// library uses the taxonomy during search time.
    /// <para>
    /// A TaxonomyReader holds a list of categories. Each category has a serial
    /// number which we call an "ordinal", and a hierarchical "path" name:
    /// <list type="bullet">
    /// <item><description>
    /// The ordinal is an integer that starts at 0 for the first category (which is
    /// always the root category), and grows contiguously as more categories are
    /// added; Note that once a category is added, it can never be deleted.
    /// </description></item>
    /// <item><description>
    /// The path is a CategoryPath object specifying the category's position in the
    /// hierarchy.
    /// </description></item>
    /// </list>
    /// </para>
    /// <b>Notes about concurrent access to the taxonomy:</b>
    /// <para>
    /// An implementation must allow multiple readers to be active concurrently
    /// with a single writer. Readers follow so-called "point in time" semantics,
    /// i.e., a TaxonomyReader object will only see taxonomy entries which were
    /// available at the time it was created. What the writer writes is only
    /// available to (new) readers after the writer's <see cref="Index.IndexWriter.Commit()"/> is called.
    /// </para>
    /// <para>
    /// In faceted search, two separate indices are used: the main Lucene index,
    /// and the taxonomy. Because the main index refers to the categories listed
    /// in the taxonomy, it is important to open the taxonomy *after* opening the
    /// main index, and it is also necessary to Reopen() the taxonomy after
    /// Reopen()ing the main index.
    /// </para>
    /// <para>
    /// This order is important, otherwise it would be possible for the main index
    /// to refer to a category which is not yet visible in the old snapshot of
    /// the taxonomy. Note that it is indeed fine for the the taxonomy to be opened
    /// after the main index - even a long time after. The reason is that once
    /// a category is added to the taxonomy, it can never be changed or deleted,
    /// so there is no danger that a "too new" taxonomy not being consistent with
    /// an older index.
    /// </para>
    ///
    /// @lucene.experimental
    /// </summary>
    public abstract class TaxonomyReader : IDisposable
    {
        /// <summary>
        /// An iterator over a category's children.
        /// </summary>
        public class ChildrenEnumerator
        {
            private readonly int[] siblings;
            private int child;
            private int currentChild = TaxonomyReader.INVALID_ORDINAL;

            internal ChildrenEnumerator(int child, int[] siblings)
            {
                this.siblings = siblings ?? throw new ArgumentNullException(nameof(siblings)); // LUCENENT specific - added guard clause
                this.child = child;
            }

            /// <summary>
            /// Gets the current child. Returns <see cref="TaxonomyReader.INVALID_ORDINAL"/> if
            /// positioned before the first child or after the last child.
            /// </summary>
            public virtual int Current => currentChild;

            /// <summary>
            /// Move to the next child ordinal. Returns <c>false</c> if there are no more children.
            /// </summary>
            /// <returns></returns>
            public virtual bool MoveNext()
            {
                if (child == TaxonomyReader.INVALID_ORDINAL)
                    return false;

                currentChild = child;
                child = siblings[child];
                return true;
            }
        }

        /// <summary>
        /// Sole constructor.
        /// </summary>
        protected TaxonomyReader() // LUCENENET specific - marked protected instead of public
        {
        }

        /// <summary>
        /// The root category (the category with the empty path) always has the ordinal
        /// 0, to which we give a name ROOT_ORDINAL. <see cref="GetOrdinal(FacetLabel)"/>
        /// of an empty path will always return <see cref="ROOT_ORDINAL"/>, and
        /// <see cref="GetPath(int)"/> with <see cref="ROOT_ORDINAL"/> will return the empty path.
        /// </summary>
        public const int ROOT_ORDINAL = 0;

        /// <summary>
        /// Ordinals are always non-negative, so a negative ordinal can be used to
        /// signify an error. Methods here return <see cref="INVALID_ORDINAL"/> (-1) in this case.
        /// </summary>
        public const int INVALID_ORDINAL = -1;

        /// <summary>
        /// If the taxonomy has changed since the provided reader was opened, open and
        /// return a new <see cref="TaxonomyReader"/>; else, return <c>null</c>. The new
        /// reader, if not <c>null</c>, will be the same type of reader as the one
        /// given to this method.
        ///
        /// <para>
        /// This method is typically far less costly than opening a fully new
        /// <see cref="TaxonomyReader"/> as it shares resources with the provided
        /// <see cref="TaxonomyReader"/>, when possible.
        /// </para>
        /// </summary>
        public static T OpenIfChanged<T>(T oldTaxoReader) where T : TaxonomyReader
        {
            T newTaxoReader = (T)oldTaxoReader.DoOpenIfChanged();
            if (Debugging.AssertsEnabled) Debugging.Assert(newTaxoReader != oldTaxoReader);
            return newTaxoReader;
        }

        private volatile bool closed = false;

        // set refCount to 1 at start
        private readonly AtomicInt32 refCount = new AtomicInt32(1);

        private readonly object syncLock = new object(); // LUCENENET specific - avoid lock (this)

        // LUCENENET specific - Removed DoClose() and replaced with Dispose(true)

        /// <summary>
        /// Implements the actual opening of a new <see cref="TaxonomyReader"/> instance if
        /// the taxonomy has changed.
        /// </summary>
        /// <seealso cref="OpenIfChanged{T}(T)"/>
        protected abstract TaxonomyReader DoOpenIfChanged();

        /// <summary>
        /// Throws <see cref="ObjectDisposedException"/> if this <see cref="Index.IndexReader"/> is disposed
        /// </summary>
        protected void EnsureOpen()
        {
            if (RefCount <= 0)
            {
                throw AlreadyClosedException.Create(this.GetType().FullName, "this TaxonomyReader is disposed.");
            }
        }

        // LUCENENET specific - implementing proper dispose pattern
#pragma warning disable CA1063 // Implement IDisposable Correctly
        public void Dispose()
#pragma warning restore CA1063 // Implement IDisposable Correctly
        {
            if (closed) return;
            UninterruptableMonitor.Enter(syncLock);
            try
            {
                if (closed) return;
                DecRef();
                closed = true;
            }
            finally
            {
                UninterruptableMonitor.Exit(syncLock);
            }
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Performs the actual task of closing the resources that are used by the
        /// taxonomy reader.
        /// </summary>
        protected abstract void Dispose(bool disposing); // LUCENENET: Refactored from DoClose()

        /// <summary>
        /// Expert: decreases the refCount of this TaxonomyReader instance. If the
        /// refCount drops to 0 this taxonomy reader is closed.
        /// </summary>
        public void DecRef()
        {
            EnsureOpen();
            int rc = refCount.DecrementAndGet();
            if (rc == 0)
            {
                bool success = false;
                try
                {
                    Dispose(true); // LUCENENET specific - changed from DoClose() to Dispose(bool)
                    closed = true;
                    success = true;
                }
                finally
                {
                    if (!success)
                    {
                        // Put reference back on failure
                        refCount.IncrementAndGet();
                    }
                }
            }
            else if (rc < 0)
            {
                throw IllegalStateException.Create("too many decRef calls: refCount is " + rc + " after decrement");
            }
        }

        /// <summary>
        /// Returns a <see cref="ParallelTaxonomyArrays"/> object which can be used to
        /// efficiently traverse the taxonomy tree.
        /// </summary>
        public abstract ParallelTaxonomyArrays ParallelTaxonomyArrays { get; }

        /// <summary>
        /// Returns an iterator over the children of the given ordinal.
        /// </summary>
        public virtual ChildrenEnumerator GetChildren(int ordinal)
        {
            ParallelTaxonomyArrays arrays = ParallelTaxonomyArrays;
            int child = ordinal >= 0 ? arrays.Children[ordinal] : INVALID_ORDINAL;
            return new ChildrenEnumerator(child, arrays.Siblings);
        }

        /// <summary>
        /// Retrieve user committed data.
        /// </summary>
        /// <seealso cref="ITaxonomyWriter.CommitData"/>
        public abstract IDictionary<string, string> CommitUserData { get; }

        /// <summary>
        /// Returns the ordinal of the category given as a path. The ordinal is the
        /// category's serial number, an integer which starts with 0 and grows as more
        /// categories are added (note that once a category is added, it can never be
        /// deleted).
        /// </summary>
        /// <returns> the category's ordinal or <see cref="INVALID_ORDINAL"/> if the category
        ///         wasn't found. </returns>
        public abstract int GetOrdinal(FacetLabel categoryPath);

        /// <summary>
        /// Returns ordinal for the dim + path.
        /// </summary>
        public virtual int GetOrdinal(string dim, string[] path)
        {
            string[] fullPath = new string[path.Length + 1];
            fullPath[0] = dim;
            Array.Copy(path, 0, fullPath, 1, path.Length);
            return GetOrdinal(new FacetLabel(fullPath));
        }

        /// <summary>
        /// Returns the path name of the category with the given ordinal.
        /// </summary>
        public abstract FacetLabel GetPath(int ordinal);

        /// <summary>
        /// Returns the current refCount for this taxonomy reader.
        /// </summary>
        public int RefCount => refCount;

        /// <summary>
        /// Returns the number of categories in the taxonomy. Note that the number of
        /// categories returned is often slightly higher than the number of categories
        /// inserted into the taxonomy; This is because when a category is added to the
        /// taxonomy, its ancestors are also added automatically (including the root,
        /// which always get ordinal 0).
        /// </summary>
        public abstract int Count { get; }

        /// <summary>
        /// Expert: increments the refCount of this TaxonomyReader instance. RefCounts
        /// can be used to determine when a taxonomy reader can be closed safely, i.e.
        /// as soon as there are no more references. Be sure to always call a
        /// corresponding <see cref="DecRef"/>, in a finally clause; otherwise the reader may never
        /// be disposed.
        /// </summary>
        public void IncRef()
        {
            EnsureOpen();
            refCount.IncrementAndGet();
        }

        /// <summary>
        /// Expert: increments the refCount of this TaxonomyReader
        /// instance only if it has not been closed yet.  Returns
        /// <c>true</c> on success.
        /// </summary>
        public bool TryIncRef()
        {
            int count;
            while ((count = refCount) > 0)
            {
                if (refCount.CompareAndSet(count, count + 1))
                {
                    return true;
                }
            }
            return false;
        }
    }
}


text:
CREATE TABLE Localization (
    id_localization SERIAL PRIMARY KEY,
    id_onibus INTEGER NOT NULL,
    lat TEXT NOT NULL,
    long TEXT NOT NULL,
    time TIMESTAMP NOT NULL
);


text:
<?php
//OnState.php
class OnState implements IState
{
    private $context;

    public function __construct(Context $contextNow)
    {
        $this->context = $contextNow;
    }

    public function turnLightOn()
    {
        echo "Light is already on-> take no action
";
    }

    public function turnLightOff()
    {
        echo "Lights off!
";
        $this->context-setState($this->context->getOffState());
    }
}


text:
<?php

namespace Installer;

use Composer\Script\Event;
use Exception;

class RequirementScripts
{

    /**
     * messages container
     *
     * @var array
     */
    protected static $messages = [];

    /**
     * Handle the pre-update or pre-install Composer event.
     *
     * @param  \Composer\Script\Event  $event
     *
     * @return void
     */
    public static function preUpdate(Event $event)
    {
        print "\nChecking installation requirements\n";
        $isValid = self::validateNode() && self::validateBower() && self::validateGrunt();
        if ($isValid) {
            return;
        }
        foreach (self::$messages as $message) {
            print "\n" . $message . "\n";
        }
    }

    /**
     * validates node
     *
     * @return boolean
     * @throws Exception
     */
    protected static function validateNode()
    {
        try {
            print "\nChecking node requirement, ";
            $npmVersion = null;
            exec('npm -v ', $npmVersion);
            if (!isset($npmVersion[0])) {
                throw new Exception('Unable to find Node. Npm command not found.');
            }

            if (strlen($npmVersion[0]) <= 0) {
                throw new Exception('Invalid node version.');
            }
            print sprintf("found %s node version.", $npmVersion[0]);
        } catch (Exception $ex) {
            array_push(self::$messages, $ex->getMessage());
            return false;
        }
        return true;
    }

    /**
     * validates grunt
     *
     * @return boolean
     * @throws Exception
     */
    protected static function validateGrunt()
    {
        try {
            print "\nChecking grunt requirements, ";
            $gruntVersion = null;
            exec('grunt -v ', $gruntVersion);
            if (!isset($gruntVersion[0])) {
                throw new Exception('Unable to find grunt. Grunt command not found.');
            }

            if (strlen($gruntVersion[0]) <= 0) {
                throw new Exception('Invalid grunt version.');
            }
            print sprintf("found %s grunt version.\n", $gruntVersion[0]);
        } catch (Exception $ex) {
            array_push(self::$messages, $ex->getMessage());
            return false;
        }
        return true;
    }

    /**
     * validates bower
     *
     * @return boolean
     * @throws Exception
     */
    protected static function validateBower()
    {
        try {
            print "\nChecking bower requirements, ";
            $bowerVersion = null;
            exec('bower -v ', $bowerVersion);
            if (!isset($bowerVersion[0])) {
                throw new Exception('Unable to find bower. Bower command not found.');
            }

            if (strlen($bowerVersion[0]) <= 0) {
                throw new Exception('Invalid bower version.');
            }
            print sprintf("found %s bower version.", $bowerVersion[0]);
        } catch (Exception $ex) {
            array_push(self::$messages, $ex->getMessage());
            return false;
        }
        return true;
    }

}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <link rel="shortcut icon" type="image/png" href="/static/images/logo.png"/>
  <meta name="viewport" content="user-scalable=no,width=device-width,initial-scale=1,maximum-scale=1">
  <title>uiv - Bootstrap 3 Components Built with Vue 2.</title>


text:
package info.guardianproject.otr.app.im.app;

import info.guardianproject.otr.app.im.provider.Imps;
import info.guardianproject.otr.app.im.R;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.View;

public class ChatBackgroundMaker {
    private final Drawable mIncomingBg;
    private final Drawable mDivider;
    private final Rect mPadding;

    public ChatBackgroundMaker(Context context) {
        Resources res = context.getResources();
        mIncomingBg = res.getDrawable(R.drawable.textfield_im_received);
        mDivider = res.getDrawable(R.drawable.text_divider_horizontal);
        mPadding = new Rect();
        mIncomingBg.getPadding(mPadding);
    }

    public void setBackground(MessageView view, String contact, int type) {

    }
}


text:
mesh-2.0
========

Implements a mesh-like system for Scratch 2.0, using Scratch 2.0's extension feature and a node.js server.

Connecting to mesh
========

When the flag is clicked, the first thing you'll want to do is use one of the connect to mesh blocks.

The block "connect to public mesh" allows you to easily connect to the mesh server run by bobbybee. This is a service provided for your own benefit, so please don't abuse it :) If you have a high bandwidth application, read on.

The block "connect to mesh port" has fields for an IP address and port, which whoever sets up the mesh server will tell you the values for (see the section "Hosting mesh" for more information). This should be used if you have a complex game.

After a sucessful connection to the mesh servers, use the 'when connected to mesh' as the true beginning of the project.

Game name and version
========

Every mesh project must have a name and version. On the Scratch 2.0 website, this defaults to the project ID, so if you share your project on Scratch 2.0, you can ignore this section. However, if the project is distributed as an sb2, you need to set the game name and version. The game name should be a unique name of the project, and the version should be updated every time you update the project. This allows mesh to connect only to other people on your project, as opposed to some arbitrary project.

Match-making
========

Currently, once you connect to a mesh server using the connect block, your project is in a restricted state, where you can not properly use mesh. To get to a state where the broadcast and variable features are active, you must have a partner with whom you will play/use the project in question with. There are two mechanisms of doing this:

A) Named groups. One player will create a group with their name (typically their username), and the other player will use the join group block using the name the other player used to find and join the group. This allows two friends to play together, but requires that they communicated about playing through some other medium (such as comments on their Scratch profiles or Skype messages).

or B) "Any" groups. Using the "join any group" block, the server will match the player with the next available player who also uses the "join any group". Perfect if you just would like to play the game, and do not care who you will play the game with.

Once a second player is found, the "when group full" hat block will activate.

Using mesh
========

Once you are in a group, you can use the following blocks for communication:

- the "when I receive" and "broadcast" blocks, which are identical to the standard blocks, except they are broadcasted to the other Scratcher's computer
- the "set variable to value" and "value of variable" blocks which will allow you to share variables over the network (note: no variable creation is required)
- the "my player ID" block which will give you a unique number within your group (useful for determining who get's what avatar or who controls shared objects, for instance)

Advanced: Hosting mesh
========

At the time of writing (August 21, 2014) there is a public mesh server hosted by bobbybee. You can simply use the "connect to public mesh" to use it, and therefore ignore this section. However, if you have a complex application or game, you should follow these instructions to host your own server.

To host mesh, you will need node.js.

1) download and install node.js from the node.js website (http://nodejs.org). If you already have node, you can skip this step

2) download the server.js file from this repository and save it in an empty folder

3) cd into the folder with the server.js file

4) at your shell, enter

$ npm install

5) finally, to start the server from this directory, enter at your shell:

$ npm start

You will need to repeat steps 3 and 5 whenever you would like to start the mesh server.

On the Scratch side, the "connect to mesh server port" block should connect to your IP address and the port 4354. For making the mesh server publicly available, use your public IP address, port forwarding the port 4354. For playing over LAN (within your network), find your private IP address (typically 192.168.1.*) and connect using that from Scratch.