text:
package com.perforce.p4java.tests.dev.unit.bug.r161;

import com.perforce.p4java.CharsetConverter;
import com.perforce.p4java.CharsetDefs;
import com.perforce.p4java.core.IChangelist;
import com.perforce.p4java.core.file.IFileSpec;
import com.perforce.p4java.exception.P4JavaException;
import com.perforce.p4java.option.server.LoginOptions;
import com.perforce.p4java.server.PerforceCharsets;
import com.perforce.p4java.tests.SimpleServerRule;
import com.perforce.p4java.tests.UnicodeServerRule;
import com.perforce.p4java.tests.dev.unit.P4JavaRshTestCase;
import com.perforce.p4java.tests.ignoreRule.ConditionallyIgnoreClassRule;
import org.apache.commons.io.IOUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

public class SubmitAndSyncUnicodeFileTypeOnUnicodeEnabledServerTest extends P4JavaRshTestCase {
    private static final String CLASS_PATH_PREFIX = "com/perforce/p4java/impl/mapbased/rpc/sys";
    private static final String RELATIVE_DEPOT_PATH = "/152Bugs/job085433/" + System.currentTimeMillis();
    private static final String TEST_FILE_PARENT_DEPOT_PATH = "//depot" + RELATIVE_DEPOT_PATH;
    private IChangelist changelist = null;
    private List<IFileSpec> submittedOrPendingFileSpecs = null;

	public static SimpleServerRule p4d = new UnicodeServerRule("r16.1", SubmitAndSyncUnicodeFileTypeOnUnicodeEnabledServerTest.class.getSimpleName());

    @ClassRule
    public static ConditionallyIgnoreClassRule ignoreWindows = ConditionallyIgnoreClassRule.ifWindows(
            "This test creates files that cannot be created in Windows",

            // p4d should only be initialized if the rule is not ignored.
            p4d);

    @BeforeClass
    public static void beforeAll() throws Exception {
        setupServer(p4d.getRSHURL(), null, null, true, null);
    }

    @Test
    public void testEncodeByJpShiftJisWithUnixLineEndingUnicodeFileUnderServerUnicodeEnabled_UnixClientLineEnding() throws Exception{
        String perforceCharset = "shiftjis";
        login(perforceCharset);

        File testResourceFile = loadFileFromClassPath(CLASS_PATH_PREFIX + "/shift_jis.txt");
        Charset matchCharset = Charset.forName(PerforceCharsets.getJavaCharsetName(perforceCharset));
        long utf8EncodedOriginalFileSize = getUnicodeFileSizeAfterEncodedByUtf8(
                testResourceFile,
                matchCharset);
        long originalFileSize = Files.size(testResourceFile.toPath());
        testSubmitFile(
                "p4TestUnixLineend",
                testResourceFile,
                "unicode",
                utf8EncodedOriginalFileSize,
                originalFileSize
        );
    }

    @Test
    public void testEncodeByJpShiftJisWithUnixLineEndingUnicodeFileUnderServerUnicodeEnabled_WinClientLineEnding() throws Exception{
        String perforceCharset = "shiftjis";
        login(perforceCharset);

        File testResourceFile = loadFileFromClassPath(CLASS_PATH_PREFIX + "/shift_jis.txt");
        Charset matchCharset = Charset.forName(PerforceCharsets.getJavaCharsetName(perforceCharset));
        int totalUnixLineEndings = 1;
        long utf8EncodedOriginalFileSize = getUnicodeFileSizeAfterEncodedByUtf8(
                testResourceFile,
                matchCharset);
        long originalFileSize = Files.size(testResourceFile.toPath());
        testSubmitFile(
                "p4TestWinLineend",
                testResourceFile,
                "unicode",
                utf8EncodedOriginalFileSize,
                originalFileSize + totalUnixLineEndings
        );
    }

    //@Test
    public void testEncodedByeEncJpWithUnixLineEndingFileWhenClientCharsetIsMatchUnderServerUnicodeEnabled_WinClientLineEnding() throws Exception {
        String perforceCharset = "eucjp";
        login(perforceCharset);

        File testResourceFile = loadFileFromClassPath(CLASS_PATH_PREFIX + "/euc-jp.txt");
        int totalUnixLineEndings = 10;
        long originalFileSize = Files.size(testResourceFile.toPath());
        Charset matchCharset = Charset.forName(PerforceCharsets.getJavaCharsetName(perforceCharset));
        long utf8EncodedOriginalFileSize = getUnicodeFileSizeAfterEncodedByUtf8(
                testResourceFile,
                matchCharset);

        testSubmitFile(
                "p4TestWinLineend",
                testResourceFile,
                "unicode",
                utf8EncodedOriginalFileSize,
                originalFileSize + totalUnixLineEndings
        );
    }

    @Test
    public void testEncodedByeGb18030WithUnixLineEndingFileWhenClientCharsetIsMatchUnderServerUnicodeEnabled_UnixClientLineEnding() throws Exception{
        String perforceCharset = "cp936";

        login(perforceCharset);
        File testResourceFile = loadFileFromClassPath(CLASS_PATH_PREFIX + "/gb18030.txt");

        long originalFileSize = Files.size(testResourceFile.toPath());
        Charset matchCharset = Charset.forName(PerforceCharsets.getJavaCharsetName(perforceCharset));
        long utf8EncodedOriginalFileSize = getUnicodeFileSizeAfterEncodedByUtf8(
                testResourceFile,
                matchCharset);

        testSubmitFile(
                "p4TestUnixLineend",
                testResourceFile,
                "unicode",
                utf8EncodedOriginalFileSize,
                originalFileSize
        );
    }

    @Test
    public void testEncodedByeGb18030WithUnixLineEndingFileWhenClientCharsetIsMatchUnderServerUnicodeEnabled_WinClientLineEnding() throws Exception{
        String perforceCharset = "cp936";

        login(perforceCharset);
        File testResourceFile = loadFileFromClassPath(CLASS_PATH_PREFIX + "/gb18030.txt");

        int totalUnixLineEndings = 1;
        long originalFileSize = Files.size(testResourceFile.toPath());
        Charset matchCharset = Charset.forName(PerforceCharsets.getJavaCharsetName(perforceCharset));
        long utf8EncodedOriginalFileSize = getUnicodeFileSizeAfterEncodedByUtf8(
                testResourceFile,
                matchCharset);

        testSubmitFile(
                "p4TestWinLineend",
                testResourceFile,
                "unicode",
                utf8EncodedOriginalFileSize,
                originalFileSize + totalUnixLineEndings
        );
    }

    @Test
    public void testEncodedByeGb18030WithWinLineEndingFileWhenClientCharsetIsMatchUnderServerUnicodeEnabled_UnixClientLineEnding() throws Exception{
        String perforceCharset = "cp936";
        login(perforceCharset);

        File testResourceFile = loadFileFromClassPath("com/perforce/p4java/common/io/gb18030_win_line_endings.txt");
        long originalFileSize = Files.size(testResourceFile.toPath());
        Charset matchCharset = Charset.forName(PerforceCharsets.getJavaCharsetName(perforceCharset));
        long utf8EncodedOriginalFileSize = getUnicodeFileSizeAfterEncodedByUtf8(
                testResourceFile,
                matchCharset);

        testSubmitFile(
                "p4TestUnixLineend",
                testResourceFile,
                "unicode",
                utf8EncodedOriginalFileSize,
                originalFileSize
        );
    }

    @Test
    public void testEncodedByeGb18030WithWinLineEndingFileWhenClientCharsetIsMatchUnderServerUnicodeEnabled_WinClientLineEnding() throws Exception{
        String perforceCharset = "cp936";
        login(perforceCharset);

        File testResourceFile = loadFileFromClassPath("com/perforce/p4java/common/io/gb18030_win_line_endings.txt");
        int totalWinLineEndings = 4;
        long originalFileSize = Files.size(testResourceFile.toPath());
        Charset matchCharset = Charset.forName(PerforceCharsets.getJavaCharsetName(perforceCharset));
        long utf8EncodedOriginalFileSize = getUnicodeFileSizeAfterEncodedByUtf8(
                testResourceFile,
                matchCharset);

        testSubmitFile(
                "p4TestWinLineend",
                testResourceFile,
                "unicode",
                utf8EncodedOriginalFileSize - totalWinLineEndings,
                originalFileSize
        );
    }

    @Ignore("A unicode server must have a charset, might reuse test when 'auto' is supported")
    @Test
    public void testEncodedByeEncJpWithUnixLineEndingFileExpectedDetectAsTextWhenClientCharsetIsNullUnderServerUnicodeEnabled_UnixClientLineEnding() throws Exception {
        File testResourceFile = loadFileFromClassPath(CLASS_PATH_PREFIX + "/euc-jp.txt");
        login("none");

        long originalFileSize = Files.size(testResourceFile.toPath());
        testSubmitFile(
                "p4TestUnixLineend",
                testResourceFile,
                "text",
                originalFileSize,
                originalFileSize
        );
    }

    @Test
    public void testEncodedByeEncJpWithUnixLineEndingFileWhenClientCharsetIsNotMatchRealFileEncodeUnderServerUnicodeEnabledThenTradeAsBinary_WinClientLineEnding() throws Exception{
        File testResourceFile = loadFileFromClassPath(CLASS_PATH_PREFIX + "/euc-jp.txt");
        login("shiftjis");

        int totalUnixLineEndings = 10;
        long originalFileSize = Files.size(testResourceFile.toPath());
        testSubmitFile(
                "p4TestWinLineend",
                testResourceFile,
                "text",
                originalFileSize,
                originalFileSize + totalUnixLineEndings
        );
    }

    @Test
    public void testEncodedByeGb18030WithUnixLineEndingFileWhenClientCharsetIsNotMatchRealFileEncodeUnderServerUnicodeEnabledThenTradeAsBinary_UnixClientLineEnding() throws Exception{
        File testResourceFile = loadFileFromClassPath(CLASS_PATH_PREFIX + "/gb18030.txt");
        login("shiftjis");

        long originalFileSize = Files.size(testResourceFile.toPath());
        testSubmitFile(
                "p4TestUnixLineend",
                testResourceFile,
                "text",
                originalFileSize,
                originalFileSize
        );
    }

    private void testSubmitFile(
            final String clientName,
            final File testResourceFile,
            final String expectedFileTypeString,
            final long expectedServerSideFileSize,
            final long expectedSyncedLocalFileSize) throws Exception {

        String depotPath = TEST_FILE_PARENT_DEPOT_PATH + "/" + testResourceFile.getName();
        SubmittingSupplier submittingSupplier = submitFileThatLoadFromClassPath(clientName,
                depotPath,
                RELATIVE_DEPOT_PATH,
                testResourceFile);

        submittedOrPendingFileSpecs = new ArrayList<>();
        submittedOrPendingFileSpecs.add(submittingSupplier.submittedFileSpec());
        changelist = submittingSupplier.changelist();
        Path targetLocalFile = submittingSupplier.targetLocalFile();

        verifyServerSideFileType(depotPath, expectedFileTypeString);
        verifyServerSideFileSize(depotPath, expectedServerSideFileSize);
        verifyFileSizeAfterSyncFromDepot(depotPath, targetLocalFile, expectedSyncedLocalFileSize);
    }

    private void login(String clientCharset) throws P4JavaException {
        setClientCharsetIfServerSupportUnicode(server, clientCharset);
        server.setUserName(getUserName());
        server.login(getPassword(), new LoginOptions());
    }

    private long getUnicodeFileSizeAfterEncodedByUtf8(File testResourceFile, Charset clientCharset) throws Exception {
        try (InputStream fileInputStream = new FileInputStream(testResourceFile)) {
            byte[] fileBytes = IOUtils.toByteArray(fileInputStream);
            ByteBuffer buf = ByteBuffer.wrap(fileBytes);
    		CharsetConverter convert = new CharsetConverter(clientCharset, CharsetDefs.UTF8);
    		return convert.convert(buf).limit();
        }
    }

    @After
    public void afterEach() throws Exception {
        revertChangelist(changelist, submittedOrPendingFileSpecs);
    }

    @AfterClass
    public static void afterAll() throws Exception {
        afterEach(server);
    }
}


text:
import struct
import re

try:
    import io as StringIO
except ImportError:
    import io

from .err import Warning, Error, InterfaceError, DataError, \
             DatabaseError, OperationalError, IntegrityError, InternalError, \
            NotSupportedError, ProgrammingError

insert_values = re.compile(r'\svalues\s*(\(.+\))', re.IGNORECASE)

class Cursor(object):
    '''
    This is the object you use to interact with the database.
    '''
    def __init__(self, connection):
        '''
        Do not create an instance of a Cursor yourself. Call
        connections.Connection.cursor().
        '''
        from weakref import proxy
        self.connection = proxy(connection)
        self.description = None
        self.rownumber = 0
        self.rowcount = -1
        self.arraysize = 1
        self._executed = None
        self.messages = []
        self.errorhandler = connection.errorhandler
        self._has_next = None
        self._rows = ()

    def __del__(self):
        '''
        When this gets GC'd close it.
        '''
        self.close()

    def close(self):
        '''
        Closing a cursor just exhausts all remaining data.
        '''
        if not self.connection:
            return
        try:
            while self.nextset():
                pass
        except:
            pass

        self.connection = None

    def _get_db(self):
        if not self.connection:
            self.errorhandler(self, ProgrammingError, "cursor closed")
        return self.connection

    def _check_executed(self):
        if not self._executed:
            self.errorhandler(self, ProgrammingError, "execute() first")

    def setinputsizes(self, *args):
        """Does nothing, required by DB API."""

    def setoutputsizes(self, *args):
        """Does nothing, required by DB API."""

    def nextset(self):
        ''' Get the next query set '''
        if self._executed:
            self.fetchall()
        del self.messages[:]

        if not self._has_next:
            return None
        connection = self._get_db()
        connection.next_result()
        self._do_get_result()
        return True

    def execute(self, query, args=None):
        ''' Execute a query '''
        from sys import exc_info

        conn = self._get_db()
        charset = conn.charset
        del self.messages[:]

        # TODO: make sure that conn.escape is correct

        if args is not None:
            if isinstance(args, tuple) or isinstance(args, list):
                escaped_args = tuple(conn.escape(arg) for arg in args)
            elif isinstance(args, dict):
                escaped_args = dict((key, conn.escape(val)) for (key, val) in list(args.items()))
            else:
                #If it's not a dictionary let's try escaping it anyways.
                #Worst case it will throw a Value error
                escaped_args = conn.escape(args)

            query = query % escaped_args

        if isinstance(query, str):
            query = query.encode(charset)

        result = 0
        try:
            result = self._query(query)
        except:
            exc, value, tb = exc_info()
            del tb
            self.messages.append((exc,value))
            self.errorhandler(self, exc, value)

        self._executed = query
        return result

    def executemany(self, query, args):
        ''' Run several data against one query '''
        del self.messages[:]
        #conn = self._get_db()
        if not args:
            return
        #charset = conn.charset
        #if isinstance(query, unicode):
        #    query = query.encode(charset)

        self.rowcount = sum([ self.execute(query, arg) for arg in args ])
        return self.rowcount

    def callproc(self, procname, args=()):
        """Execute stored procedure procname with args

        procname -- string, name of procedure to execute on server

        args -- Sequence of parameters to use with procedure

        Returns the original args.

        Compatibility warning: PEP-249 specifies that any modified
        parameters must be returned. This is currently impossible
        as they are only available by storing them in a server
        variable and then retrieved by a query. Since stored
        procedures return zero or more result sets, there is no
        reliable way to get at OUT or INOUT parameters via callproc.
        The server variables are named @_procname_n, where procname
        is the parameter above and n is the position of the parameter
        (from zero). Once all result sets generated by the procedure
        have been fetched, you can issue a SELECT @_procname_0, ...
        query using .execute() to get any OUT or INOUT values.

        Compatibility warning: The act of calling a stored procedure
        itself creates an empty result set. This appears after any
        result sets generated by the procedure. This is non-standard
        behavior with respect to the DB-API. Be sure to use nextset()
        to advance through all result sets; otherwise you may get
        disconnected.
        """
        conn = self._get_db()
        for index, arg in enumerate(args):
            q = "SET @_%s_%d=%s" % (procname, index, conn.escape(arg))
            if isinstance(q, str):
                q = q.encode(conn.charset)
            self._query(q)
            self.nextset()

        q = "CALL %s(%s)" % (procname,
                             ','.join(['@_%s_%d' % (procname, i)
                                       for i in range(len(args))]))
        if isinstance(q, str):
            q = q.encode(conn.charset)
        self._query(q)
        self._executed = q

        return args

    def fetchone(self):
        ''' Fetch the next row '''
        self._check_executed()
        if self._rows is None or self.rownumber >= len(self._rows):
            return None
        result = self._rows[self.rownumber]
        self.rownumber += 1
        return result

    def fetchmany(self, size=None):
        ''' Fetch several rows '''
        self._check_executed()
        end = self.rownumber + (size or self.arraysize)
        result = self._rows[self.rownumber:end]
        if self._rows is None:
            return None
        self.rownumber = min(end, len(self._rows))
        return result

    def fetchall(self):
        ''' Fetch all the rows '''
        self._check_executed()
        if self._rows is None:
            return None
        if self.rownumber:
            result = self._rows[self.rownumber:]
        else:
            result = self._rows
        self.rownumber = len(self._rows)
        return result

    def scroll(self, value, mode='relative'):
        self._check_executed()
        if mode == 'relative':
            r = self.rownumber + value
        elif mode == 'absolute':
            r = value
        else:
            self.errorhandler(self, ProgrammingError,
                    "unknown scroll mode %s" % mode)

        if r < 0 or r >= len(self._rows):
            self.errorhandler(self, IndexError, "out of range")
        self.rownumber = r

    def _query(self, q):
        conn = self._get_db()
        self._last_executed = q
        conn.query(q)
        self._do_get_result()
        return self.rowcount

    def _do_get_result(self):
        conn = self._get_db()
        self.rowcount = conn._result.affected_rows

        self.rownumber = 0
        self.description = conn._result.description
        self.lastrowid = conn._result.insert_id
        self._rows = conn._result.rows
        self._has_next = conn._result.has_next

    def __iter__(self):
        return iter(self.fetchone, None)

    Warning = Warning
    Error = Error
    InterfaceError = InterfaceError
    DatabaseError = DatabaseError
    DataError = DataError
    OperationalError = OperationalError
    IntegrityError = IntegrityError
    InternalError = InternalError
    ProgrammingError = ProgrammingError
    NotSupportedError = NotSupportedError

class DictCursor(Cursor):
    """A cursor which returns results as a dictionary"""

    def execute(self, query, args=None):
        result = super(DictCursor, self).execute(query, args)
        if self.description:
            self._fields = [ field[0] for field in self.description ]
        return result

    def fetchone(self):
        ''' Fetch the next row '''
        self._check_executed()
        if self._rows is None or self.rownumber >= len(self._rows):
            return None
        result = dict(list(zip(self._fields, self._rows[self.rownumber])))
        self.rownumber += 1
        return result

    def fetchmany(self, size=None):
        ''' Fetch several rows '''
        self._check_executed()
        if self._rows is None:
            return None
        end = self.rownumber + (size or self.arraysize)
        result = [ dict(list(zip(self._fields, r))) for r in self._rows[self.rownumber:end] ]
        self.rownumber = min(end, len(self._rows))
        return tuple(result)

    def fetchall(self):
        ''' Fetch all the rows '''
        self._check_executed()
        if self._rows is None:
            return None
        if self.rownumber:
            result = [ dict(list(zip(self._fields, r))) for r in self._rows[self.rownumber:] ]
        else:
            result = [ dict(list(zip(self._fields, r))) for r in self._rows ]
        self.rownumber = len(self._rows)
        return tuple(result)

redpajama_set_name: RedPajamaGithub


text:
package org.apache.metamodel.util;

import java.util.Arrays;

import junit.framework.TestCase;

public class ExclusionPredicateTest extends TestCase {

    public void testEval() throws Exception {
        ExclusionPredicate<String> predicate = new ExclusionPredicate<String>(Arrays.asList("foo","bar","baz"));

        assertFalse(predicate.test("foo"));
        assertFalse(predicate.test("bar"));
        assertFalse(predicate.test("baz"));

        assertTrue(predicate.test("hello world"));
    }
}


text:
"""Image classification models."""

import lingvo.compat as tf
from lingvo.core import base_model
from lingvo.core import layers
from lingvo.core import metrics
from lingvo.core import plot
from lingvo.core import py_utils
from lingvo.core import schedule
import numpy as np

def TopKAccuracy(k, logits, labels, weights):
  """Compute top-k accuracy.

  Args:
    k: An int scalar. Top-k.
    logits: A [N, C] float tensor.
    labels: A [N] int vector.
    weights: A [N] float vector.

  Returns:
    A float scalar. The accuracy at precision k.
  """
  logits = py_utils.HasRank(logits, 2)
  n, _ = tf.unstack(tf.shape(logits), 2)
  labels = py_utils.HasShape(labels, [n])
  weights = py_utils.HasShape(weights, [n])
  correct = tf.nn.in_top_k(targets=labels, predictions=logits, k=k)
  return tf.reduce_sum(tf.cast(correct, weights.dtype) * weights) / tf.maximum(
      1e-8, tf.reduce_sum(weights))

class BaseClassifier(base_model.BaseTask):
  """Base class for image classifier."""

  @classmethod
  def Params(cls):
    p = super().Params()
    p.Define('softmax', layers.SimpleFullSoftmax.Params(), 'Softmax layer.')
    p.Define('add_image_summary', True, 'If True, adds image summary in '
             'evaler/decoder jobs.')
    return p

  def _AddSummary(self, batch, prediction):
    """Adds image summaries for the batch."""
    p = self.params
    if not self.do_eval or not p.add_image_summary:
      # Image summaries only works in evaler/decoder.
      return

    def Draw(fig, axes, img, label, pred):
      plot.AddImage(
          fig=fig,
          axes=axes,
          data=img[:, :, 0] / 256.,
          show_colorbar=False,
          suppress_xticks=True,
          suppress_yticks=True)
      axes.text(
          x=0.5,
          y=0,
          s=u'%d vs. %d' % (label, pred),
          transform=axes.transAxes,
          horizontalalignment='center')

    with plot.MatplotlibFigureSummary(
        'examples', figsize=(1, 1), max_outputs=10) as fig:
      fig.AddSubplot([batch.raw, batch.label, prediction], Draw)

  def _Accuracy(self, k, logits, labels, weights):
    """Compute top-k accuracy.

    Args:
      k: An int scalar. Top-k.
      logits: A [N, C] float tensor.
      labels: A [N] int vector.
      weights: A [N] float vector.

    Returns:
      A float scalar. The accuracy at precision k.
    """
    return TopKAccuracy(k, logits, labels, weights)

class ModelV1(BaseClassifier):
  """CNNs with maxpooling followed by a softmax."""

  @classmethod
  def Params(cls):
    p = super().Params()
    p.Define(
        'filter_shapes', [(0, 0, 0, 0)],
        'Conv filter shapes. Must be a list of sequences of 4. '
        'Elements are in order of height, width, in_channel, out_channel')
    p.Define(
        'window_shapes', [(0, 0)],
        'Max pooling window shapes. Must be a list of sequences of 2. '
        'Elements are in order of height, width.')
    p.Define('fc_tpl', layers.FCLayer.Params(),
             'Params for the fully-connected logits computation.')
    p.Define('batch_norm', False, 'Apply BN or not after the conv.')
    p.Define('dropout_prob', 0.0,
             'Probability of the dropout applied after pooling.')

    tp = p.train
    tp.learning_rate = 1e-4  # Adam base LR.
    tp.lr_schedule = (
        schedule.LinearRampupExponentialDecayScaledByNumSplitSchedule.Params()
        .Set(warmup=100, decay_start=100000, decay_end=1000000, min=0.1))
    return p

  def __init__(self, params):
    super().__init__(params)
    p = self.params
    assert p.name

    assert len(p.filter_shapes) == len(p.window_shapes)

    # A few conv + max pooling layers.
    shape = [None] + list(p.input.data_shape)
    conv_params = []
    pooling_params = []
    for i, (kernel, window) in enumerate(zip(p.filter_shapes, p.window_shapes)):
      conv_params.append(layers.ConvLayer.Params().Set(
          name='conv%d' % i,
          filter_shape=kernel,
          filter_stride=(1, 1),
          batch_norm=p.batch_norm))
      pooling_params.append(layers.PoolingLayer.Params().Set(
          name='pool%d' % i, window_shape=window, window_stride=window))
    self.CreateChildren('conv', conv_params)
    self.CreateChildren('pool', pooling_params)

    # Logs expected activation shapes.
    for i in range(len(self.conv)):
      tf.logging.info('shape %d %s', i, shape)
      shape = self.conv[i].OutShape(shape)
      tf.logging.info('shape %d %s', i, shape)
      shape = self.pool[i].OutShape(shape)
    tf.logging.info('shape %s', shape)

    # FC layer to project down to p.softmax.input_dim.
    self.CreateChild(
        'fc',
        p.fc_tpl.Copy().Set(
            name='fc',
            input_dim=np.prod(shape[1:]),
            output_dim=p.softmax.input_dim))
    self.CreateChild('softmax', p.softmax)

  def FPropTower(self, theta, input_batch):
    p = self.params
    batch = tf.shape(input_batch.data)[0]
    height, width, depth = p.input.data_shape
    act = tf.reshape(input_batch.data, [batch, height, width, depth])
    for i in range(len(self.conv)):
      # Conv, BN (optional)
      act, _ = self.conv[i].FProp(theta.conv[i], act)
      # MaxPool
      act = self.pool[i].FProp(theta.pool[i], act)
      # Dropout (optional)
      if p.dropout_prob > 0.0 and not self.do_eval:
        act = tf.nn.dropout(act, rate=p.dropout_prob, seed=p.random_seed)
    # FC
    act = self.fc.FProp(theta.fc, tf.reshape(act, [batch, -1]))

    # Softmax
    labels = tf.cast(input_batch.label, tf.int64)
    xent = self.softmax.FProp(
        theta=theta.softmax,
        inputs=act,
        class_weights=input_batch.weight,
        class_ids=labels)

    self._AddSummary(input_batch, xent.per_example_argmax)

    rets = {
        'loss': (xent.avg_xent, batch),
        'log_pplx': (xent.avg_xent, batch),
        'num_preds': (batch, 1),
    }
    if self.do_eval:
      acc1 = self._Accuracy(1, xent.logits, labels, input_batch.weight)
      acc5 = self._Accuracy(5, xent.logits, labels, input_batch.weight)
      rets.update(
          accuracy=(acc1, batch),
          acc5=(acc5, batch),
          error=(1. - acc1, batch),
          error5=(1. - acc5, batch))
    return rets, {'loss': xent.per_example_xent}

  def Decode(self, input_batch):
    with tf.name_scope('decode'):
      return self.FPropDefaultTheta(input_batch)[0]

  def CreateDecoderMetrics(self):
    return {
        'num_samples_in_batch': metrics.AverageMetric(),
    }

  def PostProcessDecodeOut(self, dec_out_dict, dec_metrics_dict):
    dec_metrics_dict['num_samples_in_batch'].Update(
        dec_out_dict['num_samples_in_batch'][0])

class ModelV2(BaseClassifier):
  """CNNs followed by a softmax."""

  @classmethod
  def Params(cls):
    p = super().Params()
    p.Define('extract', None, 'Param for the layer to extract image features.')
    p.Define('label_smoothing', 0., 'Smooth the labels towards 1/num_classes.')
    p.Define('compute_accuracy_for_training', False,
             'Whether to compute accuracy for training.')
    return p

  def __init__(self, params):
    super().__init__(params)
    p = self.params
    assert p.name

    self.CreateChild('extract', p.extract)
    self.CreateChild('softmax', p.softmax)

  def ComputePredictions(self, theta, input_batch):
    # Forward through layers.
    act = self.extract.FProp(theta.extract, input_batch.data)
    # Avg pool
    if py_utils.GetRank(act) == 4:
      act = tf.reduce_mean(act, axis=[1, 2])
    act = py_utils.HasRank(act, 2)
    logits = self.softmax.Logits(theta.softmax, act)
    return py_utils.NestedMap(act=act, logits=logits)

  def ComputeLoss(self, theta, predictions, input_batch):
    p = self.params
    batch = tf.shape(input_batch.data)[0]
    act = predictions.act
    with tf.ops.colocate_with(act):
      tf.logging.info("{}'s device: {}".format(act, act.device))
      # Softmax
      if py_utils.GetRank(input_batch.label) == 1:
        # Create one_hot labels if rank is 1.
        labels = tf.cast(input_batch.label, tf.int64)
        onehot_labels = tf.one_hot(labels, p.softmax.num_classes)
      else:
        onehot_labels = input_batch.label
        labels = tf.math.argmax(onehot_labels, axis=-1)
      if p.label_smoothing > 0:
        smooth_positives = 1.0 - p.label_smoothing
        smooth_negatives = p.label_smoothing / p.softmax.num_classes
        onehot_labels = onehot_labels * smooth_positives + smooth_negatives

      xent = self.softmax.FProp(
          theta=theta.softmax,
          inputs=act,
          class_weights=input_batch.weight,
          class_probabilities=onehot_labels)

    self._AddSummary(input_batch, xent.per_example_argmax)

    rets = {
        'loss': (xent.avg_xent, batch),
        'log_pplx': (xent.avg_xent, batch),
        'num_preds': (batch, 1),
    }
    if self.do_eval or p.compute_accuracy_for_training:
      acc1 = self._Accuracy(1, xent.logits, labels, input_batch.weight)
      acc5 = self._Accuracy(5, xent.logits, labels, input_batch.weight)
      rets.update(
          accuracy=(acc1, batch),
          acc5=(acc5, batch),
          error=(1. - acc1, batch),
          error5=(1. - acc5, batch))
    return rets, {'loss': xent.per_example_xent}

  def Inference(self):
    """Constructs inference subgraphs.

    Returns:
      dict: A dictionary of the form ``{'subgraph_name': (fetches, feeds)}``.
      Each of fetches and feeds is itself a dictionary which maps a string name
      (which describes the tensor) to a corresponding tensor in the inference
      graph which should be fed/fetched from.
    """
    subgraphs = {}
    with tf.name_scope('inference'):
      subgraphs['default'] = self._InferenceSubgraph_Default()
    return subgraphs

  def _InferenceSubgraph_Default(self):
    """Constructs graph for single-image inference.

    Returns:
      (fetches, feeds) where both fetches and feeds are dictionaries. Each
      dictionary consists of keys corresponding to tensor names, and values
      corresponding to a tensor in the graph which should be input/read from.
    """
    p = self.params
    with tf.name_scope('default'):
      normalized_image = tf.placeholder(
          dtype=p.dtype, shape=p.input.data_shape, name='normalized_image')
      inputs = py_utils.NestedMap(data=normalized_image[tf.newaxis, ...])
      logits = tf.reshape(
          self.ComputePredictions(self.theta, inputs).logits,
          [p.softmax.num_classes],
          name='logits')
      feeds = {
          'normalized_image': normalized_image,
      }
      fetches = {
          'logits': logits,
          'probs': tf.nn.softmax(logits, name='probs'),
          'prediction': tf.argmax(logits, name='prediction'),
      }
      return fetches, feeds

  def DecodeWithTheta(self, theta, input_batch):
    """Constructs the decode graph for decoding with theta."""
    predictions = self.ComputePredictions(theta, input_batch)
    labels = tf.cast(input_batch.label, tf.int64)
    ret = py_utils.NestedMap()
    ret.correct_top1 = tf.nn.in_top_k(
        targets=labels, predictions=predictions.logits, k=1)
    ret.correct_top5 = tf.nn.in_top_k(
        targets=labels, predictions=predictions.logits, k=5)
    return ret


text:
require("exampleObject.js");

suite("An exampleObject can", function(){

	var ex;

	before(function(){
		ex = new ExampleObject();
	})

	test("add two numbers", function(){
		assertEquals(4, ex.add(2, 2));
	});

	test("remember the last result", function(){
		ex.add(2, 2);
		assertEquals(4, ex.getLastResult());
	});

});


text:
module NiwaTextream
  class MainPage
    attr_accessor :url

    @@url = nil
    # mechanize object
    @mechanize = nil
    # header object
    @header = nil
    # body object
    @body = nil

    @page = nil

    def initialize(mechanize)
      @mechanize = mechanize
    end

    # go to page by using mechanize
    def self.goTo(mechanize)
      @page = mechanize.get(@@url)
    end

    def self.url
      @@url
    end
  end
end


text:
package com.github.steveice10.mc.protocol.packet.ingame.server;

import com.github.steveice10.packetlib.io.NetInput;
import com.github.steveice10.packetlib.io.NetOutput;
import com.github.steveice10.packetlib.packet.Packet;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.With;

import java.io.IOException;

@Data
@With
@Setter(AccessLevel.NONE)
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor
public class ServerPluginMessagePacket implements Packet {
    private @NonNull String channel;
    private @NonNull byte[] data;

    @Override
    public void read(NetInput in) throws IOException {
        this.channel = in.readString();
        this.data = in.readBytes(in.available());
    }

    @Override
    public void write(NetOutput out) throws IOException {
        out.writeString(this.channel);
        out.writeBytes(this.data);
    }

    @Override
    public boolean isPriority() {
        return false;
    }
}


text:
Python API wrapper for paystack ( https://paystack.com/ )

# Installation

pip install python-paystack

# Configuration

To get started, import PaystackConfig from python_paystack.paystack_config and instantiate your public and secret keys.
Other settings which are instatiated by default include the paystack api url (PAYSTACK_URL), PASS_ON_TRANSACTION_COST which determines if the cost per transaction is passed to the end user, LOCAL_COST and INTL_COST are the paystack charges for local and international cards respectively.

```python
from python_paystack.paystack_config import PaystackConfig

PaystackConfig.SECRET_KEY  = PAYSTACK_SECRET_KEY
PaystackConfig.PUBLIC_KEY = PAYSTACK_PUBLIC_KEY

```

# Usage

Most of the library's functionality lies in the managers.py file which contains the TransactionsManager, CustomersManager, PlanManager and the TransfersManager.

The Manager classes handle every direct interaction with the Paystack API.

# Transactions

You can initialize transactions using all 3 methods supported by paystack i.e Standard, Inline and Inline Embed.
Both the inline and inline embed methods return a dictionary of values while the standard method returns a Transaction object which contains an authorization url.

**Starting and verifying a standard transaction**

```python
from python_paystack.objects.transactions import Transaction
from python_paystack.managers import TransactionsManager

transaction = Transaction(2000, 'email@test.com')
transaction_manager = TransactionsManager()
transaction = transaction_manager.initialize_transaction('STANDARD', transaction)
#Starts a standard transaction and returns a transaction object

transaction.authorization_url
#Gives the authorization_url for the transaction

#Transactions can easily be verified like so
transaction = transaction_manager.verify_transaction(transaction)

```

**Starting an inline transaction**
```python
transaction_manager.initialize_transaction('INLINE', transaction)

```

**Starting an inline embed transaction**
```python
transaction_manager.initialize_transaction('INLINE EMBED', transaction)
```

# Customers

**Registering a customer with paystack**

A customer can be registered using the CustomersManager.create_customer method which accepts a Customer object as an argument.
All the customer information to be sent to paystack is taken from the Customer object.
Misc. data can also be sent using the meta argument.
```python
from python_paystack.managers import CustomersManager
from python_paystack.objects.customers import Customer

customer = Customer('test@email.com')
customer_manager = CustomersManager()
customer_manager.create(customer)
```

**Getting existing customers**
```python
customer_manager = CustomersManager()
customer_manager.get_all()
#Returns a list containing every customer

customer_manager.get(id)
#Returns customer with the specified id
```

# Transfers

**Making a transfer with paystack**
```python
from python_paystack.objects.transfers import Transfer
from python_paystack.managers import TransfersManager

transfer = Transfer(2000, "RCP_123456")
transfer_manager = TransfersManager()
transfer = transfer_manager.create(transfer)

```

# TODO :

Tests


text:
[![npm](https://img.shields.io/npm/v/iab-vast-error.svg)](https://www.npmjs.com/package/iab-vast-error) [![Dependencies](https://img.shields.io/david/zentrick/iab-vast-error.svg)](https://david-dm.org/zentrick/iab-vast-error) [![Build Status](https://img.shields.io/circleci/project/github/zentrick/iab-vast-error/master.svg)](https://circleci.com/gh/zentrick/iab-vast-error) [![Coverage Status](https://img.shields.io/coveralls/zentrick/iab-vast-error/master.svg)](https://coveralls.io/r/zentrick/iab-vast-error) [![JavaScript Standard Style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)

Error class that describes VAST errors.

## Usage

```js
import VASTError from 'iab-vast-error'

try {
  throw new VASTError(100)
} catch (e) {
  if (e instanceof VASTError) {
    // e.code -> 100
    // e.message -> VAST error 100: XML parsing error.
  }
}
```

## Maintainer

[Tim De Pauw](https://github.com/timdp)

## License

MIT


text:
/******************************************************************************
 * This project provides two demo applications.  A simple blinky style project,
 * and a more comprehensive test and demo application.  The
 * configCREATE_SIMPLE_BLINKY_DEMO_ONLY setting (defined in FreeRTOSConfig.h) is
 * used to select between the two.  The simply blinky demo is implemented and
 * described in main_blinky.c.  The more comprehensive test and demo application
 * is implemented and described in main_full.c.
 *
 * This file implements the code that is not demo specific, including the
 * hardware setup and FreeRTOS hook functions.
 *
 */

/* Standard includes. */
#include <stdio.h>

/* Kernel includes. */
#include "FreeRTOS.h"
#include "task.h"

/* Standard demo includes - just needed for the LED (ParTest) initialisation
function. */
#include "partest.h"

/*
 * Set up the hardware ready to run this demo.
 */
static void prvSetupHardware( void );

/*
 * main_blinky() is used when configCREATE_SIMPLE_BLINKY_DEMO_ONLY is set to 1.
 * main_full() is used when configCREATE_SIMPLE_BLINKY_DEMO_ONLY is set to 0.
 */
extern void main_blinky( void );
extern void main_full( void );

/* Prototypes for the standard FreeRTOS callback/hook functions implemented
within this file. */
void vApplicationMallocFailedHook( void );
void vApplicationIdleHook( void );
void vApplicationStackOverflowHook( xTaskHandle pxTask, signed char *pcTaskName );
void vApplicationTickHook( void );

/*-----------------------------------------------------------*/
/* See the documentation page for this demo on the FreeRTOS.org web site for
full information - including hardware setup requirements. */

int main( void )
{
	/* Prepare the hardware to run this demo. */
	prvSetupHardware();

	/* The configCREATE_SIMPLE_BLINKY_DEMO_ONLY setting is described at the top
	of this file. */
	#if configCREATE_SIMPLE_BLINKY_DEMO_ONLY == 1
	{
		main_blinky();
	}
	#else
	{
		main_full();
	}
	#endif

	return 0;
}
/*-----------------------------------------------------------*/

static void prvSetupHardware( void )
{
	/* Perform any configuration necessary to use the ParTest LED output
	functions.  The name ParTest is now somewhat obsolete - originally it
	stood for PARallel port Test. */
	vParTestInitialise();
}
/*-----------------------------------------------------------*/

void vApplicationMallocFailedHook( void )
{
	/* vApplicationMallocFailedHook() will only be called if
	configUSE_MALLOC_FAILED_HOOK is set to 1 in FreeRTOSConfig.h.  It is a hook
	function that will get called if a call to pvPortMalloc() fails.
	pvPortMalloc() is called internally by the kernel whenever a task, queue,
	timer or semaphore is created.  It is also called by various parts of the
	demo application.  If heap_1.c or heap_2.c are used, then the size of the
	heap available to pvPortMalloc() is defined by configTOTAL_HEAP_SIZE in
	FreeRTOSConfig.h, and the xPortGetFreeHeapSize() API function can be used
	to query the size of free heap space that remains (although it does not
	provide information on how the remaining heap might be fragmented). */
	taskDISABLE_INTERRUPTS();
	for( ;; );
}
/*-----------------------------------------------------------*/

void vApplicationIdleHook( void )
{
	/* vApplicationIdleHook() will only be called if configUSE_IDLE_HOOK is set
	to 1 in FreeRTOSConfig.h.  It will be called on each iteration of the idle
	task.  It is essential that code added to this hook function never attempts
	to block in any way (for example, call xQueueReceive() with a block time
	specified, or call vTaskDelay()).  If the application makes use of the
	vTaskDelete() API function (as this demo application does) then it is also
	important that vApplicationIdleHook() is permitted to return to its calling
	function, because it is the responsibility of the idle task to clean up
	memory allocated by the kernel to any task that has since been deleted. */

	#if configCREATE_SIMPLE_BLINKY_DEMO_ONLY != 1
	{
		/* If the file system is only going to be accessed from one task then
		F_FS_THREAD_AWARE can be set to 0 and the set of example files is created
		before the RTOS scheduler is started.  If the file system is going to be
		access from more than one task then F_FS_THREAD_AWARE must be set to 1 and
		the	set of sample files are created from the idle task hook function. */
		#if F_FS_THREAD_AWARE == 1
		{
			static portBASE_TYPE xCreatedSampleFiles = pdFALSE;

			/* Initialise the drive and file system, then create a few example
			files.  The output from this function just goes to the stdout window,
			allowing the output to be viewed when the UDP command console is not
			connected. */
			if( xCreatedSampleFiles == pdFALSE )
			{
				vCreateAndVerifySampleFiles();
				xCreatedSampleFiles = pdTRUE;
			}
		}
		#endif
	}
	#endif
}
/*-----------------------------------------------------------*/

void vApplicationStackOverflowHook( xTaskHandle pxTask, signed char *pcTaskName )
{
	( void ) pcTaskName;
	( void ) pxTask;

	/* Run time stack overflow checking is performed if
	configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2.  This hook
	function is called if a stack overflow is detected. */
	taskDISABLE_INTERRUPTS();
	for( ;; );
}
/*-----------------------------------------------------------*/

void vApplicationTickHook( void )
{
	/* This function will be called by each tick interrupt if
	configUSE_TICK_HOOK is set to 1 in FreeRTOSConfig.h.  User code can be
	added here, but the tick hook is called from an interrupt context, so
	code must not attempt to block, and only the interrupt safe FreeRTOS API
	functions can be used (those that end in FromISR()). */
}
/*-----------------------------------------------------------*/


text:
require 'nokogiri'
require 'rest-client'
require 'easy_translate'
require 'sinatra'

#page =  RestClient.get('https://community.box.com/t5/How-to-Guides-for-Admins/Enterprise-Settings-Content-amp-Sharing/ta-p/174')
#parse_page = Nokogiri::HTML(RestClient.get('https://community.box.com/t5/How-to-Guides-for-Admins/Enterprise-Settings-Content-amp-Sharing/ta-p/174'))
#parse_page = Nokogiri::HTML(RestClient.get('https://community.box.com/t5/How-to-Guides-for-Managing/Excel-Online-Previewer/ta-p/30633'))

get '/' do
return erb :home
end

post '/showtrans' do
@kburl = params[:kburl]

parse_page = Nokogiri::HTML(RestClient.get(@kburl))
    parse_page.css('.lia-message-body').map do |a|
       # post_name = a.text.gsub /\t/, ''
        post_name = a
        #post_enter = post_name.gsub /\n/, ''
   # puts post_name
    File.open("out.txt",'w') {|f| f.write(post_name)}
end

to_parse = File.read("out.txt")
EasyTranslate.api_key = ''
@outcome = EasyTranslate.translate([to_parse], :to => :japanese)

#File.open("views/outcome1.erb",'w') {|f| f.write(outcome)}
#erb :outcome1

return erb :results

end


text:
require 'spec_helper'

describe Steam do
  it 'has a version number' do
    expect(Steam::VERSION).not_to be nil
  end
end


text:
# noicejs

Extremely thin, async dependency injection, now with
[a getting started guide](https://ssube.github.io/noicejs/getting-started).

Inspired by [Google's Guice library](https://github.com/google/guice) and written in
[Typescript](https://www.typescriptlang.org/).

## Features

- async dependency resolution
- constructor and property injection
- modular containers with inheritance
- named dependencies using strings or unique symbols
- typed errors
- typescript typedefs
- zero runtime dependencies, bundled or otherwise
- extensive test coverage

## Contents

- [noicejs](#noicejs)
  - [Features](#features)
  - [Contents](#contents)
  - [Status](#status)
  - [Releases](#releases)
  - [Usage](#usage)
  - [Build](#build)
  - [License](#license)

## Status

[![Pipeline status](https://img.shields.io/gitlab/pipeline/ssube/noicejs.svg?gitlab_url=https%3A%2F%2Fgit.apextoaster.com&logo=gitlab)](https://git.apextoaster.com/ssube/noicejs/commits/master)
[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=ssube_noicejs&metric=ncloc)](https://sonarcloud.io/dashboard?id=ssube_noicejs)
[![Test coverage](https://codecov.io/gh/ssube/noicejs/branch/master/graph/badge.svg)](https://codecov.io/gh/ssube/noicejs)
[![MIT license](https://img.shields.io/github/license/ssube/noicejs.svg)](https://github.com/ssube/noicejs/blob/master/LICENSE.md)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fssube%2Fnoicejs.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Fssube%2Fnoicejs?ref=badge_shield)

[![Open bug count](https://img.shields.io/github/issues-raw/ssube/noicejs/type-bug.svg)](https://github.com/ssube/noicejs/issues?q=is%3Aopen+is%3Aissue+label%3Atype%2Fbug)
[![Open issue count](https://img.shields.io/github/issues-raw/ssube/noicejs.svg)](https://github.com/ssube/noicejs/issues?q=is%3Aopen+is%3Aissue)
[![Closed issue count](https://img.shields.io/github/issues-closed-raw/ssube/noicejs.svg)](https://github.com/ssube/noicejs/issues?q=is%3Aissue+is%3Aclosed)

[![Renovate badge](https://badges.renovateapi.com/github/ssube/noicejs)](https://renovatebot.com)
[![Dependency status](https://img.shields.io/david/ssube/noicejs.svg)](https://david-dm.org/ssube/noicejs)
[![Dev dependency status](https://img.shields.io/david/dev/ssube/noicejs.svg)](https://david-dm.org/ssube/noicejs?type=dev)
[![Known vulnerabilities](https://snyk.io/test/github/ssube/noicejs/badge.svg)](https://snyk.io/test/github/ssube/noicejs)

[![Maintainability score](https://api.codeclimate.com/v1/badges/5d4326d6f68a2fa137cd/maintainability)](https://codeclimate.com/github/ssube/noicejs/maintainability)
[![Technical debt ratio](https://img.shields.io/codeclimate/tech-debt/ssube/noicejs.svg)](https://codeclimate.com/github/ssube/noicejs/trends/technical_debt)
[![Quality issues](https://img.shields.io/codeclimate/issues/ssube/noicejs.svg)](https://codeclimate.com/github/ssube/noicejs/issues)
[![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/ssube/noicejs.svg?logo=lgtm)](https://lgtm.com/projects/g/ssube/noicejs/context:javascript)
[![Total alerts](https://img.shields.io/lgtm/alerts/g/ssube/noicejs.svg)](https://lgtm.com/projects/g/ssube/noicejs/alerts/)

## Releases

- 3.x versions are compatible with Node 12+
- 4.x versions are compatible with Node 16+

[![github release link](https://img.shields.io/badge/github-release-blue?logo=github)](https://github.com/ssube/noicejs/releases)
[![github release version](https://img.shields.io/github/tag/ssube/noicejs.svg)](https://github.com/ssube/noicejs/releases)
[![github commits since release](https://img.shields.io/github/commits-since/ssube/noicejs/v3.0.1.svg)](https://github.com/ssube/noicejs/compare/v3.0.1...master)

[![npm package link](https://img.shields.io/badge/npm-package-blue?logo=npm)](https://www.npmjs.com/package/noicejs)
[![npm release version](https://img.shields.io/npm/v/noicejs.svg)](https://www.npmjs.com/package/noicejs)
[![Typescript definitions](https://img.shields.io/npm/types/noicejs.svg)](https://www.npmjs.com/package/noicejs)

## Usage

Consider a `Server` class that needs to fetch data from the `Cache` and `Filesystem`, but doesn't know (or need to
know) how those are implemented. The following example is [also part of the unit tests](./test/examples/TestReadme.ts).

```typescript
import { LocalModule } from './local';
import { NetworkModule } from './network';

class Cache {
  public get(path: string, ttl: number, fallback: () => Promise<string>): Promise<string> {
    /* ... */
  }
}

class Filesystem {
  public get(path: string): Promise<string> {
    /* ... */
  }
}

/**
 * Constructors, strings, and symbols are supported. Symbols are
 * preferred, as the most unique, but names can be convenient.
 */
@Inject(Cache.name.toLowerCase(), Filesystem.name.toLowerCase())
class Server {
  protected readonly cache: Cache;
  protected readonly filesystem: Filesystem;
  protected readonly ttl: number;

  constructor(options) {
    this.cache = options.cache;
    this.filesystem = options.filesystem;
    this.ttl = defaultTo(options.ttl, 0);
  }

  get(path: string) {
    return options.cache.get(path, this.ttl, () => options.filesystem.get(path));
  }
}

const TEST_TTL = 60;

function module() {
  if (process.env['DEBUG'] === 'TRUE') {
    return new LocalModule();
  } else {
    return new NetworkModule();
  }
}

async function main() {
  const container = Container.from(module());
  await container.configure();

  const server = await container.create(Server, {
    /* cache and filesystem are found and injected by container */
    ttl: TEST_TTL,
  });

  /* server.cache.get and server.filesystem.get will be called in order */
  const result = await server.get('some/file');
}
```

noicejs will collect dependencies from the decorated constructor and any superclasses, find a provider for each
injected dependency, and asynchronously resolve them before calling the constructor. Any extra parameters are passed
on to the original constructor, along with the container and resolved dependencies.

## Build

To build a bundle and run tests:

```shell
> make

yarn
yarn install v1.17.3
[1/4] Resolving packages...
success Already up-to-date.
Done in 0.20s.
/home/ssube/code/ssube/noicejs//node_modules/.bin/rollup --config /home/ssube/code/ssube/noicejs//config/rollup.js

src/index.ts, test/harness.ts, test/**/Test*.ts → out/...
...
created out/ in 3.3s
/home/ssube/code/ssube/noicejs//node_modules/.bin/api-extractor run --config /home/ssube/code/ssube/noicejs//config/api-extractor.json --local -v

api-extractor 7.3.8  - https://api-extractor.com/
...

API Extractor completed successfully
Success!
```

## License

[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fssube%2Fnoicejs.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fssube%2Fnoicejs?ref=badge_large)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.apache.hadoop.ha (Apache Hadoop Main 2.6.0-cdh5.4.2 API)</title>
<meta name="date" content="2015-05-19">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.apache.hadoop.ha

Interfaces

FenceMethod

HAServiceProtocol

Classes

HAServiceProtocolHelper

HAServiceTarget

Exceptions

BadFencingConfigurationException

FailoverFailedException

HealthCheckFailedException

ServiceFailedException


text:
Setup

## Setup for local development

It's recommanded to create a virtual Python environment, but not required. Therefore create and activate it.
```bash
$ virtualenv scf_project
$ cd scf_project/
$ source bin/activate
```

### Setup server

Get SCF and install the Python dependencies
```bash
$ git clone https://github.com/citationfinder/scholarly_citation_finder.git
$ cd scholarly_citation_finder
$ pip install -r requirements.txt
```

Migrate the database tables and collect the static files
```bash
$ ./manage.py migrate
$ ./manage.py collectstatic
```

Create a root user
```bash
$ ./manage.py createsuperuser
```

Start Celery
```bash
$ celery -A scholarly_citation_finder worker -l info
```

Finally run the build-in Django server
```bash
$ ./manage.py runserver
```

Open [http://localhost:8000](http://localhost:8000)

### Setup client

The client is located in the `public/client` directory. Gulp in combination with Webpack is used to build the client. During development run Gulp to automatically build the project and reload the browser, when you change files

```bash
$ cd public/client
$ gulp
```

Open [http://localhost:4000](http://localhost:4000)

### Documenation

MkDocs is used for this documentation. Run MkDocs during writing to check the results

```bash
$ mkdocs serve
```

Open [http://localhost:8000](http://localhost:8000)

## Setup a virtual machine

see [Deploy Vagrant](deployment.md)


text:
--TEST--
Check for exif_read_data, unusual IFD start
--SKIPIF--
<?php if (!extension_loaded('exif')) print 'skip exif extension not available';?>
--INI--
output_handler=
zlib.output_compression=0
--FILE--
<?php
/* Do not change this test it is a README.TESTING example.
 * test5.jpg is a 1*1 image that contains an Exif section with ifd = 00000009h
 */
$image  = exif_read_data(dirname(__FILE__).'/test5.jpg','',true,false);
var_dump($image['IFD0']);
?>
--EXPECT--
array(2) {
  ["ImageDescription"]=>
  string(11) "Ifd00000009"
  ["DateTime"]=>
  string(19) "2002:10:18 20:06:00"
}


text:
<?php

namespace Lug\Component\Locale\Exception;

/**
 * @author GeLo <geloen.eric@gmail.com>
 */
interface ExceptionInterface
{
}


text:
namespace EffectiveCPP {
    const int usedDeclDistance = 2;
    StatementMatcher varUseMatcherEC = declRefExpr().bind("def");
    std::map<const std::string, int>varDefineTest; //<varName, diffLine>
}

void EffectiveCPP::VarDefinePrinter::run(const MatchFinder::MatchResult &Result)
{
	//get the ASTContext
	clang::ASTContext *Context = Result.Context;
	const clang::DeclRefExpr *def = Result.Nodes.getNodeAs<clang::DeclRefExpr>("def");

	if(!def || ASTUtility::IsStmtInSTDFile(def, Context)) return;

    //only var decl is needed, no field decl or other decl
    if (!def -> getDecl() || !clang::VarDecl::classof(def -> getDecl())) return;

    const clang::VarDecl *vd = static_cast<const clang::VarDecl*>(def -> getDecl());
    const std::string varName = ASTUtility::Print(vd, Context);

    //already test
    if (varDefineTest.find(varName) != varDefineTest.end()) return;

    auto endLocDecl = Context -> getFullLoc(vd -> getLocEnd());
    auto startLocStmt = Context -> getFullLoc(def -> getLocStart());
    int declLineNo = endLocDecl.isValid() ? endLocDecl.getSpellingLineNumber() : -1;
    int usedLineNo = startLocStmt.isValid() ? startLocStmt.getSpellingLineNumber() : -1;
    //something is wrong
    if (declLineNo == -1 || usedLineNo == -1) return;

    varDefineTest[varName] = usedLineNo - declLineNo;
    if (varDefineTest[varName] > usedDeclDistance)
        ASTUtility::Print(vd, Context, "Rule056");
}


text:
require 'miq_storage_defs'

class CimAssoc
  def initialize(&block)
    @from_class   = nil
    @result_class = nil
    @assoc_class  = nil
    @role     = nil
    @result_role  = nil
    block.arity < 1 ? instance_eval(&block) : block.call(self) unless block.nil?
  end

  def reverse!
    @from_class, @result_class = @result_class, @from_class
    @role, @result_role = @result_role, @role
    self
  end

  def reverse
    dup.reverse!
  end

  def dump(offset = "", lvl = 0)
    ip("<#{self.class.name}>",          lvl, offset)
    ip("    assoc_class:  #{@assoc_class}",   lvl, offset)
    ip("    from_class:   #{@from_class}",    lvl, offset)
    ip("    result_class: #{@result_class}",  lvl, offset)
    ip("    role:         #{@role}",      lvl, offset)
    ip("    result_role:  #{@result_role}",   lvl, offset)
    ip("<END: #{self.class.name}>",       lvl, offset)
  end

  def ip(s, i, o)
    print o + "    " + "        " * i
    puts s
  end
  private :ip

  def [](sym)
    send(sym.to_s.underscore.to_sym)
  end

  def []=(sym, val)
    send((sym.to_s.underscore + "=").to_sym, val)
  end

  def method_missing(sym, *args)
    key = sym.to_s.insert(0, '@')
    if key[-1, 1] == '='
      key = key[0...-1]
      return instance_variable_set(key, args[0])
    elsif args.length == 1
      return instance_variable_set(key, args[0])
    else
      return instance_variable_get(key)
    end
  end
end # class CimAssoc

class CimProfNode
  attr_reader :flags, :association, :next
  attr_writer :tag

  TAG_DELIMITER = "_to_"

  def initialize(&block)
    @tag      = nil
    @flags      = {}
    @association  = []  # Array of CimAssoc
    @next     = CimProfNodeGroup.new  # Array of CimProfNode (children)
    block.arity < 1 ? instance_eval(&block) : block.call(self) unless block.nil?
  end

  def tag(val = nil)
    return @tag if val.nil?
    @tag = val
  end

  def add_association(assoc)
    if assoc.kind_of?(Symbol)
      a = CimAssociations[assoc]
      raise "#{self.class.name}.add_association: association #{assoc} not found" if a.nil?
      assoc = a
    end
    @association << assoc
  end

  #
  # Add the CimProfNode to the children if the current node.
  #
  def add_next!(node = nil, &block)
    node = get_node(node)
    block.arity < 1 ? node.instance_eval(&block) : block.call(node) unless block.nil?
    @next.add(node)
    self
  end

  def add_next(node = nil, &block)
    new_me = deep_dup
    new_me.add_next!(node, &block)
    new_me
  end

  def +(node = nil)
    add_next(node)
  end

  #
  # Append the CimProfNode to the end of the next chain of the current branch.
  #
  def append_next!(node = nil, &block)
    if @next.empty?
      node = get_node(node)
      block.arity < 1 ? node.instance_eval(&block) : block.call(node) unless block.nil?
      @next.add(node)
      return self
    end
    raise "#{self.class.name}.append_next: cannot append to branch with fork" if @next.length > 1
    @next.first.append_next!(node, &block)
    self
  end

  def append_next(node = nil, &block)
    new_me = deep_dup
    new_me.append_next!(node, &block)
    new_me
  end

  def <<(node = nil)
    append_next(node)
  end

  def add_flags(flags)
    @flags.merge!(flags)
  end

  def remove_flags(*args)
    args.each { |f| @flags.delete(f) }
  end

  def clear_flags
    @flags.clear
  end

  def reverse!
    raise "#{self.class.name}.reverse!: can't reverse multi-association profile, tag = #{@tag}" unless @association.length == 1
    @association[0] = CimAssociations.add_reverse(@association[0])
    @tag = reverse_tag(@tag)
    self
  end

  def reverse
    dup.reverse!
  end

  def update(&block)
    block.arity < 1 ? instance_eval(&block) : block.call(self)
  end

  def dup
    d = self.class.new
    d.tag = @tag
    d.add_flags(@flags)
    @association.each { |a| d.add_association(a) }
    d
  end

  def deep_dup
    d = dup
    d.next.add(@next.deep_dup)
    d
  end

  def node_with_tag(tag)
    return self if @tag == tag
    @next.node_with_tag(tag)
  end

  #
  # attr_readers accessed as hash
  #
  def [](tag)
    send(tag)
  end

  def check(offset = "", lvl = 0, rank = 0)
    puts offset + "#{self.class.name}.check: level = #{lvl}, rank = #{rank} START"
    association.each { |fa| self.next.check_next(offset, fa, lvl, rank) }
    puts offset + "#{self.class.name}.check: level = #{lvl}, rank = #{rank} END"
    puts

    self.next.each_with_index { |n, i| n.check(offset, lvl + 1, i) }
    nil
  end

  def dump(offset = "", lvl = 0, rank = 0)
    ip("<#{self.class.name}> (#{object_id}) [#{lvl}, #{rank}]", lvl, offset)
    ip("    tag:   #{@tag}", lvl, offset)
    ip("    flags: #{@flags.inspect}", lvl, offset)
    ip("    associations:", lvl, offset)
    @association.each { |a| a.dump(offset, lvl) }
    ip("    next:", lvl, offset)
    @next.dump(offset, lvl)
    ip("<END: #{self.class.name}> (#{object_id}) [#{lvl}, #{rank}]", lvl, offset)
  end

  def method_missing(sym, *args)
    super if (rv = CimProfiles[sym]).nil?
    rv
  end

  def reverse_tag(tag)
    tag = tag.to_s
    sa = tag.split(TAG_DELIMITER)
    return (tag + "_reversed").to_sym unless sa.length == 2
    (sa[1] + TAG_DELIMITER + sa[0]).to_sym
  end
  private :reverse_tag

  def get_node(node)
    if node.nil?
      node = self.class.new
    elsif node.kind_of?(Symbol)
      n = CimProfiles[node]
      raise "#{self.class.name}: profile #{node} not found" if n.nil?
      node = n.deep_dup
    else
      node = node.deep_dup
    end
    node
  end
  private :get_node

  def ip(s, i, o)
    print o + "    " + "        " * (i - 1) if i >= 1
    puts s
  end
  private :ip
end # class CimProfNode

class CimProfNodeGroup < Array
  include MiqStorageDefs

  def initialize(&block)
    super()
    @input_class = nil

    unless block.nil?
      block.arity < 1 ? instance_eval(&block) : block.call(self)
    end
  end

  def input_class(cim_class = nil)
    return @input_class if cim_class.nil?
    @input_class = cim_class
  end

  def node(&block)
    node = CimProfNode.new
    unless block.nil?
      block.arity < 1 ? node.instance_eval(&block) : block.call(node)
    end
    push(node)
  end

  def add(node)
    if node.kind_of?(Symbol)
      n = CimProfiles[node]
      raise "#{self.class.name}.add: profile #{node} not found" if n.nil?
      node = n
    end
    node = node.deep_dup

    if node.kind_of?(CimProfNode)
      push(node)
    elsif node.kind_of?(CimProfNodeGroup)
      concat(node)
    end
  end

  #
  # This replaces Array::<< so care must be taken to use "push" instead of "<<"
  # when the Array behavior is desired.
  #
  def <<(node)
    raise "#{self.class.name}.append_next: cannot append to branch with fork" if length > 1
    if self.empty?
      push(node)
    else
      first.append_next(node)
    end
  end

  def prepend(node)
    node.add_next!(self)
    clear
    self[0] = node
  end

  def node_with_tag(tag)
    each do |n|
      unless (rv = n.node_with_tag(tag)).nil?
        return rv
      end
    end
    nil
  end

  def reverse(head = nil)
    raise "#{self.class.name}.reverse: can't reverse branched profile" unless length <= 1

    head = self.class.new if head.nil?
    return head if self.empty?

    node = first
    rnode = node.reverse
    head.prepend(rnode)
    head.input_class(rnode.association.first.from_class)
    node.next.reverse(head)
  end

  def deep_dup
    ng = self.class.new
    each { |n| ng.add(n.deep_dup) }
    ng
  end

  def check(offset = "", lvl = 0, rank = 0)
    puts offset + "#{self.class.name}.check: level = #{lvl}, rank = #{rank} START"
    check_next(offset, nil, lvl, rank)
    puts offset + "#{self.class.name}.check: level = #{lvl}, rank = #{rank} END"
    puts
    each_with_index { |n, i| n.check(offset, lvl + 1, i) }
  end

  def cim_class_hier(cim_class)
    return [cim_class] if (ch = CIM_CLASS_HIER[cim_class]).nil?
    ch
  end
  private :cim_class_hier

  def check_next(offset = "", from_assoc = nil, _lvl = 0, _rank = 0)
    if from_assoc
      input_class = from_assoc.result_class
      assoc_class = from_assoc.assoc_class
    else
      raise "#{self.class.name}.check_next: input_class is not set" if (input_class = @input_class).nil?
      assoc_class = 'TOP'
    end

    each do |n|
      n.association.each do |ta|
        next_class = ta.from_class
        unless cim_class_hier(input_class).include?(next_class) ||
               cim_class_hier(next_class).include?(input_class)
          puts offset + "  tag: #{n.tag}" unless n.tag.nil?
          puts offset + "    #{assoc_class}: input_class #{input_class}, doesn't match #{next_class}"
        end
      end
    end
  end

  def dump(offset = "", lvl = 0)
    puts offset + "input_class: #{@input_class}" unless @input_class.nil?
    each_with_index { |n, i| n.dump(offset, lvl + 1, i) }
  end

  def method_missing(sym, *args)
    super if (rv = CimProfiles[sym]).nil?
    rv
  end
end # class CimProfNodeGroup

class CimAssociations < Hash
  private_class_method :new, :[]

  DELIMITER = '_TO_'

  def self.update(name_sfx = "", &block)
    @instance = new unless @instance

    #
    # Update should be serialized through the load process,
    # so using a class variable should be ok.
    #
    @@name_sfx = name_sfx
    unless block.nil?
      block.arity < 1 ? @instance.instance_eval(&block) : block.call(@instance)
      @instance.default = nil
    end
    @@name_sfx = ""
  end

  def initialize
    super()
  end

  def add(assoc = nil, &block)
    raise "#{self.class.name}.add: association or block required" if assoc.nil? && block.nil?

    if assoc.nil?
      assoc = CimAssoc.new(&block)
    else
      unless block.nil?
        asscoc = assoc.dup
        block.arity < 1 ? assoc.instance_eval(&block) : block.call(assoc)
        self.default = nil
      end
    end

    fa_tag = assoc_tag(assoc)
    raise "#{self.class.name}.add: association already exist #{fa_tag}" if self.key?(fa_tag)
    self[fa_tag] = assoc
    add_reverse(assoc)

    nil
  end

  def add_reverse(assoc)
    rassoc = assoc.reverse
    ra_tag = assoc_tag(rassoc)
    self[ra_tag] = rassoc unless self.key?(ra_tag)
    rassoc
  end

  def self.add_reverse(assoc)
    @instance.add_reverse(assoc)
  end

  def remove(sym)
    delete(sym)
  end

  def method_missing(sym, *args, &block)
    if args.empty? && block.nil?
      raise "#{self.class.name}: association named #{sym} not found" unless self.key?(sym)
      return self[sym]
    end

    raise "#{self.class.name}: association named #{sym} already exists" if self.key?(sym)

    if args.empty?
      assoc = CimAssoc.new
    else
      raise "#{self.class.name}.#{sym}: wrong number of arguments #{args.length} for 1" unless args.length == 1
      if (assoc = args.first).kind_of?(Symbol)
        a = self[assoc]
        raise "#{self.class.name}.#{sym}: association #{assoc} not found" if a.nil?
        assoc = a
      end
    end
    raise "#{self.class.name}.#{sym}: arg is not a CimAssoc (#{assoc.class.name})" unless assoc.kind_of?(CimAssoc)
    block.arity < 1 ? assoc.instance_eval(&block) : block.call(assoc) unless block.nil?
    self[sym] = assoc
  end

  def self.list
    @instance.keys.sort { |a, b| a.to_s <=> b.to_s }.each { |k| puts k }
  end

  def self.method_missing(sym, *args, &block)
    @instance.send(sym, *args, &block)
  end

  def assoc_tag(assoc)
    (assoc.from_class.to_s + DELIMITER + assoc.result_class.to_s + @@name_sfx).to_sym
  end
  private :assoc_tag
end # class CimAssociations

class CimProfiles < Hash
  private_class_method :new, :[]

  def self.update(&block)
    @instance = new unless @instance

    unless block.nil?
      block.arity < 1 ? @instance.instance_eval(&block) : block.call(@instance)
      @instance.default = nil
    end
  end

  def initialize
    super()
  end

  #
  # Given its name, look up the profile in the hash.
  # Like [], but it dups the profile and passes it to the block, if given.
  #
  def lookup(sym, &block)
    raise "#{self.class.name}.lookup: profile #{sym} not found." if (node = self[sym]).nil?
    node = node.deep_dup
    block.arity < 1 ? node.instance_eval(&block) : block.call(node) unless block.nil?
    node
  end

  def method_missing(sym, *args, &block)
    if args.empty? && block.nil?
      raise "#{self.class.name}: profile named #{sym} not found" unless self.key?(sym)
      return self[sym]
    end

    raise "#{self.class.name}.#{sym}: profile already exists" if self.key?(sym)

    if args.empty?
      node = CimProfNodeGroup.new
    else
      raise "#{self.class.name}.#{sym}: wrong number of arguments #{args.length} for 1" unless args.length == 1
      if (node = args.first).kind_of?(Symbol)
        n = self[node]
        raise "#{self.class.name}.#{sym}: profile #{node} not found" if n.nil?
        node = n
      elsif node.kind_of?(CimAssoc)
        node = CimProfNode.new do
          tag sym
          add_association node
        end
      end
    end
    if node.kind_of?(CimProfNode)
      node = CimProfNodeGroup.new do
        input_class node.association.first.from_class
        add node
      end
    end

    raise "#{self.class.name}.#{sym}: arg is not a CimProfNodeGroup (#{node.class.name})" unless node.kind_of?(CimProfNodeGroup)
    block.arity < 1 ? node.instance_eval(&block) : block.call(node) unless block.nil?
    self[sym] = node
  end

  def self.method_missing(sym, *args, &block)
    @instance.send(sym, *args, &block)
  end

  # Constants are looked up in global scope in instance_eval,
  # so this doesn't work.
  def self.const_missing(sym)
    @instance.send(sym, [], nil)
  end

  def self.list
    @instance.keys.sort { |a, b| a.to_s <=> b.to_s }.each { |k| puts k }
  end

  def self.check
    puts "#{name}.check: Checking profiles..."
    keys = @instance.keys.sort { |a, b| a.to_s <=> b.to_s }
    keys.each do |pn|
      puts "    #{pn}:"
      @instance[pn].check('        ')
    end
    puts "#{name}.check: Done."
  end
end # class CimProfiles


text:
/*
 *= require font-awesome
 *= require main.scss
 */


text:
<properties>

	<!-- 描述:模板管理模块 author:谭湘 CopyRight:三一 版本:1.0 Date: 2014-06-09 -->

	<property name="/workflow/templeManage/*.page"
		path:templeManager="/workflow/templeManage/templeManager.jsp"
		path:templeList="/workflow/templeManage/templeList.jsp"
		path:editTemple="/workflow/templeManage/editTemple.jsp"
		f:templeService="attr:workflow.temple.templeService"
		class="com.sany.workflow.action.TempleManageAction">
	</property>

	<property name="workflow.temple.templeService"
		f:executor="attr:workflow.temple.configsqlexecutor"
		f:activitiService="attr:activitiService"
		f:messageService="attr:workflow.MessageService"
		f:token_value="f19f3394-8242-4842-beba-33c7731c34ed"
		f:app_name="sim"
		class="com.sany.workflow.service.impl.TempleServiceImpl" />

	<property name="workflow.temple.configsqlexecutor"
		class="com.frameworkset.common.poolman.ConfigSQLExecutor">
		<construction>
			<property value="com/sany/workflow/messTemplate.xml" />
		</construction>
	</property>

	<!-- 单元测试需要的配置
	 <property name="activitiService"
		f:executor="attr:activiti.configsqlexecutor"
		class="com.sany.workflow.service.impl.ActivitiServiceImpl">
		<construction>
			<property value="activiti.cfg.xml"/>
		</construction>
	</property>

	<property name="activiti.configsqlexecutor"
		class="com.frameworkset.common.poolman.ConfigSQLExecutor" >
		<construction>
			<property value="com/sany/workflow/activiti.xml"/>
		</construction>

	</property>
 -->
</properties>


text:
id: admin-api-non-partitioned-topics
title: Managing non-partitioned topics
sidebar_label: "Non-partitioned topics"
---

For details of the content, refer to [manage topics](admin-api-topics.md).


text:
Node.js module based on Neil Fraiser's excellent [Diff Match Patch](https://code.google.com/p/google-diff-match-patch/).

[![npm version](https://badge.fury.io/js/dmp.svg)](http://badge.fury.io/js/dmp)

[![Build Status](https://travis-ci.org/Floobits/dmp.svg)](https://travis-ci.org/Floobits/dmp)

[![Floobits Status](https://floobits.com/Floobits/dmp.svg)](https://floobits.com/Floobits/dmp/redirect)

## Install

Add `dmp` to your `package.json` or `npm install dmp`.

This module requires Node.js v4.0 or later.

## Use

```js
const DMP = require("dmp");
const dmp = new DMP();

let patches = dmp.patch_make("", "abcd");

console.log(dmp.patch_toText(patches));
// @@ -0,0 +1,4 @@
// +abcd

let patch_text = "@@ -0,0 +1,4 @@\n+abcd\n";
patches = dmp.patch_fromText(patch_text);

let result = dmp.patch_apply(patches, "");
console.log(result);
// [ 'abcd', [ true ] ]
```

## Configure

After creating a DMP object, you can tweak a few attributes. Don't mess with these unless you know what you're doing!

```js
dmp.Patch_DeleteThreshold = 0.375;
dmp.Match_Threshold = 0.375;
dmp.Match_Distance = 100;
```

Default values are:

```js
Patch_DeleteThreshold = 0.5;
Match_Threshold = 0.5;
Match_Distance = 1000;
```


text:
获取值/对象的标签

## 关于 `Symbol.toStringTag`

[参考这里](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag)

`Symbol.toStringTag` 是一个内置 `symbol`, 它通常作为对象的属性键使用, 对应的属性值应该为字符串类型, 这个字符串用来表示该对象的自定义类型标签, 通常只有内置的 `Object.prototype.toString()` 方法会去读取这个标签并把它包含在自己的返回值里。

对一些对象类型(ES6新增的),toString() 方法能识别它们是因为引擎为它们设置好了 toStringTag 标签:

```js
console.log(Object.prototype.toString.call(new Map())); // "[object Map]"
console.log(Object.prototype.toString.call(function* () {})); // "[object GeneratorFunction]"
console.log(Object.prototype.toString.call(Promise.resolve())); // "[object Promise]"
```

自己创建的类不会有这份特殊待遇, `toString()` 找不到 `toStringTag` 属性时只好返回默认的 `Object` 标签:

```js
class ValidatorClass {}
console.log(Object.prototype.toString.call(new ValidatorClass())); // "[object Object]"
```

当然也可以加上 `toStringTag` 属性, 这样你的类也会有自定义的类型标签了:

```js
class ValidatorClass {
  get[Symbol.toStringTag]() {
    return "Validator";
  }
}
console.log(Object.prototype.toString.call(new ValidatorClass())); // "[object Validator]"
```

## 实现

其实就是调用

```js
Object.prototype.toString.call(value);
```


text:
<?php

use ut8ia\contentmodule\helpers\ContentHelper;
use ut8ia\slidermodule\widgets\CarouselWidget;
use yii\helpers\Url;

$images = ContentHelper::fetchImages($model->text);
if ($images['count']>1) {
    $carousel = CarouselWidget::widget([
        'template' => 'single',
        'mode' => 'images',
        'slides' => $images['images']
    ]);
    echo '
' . $carousel . '
';
    $this->registerMetaTag(['property' => 'og:image', 'content' => url::toRoute($images['main']['src'], true)]);
}
elseif($images['count']==1){
    echo '

';
}

?>

    <?= ContentHelper::cleanImages($model->text); ?>


text:
#ifndef _dns_agent_xmpp_channel_h_
#define _dns_agent_xmpp_channel_h_

#include <map>
#include <set>
#include <string>
#include <boost/function.hpp>
#include <boost/bind.hpp>

#include "xmpp/xmpp_channel.h"
#include "bind/bind_util.h"

class XmppServer;
class DnsAgentXmppChannelManager;
class AgentData;
class AgentDnsData;
class TaskTrigger;

class DnsAgentXmppChannel {
public:
    typedef std::set<DnsUpdateData *, DnsUpdateData::Compare> DataSet;

    DnsAgentXmppChannel(XmppChannel *channel,
                        DnsAgentXmppChannelManager *mgr);
    virtual ~DnsAgentXmppChannel();
    void Close();
    void ReceiveReq(const XmppStanza::XmppMessage *msg);
    void GetAgentDnsData(AgentDnsData &data);
    void UpdateDnsRecords(BindUtil::Operation op);

private:
    std::string GetDnsRecordName(std::string &vdns_name, const DnsItem &item);
    void HandleAgentUpdate(std::auto_ptr<DnsUpdateData> rcv_data);

    DataSet update_data_;
    XmppChannel *channel_;
    DnsAgentXmppChannelManager *mgr_;
};

class DnsAgentXmppChannelManager {
public:
    typedef std::map<const XmppChannel *, DnsAgentXmppChannel *> ChannelMap;

    DnsAgentXmppChannelManager(XmppServer *server);
    virtual ~DnsAgentXmppChannelManager();
    void RemoveChannel(XmppChannel *ch);
    DnsAgentXmppChannel *FindChannel(const XmppChannel *ch);
    void HandleXmppChannelEvent(XmppChannel *channel, xmps::PeerState state);

    void GetAgentData(std::vector<AgentData> &list);
    void GetAgentDnsData(std::vector<AgentDnsData> &dt);

private:
    XmppServer *server_;
    ChannelMap channel_map_;
};

#endif // _dns_agent_xmpp_channel_h_


text:
<?php

namespace Magento\Setup\Console\Command;

use Magento\Setup\Mvc\Bootstrap\InitParamListener;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputOption;

/**
 * An abstract class for all Magento Setup command.
 * It adds InitParamListener's magento-init-params option to all setup command.
 */
abstract class AbstractSetupCommand extends Command
{
    /**
     * Initialize basic Magento Setup command
     *
     * @return void
     */
    protected function configure()
    {
        $this->addOption(
            InitParamListener::BOOTSTRAP_PARAM,
            null,
            InputOption::VALUE_REQUIRED,
            'Add to any command to customize Magento initialization parameters' . PHP_EOL .
            'For example: "MAGE_MODE=developer&MAGE_DIRS[base][path]' .
            '=/var/www/example.com&MAGE_DIRS[cache][path]=/var/tmp/cache"'
        );
    }
}


text:
fast-bind
=========

Alternatives to AngularJS's built-in bindings that avoid taxing the digest cycle


text:
<head>

  <!-- Basic Page Needs
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>{{ site.title }}{% if page.title %} - {{ page.title }}{% endif %}</title>
  <meta name="description" content="{% if page.excerpt %}{{ page.excerpt | strip_html | strip_newlines | truncate: 160 }}{% else %}{{ site.description }}{% endif %}">

  <!-- Mobile Specific Metas
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- FONT
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->

  <!-- CSS
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
  <link type="text/css" rel="stylesheet" href="{{ site.baseurl }}/css/modal-video.css"/>
  <link type="text/css" rel="stylesheet" href="{{ site.baseurl }}/css/normalize.css"/>
  <link type="text/css" rel="stylesheet" href="{{ site.baseurl }}/css/custom-202004.css"/>

  <!-- JS
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script type='text/javascript' src="https://cdnjs.cloudflare.com/ajax/libs/jquery-touch-events/1.0.5/jquery.mobile-events.js"></script>
  <script type='text/javascript' src="{{ site.baseurl }}/js/jquery-modal-video.js"></script>

  <!-- Favicon
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link rel="icon" type="image/png" href="{{ site.baseurl }}/images/favicon.png">

  <!-- Extra Stuff
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
  <!--<link rel="alternate" type="application/rss+xml" title="{{ site.title }}" href="{{ "/feed.xml" | prepend: site.baseurl | prepend: site.url }}" />-->

</head>


text:
package com.hubspot.singularity.scheduler;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.hubspot.mesos.JavaUtils;
import com.hubspot.singularity.ExtendedTaskState;
import com.hubspot.singularity.SingularityDeploy;
import com.hubspot.singularity.SingularityTaskHealthcheckResult;
import com.hubspot.singularity.SingularityTaskHistoryUpdate;
import com.hubspot.singularity.SingularityTaskHistoryUpdate.SimplifiedTaskState;
import com.hubspot.singularity.SingularityTaskId;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.data.TaskManager;

@Singleton
public class SingularityDeployHealthHelper {

  private static final Logger LOG = LoggerFactory.getLogger(SingularityDeployHealthHelper.class);

  private final TaskManager taskManager;
  private final SingularityConfiguration configuration;

  @Inject
  public SingularityDeployHealthHelper(TaskManager taskManager, SingularityConfiguration configuration) {
    this.taskManager = taskManager;
    this.configuration = configuration;
  }

  public enum DeployHealth {
    WAITING, UNHEALTHY, HEALTHY;
  }

  public DeployHealth getDeployHealth(final Optional<SingularityDeploy> deploy, final Collection<SingularityTaskId> activeTasks, final boolean isDeployPending) {
    if (!deploy.isPresent() || !deploy.get().getHealthcheckUri().isPresent() || (isDeployPending && deploy.get().getSkipHealthchecksOnDeploy().or(false))) {
      return getNoHealthcheckDeployHealth(deploy, activeTasks);
    } else {
      return getHealthcheckDeployState(deploy.get(), activeTasks, isDeployPending);
    }
  }

  private DeployHealth getNoHealthcheckDeployHealth(final Optional<SingularityDeploy> deploy, final Collection<SingularityTaskId> matchingActiveTasks) {
    final Map<SingularityTaskId, List<SingularityTaskHistoryUpdate>> taskUpdates = taskManager.getTaskHistoryUpdates(matchingActiveTasks);

    for (SingularityTaskId taskId : matchingActiveTasks) {
      Collection<SingularityTaskHistoryUpdate> updates = taskUpdates.get(taskId);

      SimplifiedTaskState currentState = SingularityTaskHistoryUpdate.getCurrentState(updates);

      switch (currentState) {
        case UNKNOWN:
        case WAITING:
          return DeployHealth.WAITING;
        case DONE:
          LOG.warn("Unexpectedly found an active task ({}) in done state: {}}", taskId, updates);
          return DeployHealth.UNHEALTHY;
        case RUNNING:
          long runningThreshold = configuration.getConsiderTaskHealthyAfterRunningForSeconds();
          if (deploy.isPresent()) {
            runningThreshold = deploy.get().getConsiderHealthyAfterRunningForSeconds().or(runningThreshold);
          }

          if (runningThreshold < 1) {
            continue;
          }

          Optional<SingularityTaskHistoryUpdate> runningUpdate = SingularityTaskHistoryUpdate.getUpdate(updates, ExtendedTaskState.TASK_RUNNING);
          long taskDuration = System.currentTimeMillis() - runningUpdate.get().getTimestamp();

          if (taskDuration < TimeUnit.SECONDS.toMillis(runningThreshold)) {
            LOG.debug("Task {} has been running for {}, has not yet reached running threshold of {}", taskId, JavaUtils.durationFromMillis(taskDuration), JavaUtils.durationFromMillis(runningThreshold));
            return DeployHealth.WAITING;
          }
      }
    }

    return DeployHealth.HEALTHY;
  }

  private DeployHealth getHealthcheckDeployState(final SingularityDeploy deploy, final Collection<SingularityTaskId> matchingActiveTasks, final boolean isDeployPending) {
    Map<SingularityTaskId, SingularityTaskHealthcheckResult> healthcheckResults = taskManager.getLastHealthcheck(matchingActiveTasks);

    for (SingularityTaskId taskId : matchingActiveTasks) {
      SingularityTaskHealthcheckResult healthcheckResult = healthcheckResults.get(taskId);

      if (healthcheckResult == null) {
        LOG.debug("No healthcheck present for {}", taskId);
        return DeployHealth.WAITING;
      } else if (healthcheckResult.isFailed()) {
        LOG.debug("Found a failed healthcheck: {}", healthcheckResult);

        if (deploy.getHealthcheckMaxRetries().isPresent() && taskManager.getNumHealthchecks(taskId) > deploy.getHealthcheckMaxRetries().get()) {
          LOG.debug("{} failed {} healthchecks, the max for the deploy", taskId, deploy.getHealthcheckMaxRetries().get());
          return DeployHealth.UNHEALTHY;
        }

        if (isDeployPending && deploy.getHealthcheckMaxTotalTimeoutSeconds().isPresent()) {
          Collection<SingularityTaskHistoryUpdate> updates = taskManager.getTaskHistoryUpdates(taskId);

          long runningAt = 0;

          for (SingularityTaskHistoryUpdate update : updates) {
            if (update.getTaskState() == ExtendedTaskState.TASK_RUNNING) {
              runningAt = update.getTimestamp();
              break;
            }
          }

          if (runningAt > 0) {
            final long durationSinceRunning = System.currentTimeMillis() - runningAt;

            if (durationSinceRunning > TimeUnit.SECONDS.toMillis(deploy.getHealthcheckMaxTotalTimeoutSeconds().get())) {
              LOG.debug("{} has been running for {} and has yet to pass healthchecks, failing deploy", taskId, JavaUtils.durationFromMillis(durationSinceRunning));

              return DeployHealth.UNHEALTHY;
            }
          }
        }

        return DeployHealth.WAITING;
      }
    }

    return DeployHealth.HEALTHY;
  }

}


text:
import time
import traceback

from datetime import timedelta
from workers.models import Job
from drivers import browsers
from workers.models import Task, RunControl
from workers.utils.commons import build_control_key
from grabbers.utils.processors import ProcessSequence, ProcessCondition

# proxy
from proxy.utils.proxy import MobProxy

# celery
from celery.task.schedules import crontab
from celery.decorators import periodic_task

# ----- (1) tasks ----- #

@periodic_task(queue='tasks', run_every=(timedelta(seconds=3)))
def task_run():
    '''
    '''
    # one more try
    # db.close_old_connections()

    # get task, set to running
    task_in = Task.objects.filter(status='wait').first()
    if not task_in:
        print('[+] No tasks in wait')
        return
    task_in.status = 'running'
    task_in.save()

    # start thread
    init_time = time.time()

    # must have
    job = task_in.job
    if not task_in.config.sequence and not task_in.config.mapper:
        print('[+] Sequence or mapper must be set')
        return

    # loading vars
    wd = None
    url = task_in.target_url
    round_number = task_in.round_number
    control_key = build_control_key(url, job.id)
    mapper = task_in.config.mapper
    sequence = task_in.config.sequence
    try:
        # proxy
        MobProxy.connect(task_in)
        proxy_port = MobProxy.port()
        # build driver
        wd = getattr(browsers, task_in.config.driver.type)()
        wd.build_driver(taskConfs=task_in.config, proxy_port=proxy_port)
        print('[+] Starting GET request [{}]'.format(url))
        wd.get(url)
        if task_in.config.condition:
            cond = ProcessCondition(wd, task_in.config.condition)
            # only run sequence if cond
            cond.run()
        # process get
        process = ProcessSequence()
        process.set_job(job)
        process.set_task(task_in)
        process.set_target_url(url)
        process.set_browser(wd)
        if mapper:
            process.mapping(mapper)
        elif sequence:
            process.set_sequence(sequence)
        else:
            raise Exception('Must set mapper or sequence')
        process.run()
        MobProxy.save_data()
        status = 'done'
        job.tasks_done_count += 1
        job.save()
    except Exception:
        traceback.print_exc()
        status = 'fail'

    if wd:
        try:
            wd.close()
        except Exception as e:
            print('[-] Fail to close browser:[{}]'.format(e))
            del wd

    time_used = time.time() - init_time
    print('[+] Process took: [{0:.2f}] seconds'.format(time_used))

    # status task done -- all this for a thread issue -- improving
    task_in.status = status
    task_in.save()
    return

# ----- (2) jobs ----- #

@periodic_task(queue='jobs', run_every=(crontab(minute="*/5")))
def jobs_run():
    '''
    '''
    tasks_ceiling = 150
    run_control = RunControl()
    while True:
        jobs = Job.objects.filter(status__in=['created', 'running'])
        jobs_count = jobs.count()
        if not jobs_count:
            print('[+] No new jobs and no jobs running')
            if run_control.ask_count <= 3:
                time.sleep(30 * run_control.run_count)
                run_control.ask_count += 1
                continue
            break
        # ask renew
        run_control.ask_count = 0
        # soon will consider tasks duration
        tasks_limit = 100
        taskal = tasks_ceiling / jobs_count
        if taskal > 1:
            tasks_limit = taskal
        for job in jobs:
            tasks = Task.objects.filter(job=job, status='created')
            tasks_count = tasks.count()
            # new job
            if job.status == 'created':
                print("[+] Starting job {}.\
                Total tasks: {}".format(job.name, tasks_count))
                job.status = 'running'
                job.save()
            # done job
            if not tasks_count:
                if job.done_count >= 2:
                    job.status = 'done'
                    job.save()
                    print('[+] Job {} is done'.format(job.name))
                    continue
                job.done_count += 1
                job.save()
                time.sleep(0.01)
                continue
            # run task
            for task in tasks[:tasks_limit]:
                task.status = 'wait'
                task.save()
                time.sleep(0.01)


text:
<?php
$joined_features_waitlist = false;

$joined_waitlists = WMobilePack_Options::get_setting('joined_waitlists');

if ($joined_waitlists != '' && in_array('themes_features', $joined_waitlists))
    $joined_features_waitlist = true;

// check if we have a https connection
$is_secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443;

?>

Sign up and get FREE mobile growth lessons:

		<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">

			<form action="https://wpmobilepack.us13.list-manage.com/subscribe/post?u=df15f7f3ba7071146f98e66b3&id=6989f14b64" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

Subscribe

* indicates required

						Email Address  *

						<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" style="margin:auto;">

						First Name
						<input type="text" value="" name="FNAME" class="" id="mce-FNAME" style="margin:auto;">

						Last Name
						<input type="text" value="" name="LNAME" class="" id="mce-LNAME" style="margin:auto;">

						Business
						<input type="text" value="" name="MMERGE5" class="" id="mce-MMERGE5" style="margin:auto;">

<input type="text" name="b_df15f7f3ba7071146f98e66b3_6989f14b64" tabindex="-1" value="">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

			</form>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>类 net.sf.pagecache.constructs.web.plugins.redis.JedisManager的使用 (pagecache-redis 0.0.1-SNAPSHOT API)</title>
<meta name="date" content="2016-05-23">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类

类 net.sf.pagecache.constructs.web.plugins.redis.JedisManager
的使用

使用JedisManager的程序包

程序包
说明

net.sf.pagecache.constructs.web.plugins.redis

net.sf.pagecache.constructs.web.plugins.redis中JedisManager的使用

声明为JedisManager的net.sf.pagecache.constructs.web.plugins.redis中的字段

限定符和类型
字段和说明

private JedisManager
RedisPageCacheManage.jedisManager

返回JedisManager的net.sf.pagecache.constructs.web.plugins.redis中的方法

限定符和类型
方法和说明

static JedisManager
JedisManagerFactory.createJedisManager()

参数类型为JedisManager的net.sf.pagecache.constructs.web.plugins.redis中的构造器

构造器和说明

RedisPageCacheManage(JedisManager jedisManager)

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类

Copyright © 2016. All rights reserved.


text:
package io.fabric8.kubernetes.assertions;

import io.fabric8.kubernetes.api.KubernetesHelper;
import io.fabric8.kubernetes.api.model.Endpoints;
import io.fabric8.kubernetes.api.model.EndpointsList;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServiceAssert;
import io.fabric8.kubernetes.api.model.ServiceSpec;
import io.fabric8.kubernetes.api.model.extensions.LabelSelector;
import io.fabric8.kubernetes.api.model.extensions.LabelSelectorRequirement;
import io.fabric8.kubernetes.client.KubernetesClient;

import java.util.List;
import java.util.Map;

import static io.fabric8.kubernetes.api.KubernetesHelper.getLabels;
import static io.fabric8.kubernetes.assertions.PodSelectionAssert.getDefaultNotReadyTimeoutMs;
import static io.fabric8.kubernetes.assertions.PodSelectionAssert.getDefaultReadyPeriodMs;

/**
 * Adds assertions for asserting that a Service has ready pods etc
 */
public class ServicePodsAssert extends ServiceAssert implements HasPodSelectionAssert {
    private final KubernetesClient client;

    public ServicePodsAssert(KubernetesClient client, Service actual) {
        super(actual);
        this.client = client;
    }

    @Override
    public PodSelectionAssert pods() {
        spec().isNotNull().selector().isNotNull();
        ServiceSpec spec = this.actual.getSpec();
        int replicas = 1;
        LabelSelector selector = null;
        Map<String, String> matchLabels = spec.getSelector();
        List<LabelSelectorRequirement> matchExpressions = selector.getMatchExpressions();
        return new PodSelectionAssert(client, replicas, matchLabels, matchExpressions, "Service " + KubernetesHelper.getName(actual));
    }

    /**
     * Asserts that either this service has a valid Endpoint or that a pod is Ready for a period of time
     */
    public ServicePodsAssert hasEndpointOrReadyPod() {
        return hasEndpointOrReadyPod(getDefaultNotReadyTimeoutMs(), getDefaultReadyPeriodMs());
    }

    /**
     * Asserts that either this service has a valid Endpoint or that a pod is Ready for a period of time
     */
    public ServicePodsAssert hasEndpointOrReadyPod(long notReadyTimeoutMS, long readyPeriodMS) {
        EndpointsList list = client.endpoints().withLabels(getLabels(actual)).list();
        if (list != null) {
            List<Endpoints> items = list.getItems();
            if (items.size() > 0) {
                return this;
            }
        }
        pods().isPodReadyForPeriod(notReadyTimeoutMS, readyPeriodMS);
        return this;
    }
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
   - Example Configuration Database Entry for a BulkDataThreadDistributer
   -
   - Author: oat
   -
   - History:
   -   2004-11-23  oat  Created
  -->
<BulkDataDistributer xmlns="urn:schemas-cosylab-com:BulkDataDistributer:1.0"
	  xmlns:baci="urn:schemas-cosylab-com:BACI:1.0"
	  xmlns:cdb="urn:schemas-cosylab-com:CDB:1.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	  sender_protocols="TCP/TCP/TCP/TCP"
	  recv_protocols="TCP/TCP/TCP/TCP"/>


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace Cake.Core
{
    internal static class Constants
    {
        public static class Paths
        {
            public const string Tools = "Paths_Tools";
            public const string Addins = "Paths_Addins";
        }
    }
}


text:
$(function() {
  // Get a reference to the root of the chat data.
  var messagesRef = new Firebase("https://INSTANCE.firebaseio.com/chat");

  // When the user presses enter on the message input, write the message to firebase.
  $("#messageInput").keypress(function (e) {
    if (e.keyCode == 13) {
      var name = $("#nameInput").val();
      var text = $("#messageInput").val();
      messagesRef.push({name:name, text:text});
      $("#messageInput").val("");
    }
  });

  // Add a callback that is triggered for each chat message.
  messagesRef.limitToLast(10).on("child_added", function (snapshot) {
    var message = snapshot.val();
    $("<div/>").text(message.text).prepend($("<em/>")
      .text(message.name + ": ")).appendTo($("#messagesDiv"));
    $("#messagesDiv")[0].scrollTop = $("#messagesDiv")[0].scrollHeight;
  });
});