text:
"""
    sphinx.theming
    ~~~~~~~~~~~~~~

    Theming support for HTML builders.

    :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

import os
import shutil
import zipfile
import tempfile
import ConfigParser
from os import path

from sphinx import package_dir
from sphinx.errors import ThemeError

NODEFAULT = object()
THEMECONF = 'theme.conf'

class Theme(object):
    """
    Represents the theme chosen in the configuration.
    """
    themes = {}

    @classmethod
    def init_themes(cls, confdir, theme_path, warn=None):
        """Search all theme paths for available themes."""
        cls.themepath = list(theme_path)
        cls.themepath.append(path.join(package_dir, 'themes'))

        for themedir in cls.themepath[::-1]:
            themedir = path.join(confdir, themedir)
            if not path.isdir(themedir):
                continue
            for theme in os.listdir(themedir):
                if theme.lower().endswith('.zip'):
                    try:
                        zfile = zipfile.ZipFile(path.join(themedir, theme))
                        if THEMECONF not in zfile.namelist():
                            continue
                        tname = theme[:-4]
                        tinfo = zfile
                    except Exception:
                        if warn:
                            warn('file %r on theme path is not a valid '
                                 'zipfile or contains no theme' % theme)
                        continue
                else:
                    if not path.isfile(path.join(themedir, theme, THEMECONF)):
                        continue
                    tname = theme
                    tinfo = None
                cls.themes[tname] = (path.join(themedir, theme), tinfo)

    def __init__(self, name):
        if name not in self.themes:
            raise ThemeError('no theme named %r found '
                             '(missing theme.conf?)' % name)
        self.name = name

        tdir, tinfo = self.themes[name]
        if tinfo is None:
            # already a directory, do nothing
            self.themedir = tdir
            self.themedir_created = False
        else:
            # extract the theme to a temp directory
            self.themedir = tempfile.mkdtemp('sxt')
            self.themedir_created = True
            for name in tinfo.namelist():
                if name.endswith('/'): continue
                dirname = path.dirname(name)
                if not path.isdir(path.join(self.themedir, dirname)):
                    os.makedirs(path.join(self.themedir, dirname))
                fp = open(path.join(self.themedir, name), 'wb')
                fp.write(tinfo.read(name))
                fp.close()

        self.themeconf = ConfigParser.RawConfigParser()
        self.themeconf.read(path.join(self.themedir, THEMECONF))

        try:
            inherit = self.themeconf.get('theme', 'inherit')
        except ConfigParser.NoOptionError:
            raise ThemeError('theme %r doesn\'t have "inherit" setting' % name)
        if inherit == 'none':
            self.base = None
        elif inherit not in self.themes:
            raise ThemeError('no theme named %r found, inherited by %r' %
                             (inherit, name))
        else:
            self.base = Theme(inherit)

    def get_confstr(self, section, name, default=NODEFAULT):
        """Return the value for a theme configuration setting, searching the
        base theme chain.
        """
        try:
            return self.themeconf.get(section, name)
        except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
            if self.base is not None:
                return self.base.get_confstr(section, name, default)
            if default is NODEFAULT:
                raise ThemeError('setting %s.%s occurs in none of the '
                                 'searched theme configs' % (section, name))
            else:
                return default

    def get_options(self, overrides):
        """Return a dictionary of theme options and their values."""
        chain = [self.themeconf]
        base = self.base
        while base is not None:
            chain.append(base.themeconf)
            base = base.base
        options = {}
        for conf in reversed(chain):
            try:
                options.update(conf.items('options'))
            except ConfigParser.NoSectionError:
                pass
        for option, value in overrides.iteritems():
            if option not in options:
                raise ThemeError('unsupported theme option %r given' % option)
            options[option] = value
        return options

    def get_dirchain(self):
        """Return a list of theme directories, beginning with this theme's,
        then the base theme's, then that one's base theme's, etc.
        """
        chain = [self.themedir]
        base = self.base
        while base is not None:
            chain.append(base.themedir)
            base = base.base
        return chain

    def cleanup(self):
        """Remove temporary directories."""
        if self.themedir_created:
            try:
                shutil.rmtree(self.themedir)
            except Exception:
                pass
        if self.base:
            self.base.cleanup()


text:
package com.whippy.poker.server.beans;

import static org.junit.Assert.fail;

import org.junit.Test;

import com.whippy.poker.common.beans.Card;
import com.whippy.poker.common.beans.Deck;
import com.whippy.poker.common.beans.Suit;
import com.whippy.poker.common.beans.Value;

public class DeckTest {

        //~ ----------------------------------------------------------------------------------------------------------------
        //~ Methods
        //~ ----------------------------------------------------------------------------------------------------------------

        @Test
        public void testShuffle() {
                Deck deck = new Deck();
                deck.shuffle();
                if(deck.getTopCard().equals(new Card(Suit.SPADES, Value.ACE))){
                        if(deck.getTopCard().equals(new Card(Suit.SPADES, Value.KING))){
                                fail("Top 2 cards are as if deck not shuffled");
                        }
                }
        }

}
//J+

redpajama_set_name: RedPajamaGithub


text:
import unittest

from go_counting import (
    Board,
    WHITE,
    BLACK,
    NONE,
)

# Tests adapted from `problem-specifications//canonical-data.json`

class GoCountingTest(unittest.TestCase):
    def test_black_corner_territory_on_5x5_board(self):
        board = Board(["  B  ", " B B ", "B W B", " W W ", "  W  "])
        stone, territory = board.territory(x=0, y=1)
        self.assertEqual(stone, BLACK)
        self.assertSetEqual(territory, {(0, 0), (0, 1), (1, 0)})

    def test_white_center_territory_on_5x5_board(self):
        board = Board(["  B  ", " B B ", "B W B", " W W ", "  W  "])
        stone, territory = board.territory(x=2, y=3)
        self.assertEqual(stone, WHITE)
        self.assertSetEqual(territory, {(2, 3)})

    def test_open_corner_territory_on_5x5_board(self):
        board = Board(["  B  ", " B B ", "B W B", " W W ", "  W  "])
        stone, territory = board.territory(x=1, y=4)
        self.assertEqual(stone, NONE)
        self.assertSetEqual(territory, {(0, 3), (0, 4), (1, 4)})

    def test_a_stone_and_not_a_territory_on_5x5_board(self):
        board = Board(["  B  ", " B B ", "B W B", " W W ", "  W  "])
        stone, territory = board.territory(x=1, y=1)
        self.assertEqual(stone, NONE)
        self.assertSetEqual(territory, set())

    def test_invalid_because_x_is_too_low_for_5x5_board(self):
        board = Board(["  B  ", " B B ", "B W B", " W W ", "  W  "])
        with self.assertRaises(ValueError) as err:
            board.territory(x=-1, y=1)
        self.assertEqual(type(err.exception), ValueError)
        self.assertEqual(err.exception.args[0], "Invalid coordinate")

    def test_invalid_because_x_is_too_high_for_5x5_board(self):
        board = Board(["  B  ", " B B ", "B W B", " W W ", "  W  "])
        with self.assertRaises(ValueError) as err:
            board.territory(x=5, y=1)
        self.assertEqual(type(err.exception), ValueError)
        self.assertEqual(err.exception.args[0], "Invalid coordinate")

    def test_invalid_because_y_is_too_low_for_5x5_board(self):
        board = Board(["  B  ", " B B ", "B W B", " W W ", "  W  "])
        with self.assertRaises(ValueError) as err:
            board.territory(x=1, y=-1)
        self.assertEqual(type(err.exception), ValueError)
        self.assertEqual(err.exception.args[0], "Invalid coordinate")

    def test_invalid_because_y_is_too_high_for_5x5_board(self):
        board = Board(["  B  ", " B B ", "B W B", " W W ", "  W  "])
        with self.assertRaises(ValueError) as err:
            board.territory(x=1, y=5)
        self.assertEqual(type(err.exception), ValueError)
        self.assertEqual(err.exception.args[0], "Invalid coordinate")

    def test_one_territory_is_the_whole_board(self):
        board = Board([" "])
        territories = board.territories()
        self.assertSetEqual(territories[BLACK], set())
        self.assertSetEqual(territories[WHITE], set())
        self.assertSetEqual(territories[NONE], {(0, 0)})

    def test_two_territory_rectangular_board(self):
        board = Board([" BW ", " BW "])
        territories = board.territories()
        self.assertSetEqual(territories[BLACK], {(0, 0), (0, 1)})
        self.assertSetEqual(territories[WHITE], {(3, 0), (3, 1)})
        self.assertSetEqual(territories[NONE], set())

    def test_two_region_rectangular_board(self):
        board = Board([" B "])
        territories = board.territories()
        self.assertSetEqual(territories[BLACK], {(0, 0), (2, 0)})
        self.assertSetEqual(territories[WHITE], set())
        self.assertSetEqual(territories[NONE], set())

    # Utility functions
    def assertRaisesWithMessage(self, exception):
        return self.assertRaisesRegex(exception, r".+")

if __name__ == "__main__":
    unittest.main()


text:
<!DOCTYPE html>

  <title>three.js</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

    three.js

Deferred (PBR)


text:
package com.cloudera.oryx.lambda;

import java.io.Closeable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.google.common.base.Preconditions;
import com.typesafe.config.Config;
import kafka.serializer.Decoder;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.OutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.storage.StorageLevel;
import org.apache.spark.streaming.Duration;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.streaming.kafka.KafkaUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudera.oryx.common.lang.ClassUtils;
import com.cloudera.oryx.common.settings.ConfigUtils;

/**
 * Main entry point for Oryx Batch Layer.
 *
 * @param <K> type of key read from input topic
 * @param <M> type of message read from input topic
 * @param <U> type of model message written
 */
public final class BatchLayer<K,M,U> implements Closeable {

  private static final Logger log = LoggerFactory.getLogger(BatchLayer.class);

  private final Config config;
  private final String id;
  private final String streamingMaster;
  private final String topicLockMaster;
  private final String messageTopic;
  private final Class<K> keyClass;
  private final Class<M> messageClass;
  private final Class<? extends Decoder<?>> keyDecoderClass;
  private final Class<? extends Decoder<?>> messageDecoderClass;
  private final Class<? extends Writable> keyWritableClass;
  private final Class<? extends Writable> messageWritableClass;
  private final String updateClassName;
  private final String dataDirString;
  private final String modelDirString;
  private final int numExecutors;
  private final int executorCores;
  private final String executorMemoryString;
  private final String driverMemoryString;
  private final int receiverParallelism;
  private final int generationIntervalSec;
  private final int blockIntervalSec;
  private final int storagePartitions;
  private final int uiPort;
  private JavaStreamingContext streamingContext;

  @SuppressWarnings("unchecked")
  public BatchLayer(Config config) {
    Preconditions.checkNotNull(config);
    log.info("Configuration:\n{}", ConfigUtils.prettyPrint(config));
    this.config = config;
    this.id = ConfigUtils.getOptionalString(config, "oryx.id");
    this.streamingMaster = config.getString("oryx.batch.streaming.master");
    this.topicLockMaster = config.getString("oryx.input-topic.lock.master");
    this.messageTopic = config.getString("oryx.input-topic.message.topic");
    this.keyClass = ClassUtils.loadClass(config.getString("oryx.input-topic.message.key-class"));
    this.messageClass =
        ClassUtils.loadClass(config.getString("oryx.input-topic.message.message-class"));
    this.keyDecoderClass = (Class<? extends Decoder<?>>) ClassUtils.loadClass(
        config.getString("oryx.input-topic.message.key-decoder-class"), Decoder.class);
    this.messageDecoderClass = (Class<? extends Decoder<?>>) ClassUtils.loadClass(
        config.getString("oryx.input-topic.message.message-decoder-class"), Decoder.class);
    this.keyWritableClass = ClassUtils.loadClass(
        config.getString("oryx.batch.storage.key-writable-class"), Writable.class);
    this.messageWritableClass = ClassUtils.loadClass(
        config.getString("oryx.batch.storage.message-writable-class"), Writable.class);
    this.updateClassName = config.getString("oryx.batch.update-class");
    this.dataDirString = config.getString("oryx.batch.storage.data-dir");
    this.modelDirString = config.getString("oryx.batch.storage.model-dir");
    this.numExecutors = config.getInt("oryx.batch.streaming.num-executors");
    this.executorCores = config.getInt("oryx.batch.streaming.executor-cores");
    this.executorMemoryString = config.getString("oryx.batch.streaming.executor-memory");
    this.driverMemoryString = config.getString("oryx.batch.streaming.driver-memory");
    this.receiverParallelism = config.getInt("oryx.batch.streaming.receiver-parallelism");
    this.generationIntervalSec = config.getInt("oryx.batch.streaming.generation-interval-sec");
    this.blockIntervalSec = config.getInt("oryx.batch.streaming.block-interval-sec");
    this.storagePartitions = config.getInt("oryx.batch.storage.partitions");
    this.uiPort = config.getInt("oryx.batch.ui.port");

    Preconditions.checkArgument(!dataDirString.isEmpty());
    Preconditions.checkArgument(!modelDirString.isEmpty());
    Preconditions.checkArgument(numExecutors >= 1);
    Preconditions.checkArgument(executorCores >= 1);
    Preconditions.checkArgument(receiverParallelism >= 1);
    Preconditions.checkArgument(generationIntervalSec > 0);
    Preconditions.checkArgument(blockIntervalSec > 0);
    Preconditions.checkArgument(storagePartitions > 0);
    Preconditions.checkArgument(uiPort > 0);
  }

  public synchronized void start() {
    if (id != null) {
      log.info("Starting Batch Layer {}", id);
    }
    log.info("Starting SparkContext for master {}, interval {} seconds",
             streamingMaster, generationIntervalSec);

    long blockIntervalMS = TimeUnit.MILLISECONDS.convert(blockIntervalSec, TimeUnit.SECONDS);

    SparkConf sparkConf = new SparkConf();

    sparkConf.setIfMissing("spark.serializer", "org.apache.spark.serializer.KryoSerializer");

    sparkConf.setIfMissing("spark.executor.instances", Integer.toString(numExecutors));
    sparkConf.setIfMissing("spark.executor.cores", Integer.toString(executorCores));
    sparkConf.setIfMissing("spark.executor.memory", executorMemoryString);
    sparkConf.setIfMissing("spark.driver.memory", driverMemoryString);

    String blockIntervalString = Long.toString(blockIntervalMS);
    sparkConf.setIfMissing("spark.streaming.blockInterval", blockIntervalString);
    // Turn this down to prevent long blocking at shutdown
    sparkConf.setIfMissing("spark.streaming.gracefulStopTimeout", blockIntervalString);
    sparkConf.setIfMissing("spark.cleaner.ttl", Integer.toString(20 * generationIntervalSec));
    sparkConf.setIfMissing("spark.logConf", "true");
    sparkConf.setIfMissing("spark.ui.port", Integer.toString(uiPort));
    sparkConf.setIfMissing("spark.ui.showConsoleProgress", "false");

    // Want to use some versions that may not match Spark or YARN
    sparkConf.setIfMissing("spark.yarn.user.classpath.first", "true");
    // Don't set spark.files.userClassPathFirst (see issue #120)

    sparkConf.setMaster(streamingMaster);
    sparkConf.setAppName("OryxBatchLayer");
    long batchDurationMS =
       TimeUnit.MILLISECONDS.convert(generationIntervalSec, TimeUnit.SECONDS);

    streamingContext = new JavaStreamingContext(new JavaSparkContext(sparkConf),
                                                new Duration(batchDurationMS));

    log.info("Creating message stream from topic");

    JavaPairDStream<K,M> dStream = buildDStream();

    dStream.foreachRDD(
        new BatchUpdateFunction<>(config,
                                  keyClass,
                                  messageClass,
                                  keyWritableClass,
                                  messageWritableClass,
                                  dataDirString,
                                  modelDirString,
                                  loadUpdateInstance(),
                                  streamingContext));

    // Save data to HDFS. Write the original message type, not transformed.
    JavaPairDStream<Writable,Writable> writableDStream =
        dStream.repartition(storagePartitions).mapToPair(
            new ValueToWritableFunction<>(keyClass,
                                          messageClass,
                                          keyWritableClass,
                                          messageWritableClass));

    // This horrible, separate declaration is necessary to appease the compiler
    @SuppressWarnings("unchecked")
    Class<? extends OutputFormat<?,?>> outputFormatClass =
        (Class<? extends OutputFormat<?,?>>) (Class<?>) SequenceFileOutputFormat.class;

    // "Inline" saveAsNewAPIHadoopFiles to be able to skip saving empty RDDs
    writableDStream.foreachRDD(
        new SaveToHDFSFunction(dataDirString + "/oryx",
                               "data",
                               keyWritableClass,
                               messageWritableClass,
                               outputFormatClass,
                               streamingContext.sparkContext().hadoopConfiguration()));

    log.info("Starting Spark Streaming");

    streamingContext.start();
  }

  public void await() {
    Preconditions.checkState(streamingContext != null);
    log.info("Spark Streaming is running");
    streamingContext.awaitTermination();
  }

  @Override
  public synchronized void close() {
    if (streamingContext != null) {
      log.info("Shutting down");
      streamingContext.stop(true, true);
      streamingContext = null;
    }
  }

  private JavaPairDStream<K,M> buildDStream() {
    Map<String,String> kafkaParams = new HashMap<>();
    kafkaParams.put("zookeeper.connect", topicLockMaster);
    kafkaParams.put("group.id", "OryxGroup-BatchLayer-" + System.currentTimeMillis());
    // Don't re-consume old messages from input
    kafkaParams.put("auto.offset.reset", "largest");
    if (id != null) {
      // Set consumer.id to access last read offset for the layer
      kafkaParams.put("consumer.id", "Oryx-BatchLayer-" + id);
    }

    List<JavaPairDStream<K,M>> streams = new ArrayList<>(receiverParallelism);
    for (int i = 0; i < receiverParallelism; i++) {
      streams.add(KafkaUtils.createStream(
                    streamingContext,
                    keyClass,
                    messageClass,
                    keyDecoderClass,
                    messageDecoderClass,
                    kafkaParams,
                    Collections.singletonMap(messageTopic, 1),
                    StorageLevel.MEMORY_AND_DISK_2()));
    }

    if (streams.size() == 1) {
      return streams.get(0);
    } else {
      return streamingContext.union(streams.get(0), streams.subList(1, streams.size()));
    }
  }

  @SuppressWarnings("unchecked")
  private BatchLayerUpdate<K,M,U> loadUpdateInstance() {
    Class<?> updateClass = ClassUtils.loadClass(updateClassName);

    if (BatchLayerUpdate.class.isAssignableFrom(updateClass)) {

      try {
        return ClassUtils.loadInstanceOf(
            updateClassName,
            BatchLayerUpdate.class,
            new Class<?>[]{Config.class},
            new Object[]{config});
      } catch (IllegalArgumentException iae) {
        return ClassUtils.loadInstanceOf(updateClassName, BatchLayerUpdate.class);
      }

    } else if (ScalaBatchLayerUpdate.class.isAssignableFrom(updateClass)) {

      try {
        return new ScalaBatchLayerUpdateAdapter<>(ClassUtils.loadInstanceOf(
            updateClassName,
            ScalaBatchLayerUpdate.class,
            new Class<?>[]{Config.class},
            new Object[]{config}));
      } catch (IllegalArgumentException iae) {
        return new ScalaBatchLayerUpdateAdapter<>(ClassUtils.loadInstanceOf(
            updateClassName, ScalaBatchLayerUpdate.class));
      }

    } else {
      throw new IllegalArgumentException("Bad update class: " + updateClassName);
    }
  }

}


text:
/* global sinon:true debounce:true */
/* eslint no-unused-expressions: 0 */
(function () {
	'use strict';

	describe('debounce', function () {
		it('should call the function once every 1s on the leading edge', function (done) {
			var spy = sinon.spy();
			var debounced = debounce(spy, 1000, true);
			debounced();
			debounced();
			debounced();
			setTimeout(function () {
				spy.should.have.been.calledOnce;
				done();
			}, 1000);
		});

		it('should call the function once every 1s on the trailing edge', function (done) {
			var spy = sinon.spy();
			var debounced = debounce(spy, 1000);
			debounced();
			debounced();
			debounced();
			setTimeout(function () {
				spy.should.have.been.calledOnce;
				done();
			}, 1000);
		});
	});
}());


text:
class Spree::Base < ActiveRecord::Base
  include Spree::Preferences::Preferable
  serialize :preferences, Hash
  after_initialize do
    if has_attribute?(:preferences)
      self.preferences = default_preferences.merge(preferences)
    end
  end

  if Kaminari.config.page_method_name != :page
    def self.page num
      send Kaminari.config.page_method_name, num
    end
  end

  self.abstract_class = true
end


text:
using UnityEngine;
using UnityEditor;

namespace CreateThis.Factory.VR.UI.Button {
    [CustomEditor(typeof(KeyboardToggleButtonFactory))]
    [CanEditMultipleObjects]
    public class KeyboardToggleButtonFactoryEditor : ToggleButtonFactoryEditor {
        SerializedProperty keyboard;

        protected override void OnEnable() {
            base.OnEnable();
            keyboard = serializedObject.FindProperty("keyboard");
        }

        protected override void BuildGenerateButton() {
            if (GUILayout.Button("Generate")) {
                if (target.GetType() == typeof(KeyboardToggleButtonFactory)) {
                    KeyboardToggleButtonFactory buttonFactory = (KeyboardToggleButtonFactory)target;
                    buttonFactory.Generate();
                }
            }
        }

        protected override void AdditionalProperties() {
            base.AdditionalProperties();
            EditorGUILayout.PropertyField(keyboard);
        }
    }
}


text:
package com.jlj.dao;

import java.util.List;

import com.jlj.model.Prizer;

public interface IPrizerDao {

	/* (non-Javadoc)
	 * @see com.jlj.dao.imp.IBigtypeDao#save(com.jlj.model.Bigtype)
	 * 保存一条记录
	 */
	public abstract void save(Prizer prizer);

	/* (non-Javadoc)
	 * @see com.jlj.dao.imp.IBigtypeDao#delete(com.jlj.model.Bigtype)
	 * 删除一条记录
	 */
	public abstract void delete(Prizer prizer);

	/* (non-Javadoc)
	 * @see com.jlj.dao.imp.IBigtypeDao#deleteById(int)
	 * 根据ID删除一条记录
	 */
	public abstract void deleteById(int id);

	/* (non-Javadoc)
	 * @see com.jlj.dao.imp.IBigtypeDao#update(com.jlj.model.Bigtype)
	 * 修改一条记录
	 */
	public abstract void update(Prizer prizer);

	/* (non-Javadoc)
	 * @see com.jlj.dao.imp.IBigtypeDao#updateByHql(java.lang.String, java.lang.String[], java.lang.Object[])
	 * 根据hql语句、条件、条件值修改某些记录
	 */
	public abstract void updateByHql(final String hql,
			final String[] paramNames, final Object[] values);

	/* (non-Javadoc)
	 * @see com.jlj.dao.imp.IBigtypeDao#getBigtypes()
	 * 获得所有记录
	 */
	public abstract List<Prizer> getPrizers();

	/* (non-Javadoc)
	 * @see com.jlj.dao.imp.IBigtypeDao#queryList(java.lang.String)
	 * 根据hql语句来查询所有记录
	 */
	public abstract List<Prizer> queryList(String queryString);

	/* (non-Javadoc)
	 * @see com.jlj.dao.imp.IBigtypeDao#getObjectsByCondition(java.lang.String, java.lang.Object[])
	 * 根据hql、条件值查询某些记录
	 */
	public abstract List<Prizer> getObjectsByCondition(String queryString,
			Object[] p);

	/* (non-Javadoc)
	 * @see com.jlj.dao.imp.IBigtypeDao#queryList(java.lang.String, java.lang.String[], java.lang.Object[])
	 * 根据hql语句、条件、条件值查询某些记录
	 */
	public abstract List<Prizer> queryList(String queryString,
			String[] paramNames, Object[] values);

	/* (non-Javadoc)
	 * @see com.jlj.dao.imp.IBigtypeDao#getObjectsByIdList(java.lang.String, java.util.List)
	 * 根据hql、id列表查询某些记录
	 */
	public abstract List<Prizer> getObjectsByIdList(final String hql,
			final List<Integer> idList);

	/* (non-Javadoc)
	 * @see com.jlj.dao.imp.IBigtypeDao#pageList(java.lang.String, java.lang.Object[], java.lang.Integer, java.lang.Integer)
	 * 根据hql语句、条件值、分页查询某些记录
	 */
	public abstract List<Prizer> pageList(final String queryString,
			final Object[] p, final Integer page, final Integer size);

	/* (non-Javadoc)
	 * @see com.jlj.dao.imp.IBigtypeDao#getUniqueResult(java.lang.String, java.lang.Object[])
	 * 根据hql、条件值获得一个唯一值
	 */
	public abstract int getUniqueResult(final String queryString,
			final Object[] p);

	/* (non-Javadoc)
	 * @see com.jlj.dao.imp.IBigtypeDao#loadById(int)
	 * 根据id查询一条记录
	 */
	public abstract Prizer loadById(int id);

	/* (non-Javadoc)
	 * @see com.jlj.dao.imp.IBigtypeDao#queryByNamedParam(java.lang.String, java.lang.String[], java.lang.Object[])
	 * 根据hql语句、条件、值来查询一条记录
	 */
	public abstract Prizer queryByNamedParam(String queryString,
			String[] paramNames, Object[] values);

	/* (non-Javadoc)
	 * @see com.jlj.dao.imp.IBigtypeDao#checkClientExistsWithName(java.lang.String)
	 * 根据hql语句、条件值来查询是否存在该记录
	 */
	public abstract boolean checkClientExistsWithName(String queryString,
			Object[] p);

}


text:
package net.floodlightcontroller.debugevent;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.LinkedBlockingDeque;

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

public class CircularBuffer<T> implements Iterable<T>{
    protected static Logger log = LoggerFactory.getLogger(CircularBuffer.class);
    private final LinkedBlockingDeque<T> buffer;

    public CircularBuffer(int capacity) {
        this.buffer = new LinkedBlockingDeque<T>(capacity);
    }

    /**
     * Adding an element to the circular buffer implies adding the element to
     * the tail of the deque. In doing so, if the capacity of the buffer has
     * been exhausted, then the deque's head should be removed to preserve the
     * circular nature of the buffer. A LinkedBlockingDeque is used because of its
     * concurrent nature and the fact that adding to tail and removing from head are
     * both O(1) operations. The removed head is returned to the caller for reuse.
     *
     * @param e    the element to be added
     * @return     removed element (for reuse) or null
     */
    public T add(T e) {
        T oldE = null;
        while (!buffer.offerLast(e)) {
            oldE = buffer.poll();
        }
        return oldE;
    }

    /**
     * The basic idea here is that an ArrayList has been passed in, which may or may not
     * have a size bigger that the actual number of elements that are meant to
     * be flushed to the Circular Buffer. Thus the 'uptoIndex' parameter specifies
     * the number of elements that need to be flushed starting from index 0.
     * Note that after flushing, the circular buffer may return a memory unit (of type T)
     * for reuse in the list, if the circular buffer popped off memory to preserve
     * its circular nature. Or it may just return null if nothing was popped off.
     * Either way, the list that is returned by this method, is of the SAME SIZE
     * as the list passed in, as ArrayLists can hold null elements. The only difference
     * is that the list returned will have elements that reference old popped-off memory
     * from the circular-buffer or null.
     *
     * @param elist         the ArrayList to flush into the circular buffer.
     * @param uptoIndex     flush starting from index 0 upto but not including
     *                      index 'uptoIndex'.
     * @return              the 'elist' passed in with members now pointing to
     *                      to null or old-memory for reuse. The returned list
     *                      if of the same size as 'elist'.
     */
    public ArrayList<T> addAll(ArrayList<T> elist, int uptoIndex) {
        if (uptoIndex > elist.size()) {
            log.error("uptoIndex is greater than elist size .. aborting addAll");
            return elist;
        }
        for (int index=0; index < uptoIndex; index++) {
            T e = elist.get(index);
            if (e != null) {
                elist.set(index, add(e));
            }
        }
        return elist;
    }

    /**
     * Returns an iterator over the elements in the circular buffer in proper sequence.
     * The elements will be returned in order from most-recent to oldest.
     * The returned Iterator is a "weakly consistent" iterator that will never
     * throw ConcurrentModificationException, and guarantees to traverse elements
     * as they existed upon construction of the iterator, and may (but is not
     * guaranteed to) reflect any modifications subsequent to construction.
     */
    @Override
    public Iterator<T> iterator() {
        return buffer.descendingIterator();
    }

    public int size() {
        return buffer.size();
    }

    /**
     *  Atomically removes all elements in the circular buffer
     */
    public void clear() {
        buffer.clear();
    }
}


text:
package edu.umass.cs.jfoley.coop.experiments.deepscore;

import ciir.jfoley.chai.collections.TopKHeap;
import ciir.jfoley.chai.io.IO;
import ciir.jfoley.chai.io.LinesIterable;
import ciir.jfoley.chai.io.archive.ZipArchive;
import ciir.jfoley.chai.io.archive.ZipArchiveEntry;
import ciir.jfoley.chai.string.StrUtil;
import gnu.trove.map.hash.TIntObjectHashMap;
import org.lemurproject.galago.core.retrieval.ScoredDocument;
import org.lemurproject.galago.utility.lists.Ranked;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author jfoley
 */
public class FDMOutputToTrecrun {
  public static void main(String[] args) throws IOException {
    TIntObjectHashMap<String> names = new TIntObjectHashMap<>();
    try (LinesIterable lines = LinesIterable.fromFile("/mnt/net/roaming/jfoley/web-docs/robust.ids.tsv")) {
      for (String line : lines) {
        String[] row = line.split("\t");
        int id = Integer.parseInt(row[0]);
        String name = row[1].trim();
        names.put(id, name);
      }
    }
    System.err.println("loaded "+names.size()+" names!");
    try (PrintWriter trecrun = IO.openPrintWriter("latest.trecrun")) {
      try (ZipArchive zip = ZipArchive.open("/mnt/net/roaming/jfoley/web-docs/robust.fdm.fixed.zip")) {
        for (ZipArchiveEntry zipArchiveEntry : zip.listEntries()) {
          String n = zipArchiveEntry.getName();
          String[] parts = StrUtil.takeBetween(n, "robust.", ".tsv").split("\\.");
          String qid = parts[0];
          System.err.println(qid);

          TopKHeap<ScoredDocument> topScored = new TopKHeap<>(1000);
          try (LinesIterable lines = zipArchiveEntry.getLines()) {
            for (String line : lines) {
              String[] dat = line.split("\t");
              int id = Integer.parseInt(dat[0]);
              double score = Double.parseDouble(dat[1]);
              ScoredDocument sdoc = new ScoredDocument(id, score);
              topScored.offer(sdoc);
            }
          }
          List<ScoredDocument> docs = topScored.getSorted();
          Ranked.setRanksByScore(docs);

          for (ScoredDocument doc : docs) {
            doc.documentName = names.get((int) doc.document);
            trecrun.println(doc.toTRECformat(qid));
          }
        }
      }
    }
  }
}


text:
/*
  Noah Kurinsky
  7/9/2012
  This header provides the interface for the class that creates and performs operations on
  the two dimensional histograms used to fit the model to the data.

  Interface to be expanded to compute statistics on histograms
*/

#ifndef HIST_LIB_H
#define HIST_LIB_H

#include "functions.h"

//Needed for array manipulation by the GSL statistics procedures
#define H_STRIDE 1

class hist_lib{
 private:
  //variables for storage of dynamically created histograms
  double ** model_hist;
  double ** obs_hist;
  double ** comparison_hist;
  //properties of the histograms, set internally
  double xrange[2];
  double yrange[2];
  double xbinsize;
  double ybinsize;
  double chisq;
  int xysize;
  int osize,msize;
  double m_exc;
 public:
  //constructors
  hist_lib(); //All set to null
  hist_lib(double obs_c1[],double obs_c2[],int obs_size); //only observation histogram created
  //Functions for passing data to class if not already done so by constructor
  void init_obs(double c1[],double c2[],int size);
  bool init_model(double c1[],double c2[],int size);
  //Functions for outputting properties of histograms
  double get_chisq();
  bool write_fits(string filename);
  //Deconstructor for dynamic histogram arrays
  ~hist_lib();
 private:
  //functions which produce histograms
  double ** get_hist(double c1[],double c2[],int cnum); //compute histogram, fitting binsize
  double ** compute_hist(double c1[],double c2[],int cnum); //compute histogram for given inputs
  double fit_err();
  double poiss_err(int x);
};

#endif


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

set -ex

cd "$(dirname "$0")/../../.."

base=$(pwd)

mkdir -p artifacts/

# All the ruby packages have been built in the artifact phase already
# and we only collect them here to deliver them to the distribtest phase.
# Jenkins flow (deprecated)
cp -r "${EXTERNAL_GIT_ROOT}"/platform={windows,linux,macos}/artifacts/ruby_native_gem_*/* artifacts/ || true
# Kokoro flow
cp -r "${EXTERNAL_GIT_ROOT}"/input_artifacts/ruby_native_gem_*/* artifacts/ || true

well_known_protos=( any api compiler/plugin descriptor duration empty field_mask source_context struct timestamp type wrappers )

# TODO: all the artifact builder configurations generate a grpc-VERSION.gem
# source distribution package, and only one of them will end up
# in the artifacts/ directory. They should be all equivalent though.

for arch in {x86,x64}; do
  case $arch in
    x64)
      ruby_arch=x86_64
      ;;
    *)
      ruby_arch=$arch
      ;;
  esac
  for plat in {windows,linux,macos}; do
    if [ "${KOKORO_JOB_NAME}" != "" ]
    then
      input_dir="${EXTERNAL_GIT_ROOT}/input_artifacts/protoc_${plat}_${arch}"
    else
      input_dir="${EXTERNAL_GIT_ROOT}/platform=${plat}/artifacts/protoc_${plat}_${arch}"
    fi
    output_dir="$base/src/ruby/tools/bin/${ruby_arch}-${plat}"
    mkdir -p "$output_dir"/google/protobuf
    mkdir -p "$output_dir"/google/protobuf/compiler  # needed for plugin.proto
    cp "$input_dir"/protoc* "$output_dir"/
    cp "$input_dir"/grpc_ruby_plugin* "$output_dir"/
    for proto in "${well_known_protos[@]}"; do
      cp "$base/third_party/protobuf/src/google/protobuf/$proto.proto" "$output_dir/google/protobuf/$proto.proto"
    done
  done
done

cd "$base/src/ruby/tools"
gem build grpc-tools.gemspec
cp ./grpc-tools*.gem "$base/artifacts/"


text:
id: vim
title: Vim Setup
---

Vim users can install either [vim-prettier](https://github.com/prettier/vim-prettier), which is Prettier specific, or [Neoformat](https://github.com/sbdchd/neoformat) or [ALE](https://github.com/dense-analysis/ale) which are generalized lint/format engines with support for Prettier.

## [vim-prettier](https://github.com/prettier/vim-prettier)

See the [vim-prettier](https://github.com/prettier/vim-prettier) readme for installation and usage instructions.

## [Neoformat](https://github.com/sbdchd/neoformat)

The best way to install Neoformat is with your favorite plugin manager for Vim, such as [vim-plug](https://github.com/junegunn/vim-plug):

```vim
Plug 'sbdchd/neoformat'
```

In order for Neoformat to use a project-local version of Prettier (i.e. to use `node_modules/.bin/prettier` instead of looking for `prettier` on `$PATH`), you must set the `neoformat_try_node_exe` option:

```vim
let g:neoformat_try_node_exe = 1
```

Run `:Neoformat` or `:Neoformat prettier` in a supported file to run Prettier.

To have Neoformat run Prettier on save:

```vim
autocmd BufWritePre *.js Neoformat
```

You can also make Vim format your code more frequently, by setting an `autocmd` for other events. Here are a couple of useful ones:

- `TextChanged`: after a change was made to the text in Normal mode
- `InsertLeave`: when leaving Insert mode

For example, you can format on both of the above events together with `BufWritePre` like this:

```vim
autocmd BufWritePre,TextChanged,InsertLeave *.js Neoformat
```

See `:help autocmd-events` in Vim for details.

It's recommended to use a [config file](configuration.md), but you can also add options in your `.vimrc`:

```vim
autocmd FileType javascript setlocal formatprg=prettier\ --single-quote\ --trailing-comma\ es5
" Use formatprg when available
let g:neoformat_try_formatprg = 1
```

Each space in Prettier options should be escaped with `\`.

## [ALE](https://github.com/dense-analysis/ale)

ALE requires either Vim 8 or Neovim as ALE makes use of the asynchronous abilities that both Vim 8 and Neovim provide.

The best way to install ALE is with your favorite plugin manager for Vim, such as [vim-plug](https://github.com/junegunn/vim-plug):

```vim
Plug 'dense-analysis/ale'
```

You can find further instructions on the [ALE repository](https://github.com/dense-analysis/ale#3-installation).

ALE will try to use Prettier installed locally before looking for a global installation.

Enable the Prettier fixer for the languages you use:

```vim
let g:ale_fixers = {
\   'javascript': ['prettier'],
\   'css': ['prettier'],
\}
```

ALE supports both _linters_ and _fixers_. If you don't specify which _linters_ to run, **all available tools for all supported languages will be run,** and you might get a correctly formatted file with a bunch of lint errors. To disable this behavior you can tell ALE to run only linters you've explicitly configured (more info in the [FAQ](https://github.com/dense-analysis/ale/blob/ed8104b6ab10f63c78e49b60d2468ae2656250e9/README.md#faq-disable-linters)):

```vim
let g:ale_linters_explicit = 1
```

You can then run `:ALEFix` in a JavaScript or CSS file to run Prettier.

To have ALE run Prettier on save:

```vim
let g:ale_fix_on_save = 1
```

It's recommended to use a [config file](configuration.md), but you can also add options in your `.vimrc`:

```vim
let g:ale_javascript_prettier_options = '--single-quote --trailing-comma all'
```

## [coc-prettier](https://github.com/neoclide/coc-prettier)

Prettier extension for [coc.nvim](https://github.com/neoclide/coc.nvim) which requires neovim or vim8.1.
Install coc.nvim with your favorite plugin manager, such as [vim-plug](https://github.com/junegunn/vim-plug):

```vim
Plug 'neoclide/coc.nvim', {'branch': 'release'}
```

And install coc-prettier by command:

```vim
CocInstall coc-prettier
```

Setup `Prettier` command in your `init.vim` or `.vimrc`

```vim
command! -nargs=0 Prettier :call CocAction('runCommand', 'prettier.formatFile')
```

Update your `coc-settings.json` for languages that you want format on save.

```json
{
  "coc.preferences.formatOnSaveFiletypes": ["css", "markdown"]
}
```

[coc-prettier](https://github.com/neoclide/coc-prettier) have same configurations of [prettier-vscode](https://github.com/prettier/prettier-vscode), open `coc-settings.json` by `:CocConfig` to get autocompletion support.

## Running manually

If you want something really bare-bones, you can create a custom key binding. In this example, `gp` (mnemonic: "get pretty") is used to run prettier (with options) in the currently active buffer:

```vim
nnoremap gp :silent %!prettier --stdin-filepath %<CR>
```

Note that if there's a syntax error in your code, the whole buffer will be replaced with an error message. You'll need to press `u` to get your code back.

Another disadvantage of this approach is that the cursor position won't be preserved.


text:
The HTML5 Shiv enables use of HTML5 sectioning elements in legacy Internet Explorer and provides basic HTML5 styling for Internet Explorer 6-9, Safari 4.x (and iPhone 3.x), and Firefox 3.x.

### What do these files do?

#### `html5shiv.js`
*  This includes the basic `createElement()` shiv technique, along with monkeypatches for `document.createElement` and `document.createDocumentFragment` for IE6-8. It also applies [basic styling](https://github.com/aFarkas/html5shiv/blob/51da98dabd3c537891b7fe6114633fb10de52473/src/html5shiv.js#L216-220) for HTML5 elements for IE6-9, Safari 4.x and FF 3.x.

####`html5shiv-printshiv.js`
*  This includes all of the above, as well as a mechanism allowing HTML5 elements to be styled and contain children while being printed in IE 6-8.

### Who can I get mad at now?

HTML5 Shiv is maintained by [Alexander Farkas](https://github.com/aFarkas/), [Jonathan Neal](https://twitter.com/jon_neal) and [Paul Irish](https://twitter.com/paul_irish), with many contributions from [John-David Dalton](https://twitter.com/jdalton). It is also distributed with [Modernizr](http://modernizr.com/), and the two google code projects, [html5shiv](https://code.google.com/p/html5shiv/) and [html5shim](https://code.google.com/p/html5shim/), maintained by [Remy Sharp](https://twitter.com/rem).

If you have any issues in these implementations, you can report them here! :)

For the full story of HTML5 Shiv and all of the people involved in making it, read [The Story of the HTML5 Shiv](http://paulirish.com/2011/the-history-of-the-html5-shiv/).

## Installation

###Using [Bower](http://bower.io/)

`bower install html5shiv --save-dev`

This will clone the latest version of the HTML5 shiv into the `components` directory at the root of your project and also create or update the file `bower.json` which specifies your projects dependencies.

Include the HTML5 shiv at the top of your `<head>` in a conditional comment after any stylesheets.

```html
<!--[if lt IE 9]>
	<script src="components/html5shiv/html5shiv.js"></script>
<![endif]-->
```

###Manual installation

Download and extract the [latest zip package](https://github.com/aFarkas/html5shiv/archive/master.zip) from this repositiory and copy the two files `dist/html5shiv.js` and `dist/html5shiv-printshiv.js` into your project. Then include one of them into your `<head>` as above.

## HTML5 Shiv API

HTML5 Shiv works as a simple drop-in solution. In most cases there is no need to configure HTML5 Shiv or use methods provided by HTML5 Shiv.

### `html5.elements` option

The `elements` option is a space separated string or array, which describes the **full** list of the elements to shiv.

**Configuring `elements` before `html5shiv.js` is included.**

```js
//create a global html5 options object
window.html5 = {
  'elements': 'mark section customelement'
};
```
**Configuring `elements` after `html5shiv.js` is included.**

```js
//change the html5shiv options object
window.html5.elements = 'mark section customelement';
//and re-invoke the `shivDocument` method
html5.shivDocument(document);
```

### `html5.shivCSS`

If `shivCSS` is set to `true` HTML5 Shiv will add basic styles (mostly display: block) to sectioning elements (like section, article). In most cases a webpage author should include those basic styles in his normal stylesheet to ensure older browser support (i.e. Firefox 3.6) without JavaScript.

The `shivCSS` is true by default and can be set false, only before html5shiv.js is included:

```js
//create a global html5 options object
window.html5 = {
	'shivCSS': false
};
```

### `html5.shivMethods`

If the `shivMethods` option is set to `true` (by default) HTML5 Shiv will override `document.createElement`/`document.createDocumentFragment` in Internet Explorer 6-8 to allow dynamic DOM creation of HTML5 elements.

Known issue: If an element is created using the overridden `createElement` method this element returns a document fragment as its `parentNode`, but should be normally `null`. If a script relays on this behavior, `shivMethods`should be set to `false`.
Note: jQuery 1.7+ has implemented his own HTML5 DOM creation fix for Internet Explorer 6-8. If all your scripts (including Third party scripts) are using jQuery's manipulation and DOM creation methods, you might want to set this option to `false`.

**Configuring `shivMethods` before `html5shiv.js` is included.**

```js
//create a global html5 options object
window.html5 = {
	'shivMethods': false
};
```
**Configuring `elements` after `html5shiv.js` is included.**

```js
//change the html5shiv options object
window.html5.shivMethods = false;
```

### `html5.createElement( nodeName [, document] )`

The `html5.createElement` method creates a shived element, even if `shivMethods` is set to false.

```js
var container = html5.createElement('div');
//container is shived so we can add HTML5 elements using `innerHTML`
container.innerHTML = '<section>This is a section</section>';
```

### `html5.createDocumentFragment( [document] )`

The `html5.createDocumentFragment` method creates a shived document fragment, even if `shivMethods` is set to false.

```js
var fragment = html5.createDocumentFragment();
var container = document.createElement('div');
fragment.appendChild(container);
//fragment is shived so we can add HTML5 elements using `innerHTML`
container.innerHTML = '<section>This is a section</section>';
```

## HTML5 Shiv Known Issues and Limitations

- The `shivMethods` option (overriding `document.createElement`) and the `html5.createElement` method create elements, which are not disconnected and have a parentNode (see also issue #64)
- The cloneNode problem is currently not addressed by HTML5 Shiv. HTML5 elements can be dynamically created, but can't be cloned in all cases.
- The printshiv version of HTML5 Shiv has to alter the print styles and the whole DOM for printing. In case of complex websites and or a lot of print styles this might cause performance and/or styling issues. A possible solution could be the [htc-branch](https://github.com/aFarkas/html5shiv/tree/iepp-htc) of HTML5 Shiv, which uses another technique to implement print styles for Internet Explorer 6-8.

### What about the other HTML5 element projects?

- The original conception and community collaboration story of the project is described at [The History of the HTML5 Shiv](http://paulirish.com/2011/the-history-of-the-html5-shiv/).
- [IEPP](https://code.google.com/p/ie-print-protector), by Jon Neal, addressed the printing fault of the original `html5shiv`. It was merged into `html5shiv`.
- **Shimprove**, in April 2010, patched `cloneNode` and `createElement` was later merged into `html5shiv`
- **innerShiv**, introduced in August 2010 by JD Barlett, addressed dynamically adding new HTML5 elements into the DOM. [jQuery added support](http://blog.jquery.com/2011/11/03/jquery-1-7-released/) that made innerShiv redundant and `html5shiv` addressed the same issues as well, so the project was completed.
- The **html5shim** and **html5shiv** sites on Google Code are maintained by Remy Sharp and are identical distribution points of this `html5shiv` project.
- **Modernizr** is developed by the same people as `html5shiv` and can include the latest version in any custom builds created at modernizr.com
- This `html5shiv` repo now contains tests for all the edge cases pursued by the above libraries and has been extensively tested, both in development and production.

A [detailed changelog of html5shiv](https://github.com/aFarkas/html5shiv/wiki) is available.

### Why is it called a *shiv*?

The term **shiv** [originates](http://ejohn.org/blog/html5-shiv/) from [John Resig](https://github.com/jeresig), who was thought to have used the word for its slang meaning, *a sharp object used as a knife-like weapon*, intended for Internet Explorer. Truth be known, John probably intended to use the word [shim](http://en.wikipedia.org/wiki/Shim_(computing\)), which in computing means *an application compatibility workaround*. Rather than correct his mispelling, most developers familiar with Internet Explorer appreciated the visual imagery. And that, [kids](http://html5homi.es/), is [etymology](https://en.wikipedia.org/wiki/Etymology).


text:
package io.github.rcarlosdasilva.weixin.model.request.message.bean;

@SuppressWarnings("unused")
public class Text implements Message {

  private String content;

  public void setContent(String content) {
    this.content = content;
  }

}


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('ui-popup', 'Integration | Component | ui popup', {
  integration: true
});

test('it renders', function(assert) {
  this.render(hbs`
    {{#ui-popup content="Add users to your feed"}}

    {{/ui-popup}}
  `);

  assert.equal(this.$('div[data-content]').length, 1);
});


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from caffe2.python import scope
from caffe2.python.modeling.parameter_sharing import (
    ParameterSharing,
)
from caffe2.python.layer_test_util import LayersTestCase

class ParameterSharingTest(LayersTestCase):

    def test_layer_parameter_name(self):
        output_dims = 2
        with scope.NameScope('global_scope'):
            fc1_output = self.model.FC(
                self.model.input_feature_schema.float_features,
                output_dims
            )
            self.assertEquals(self.model.layers[-1].w, 'global_scope/fc/w')
            self.assertEquals(fc1_output(), 'global_scope/fc/output')

            with scope.NameScope('nested_scope'):
                fc2_output = self.model.FC(
                    fc1_output,
                    output_dims
                )
                self.assertEquals(self.model.layers[-1].w,
                                  'global_scope/nested_scope/fc/w')
                self.assertEquals(fc2_output(),
                                  'global_scope/nested_scope/fc/output')

                fc3_output = self.model.FC(
                    fc1_output,
                    output_dims
                )
                self.assertEquals(self.model.layers[-1].w,
                                  'global_scope/nested_scope/fc_auto_0/w')
                self.assertEquals(fc3_output(),
                                  'global_scope/nested_scope/fc_auto_0/output')

    def test_layer_shared_parameter_name_different_namescopes(self):
        output_dims = 2
        with scope.NameScope('global_scope'):
            with ParameterSharing({'scope_1': 'scope_0'}):
                with scope.NameScope('scope_0'):
                    fc1_output = self.model.FC(
                        self.model.input_feature_schema.float_features,
                        output_dims
                    )
                    self.assertEquals(self.model.layers[-1].w,
                                      'global_scope/scope_0/fc/w')
                    self.assertEquals(fc1_output(),
                                      'global_scope/scope_0/fc/output')

                with scope.NameScope('scope_1'):
                    fc2_output = self.model.FC(
                        self.model.input_feature_schema.float_features,
                        output_dims
                    )
                    self.assertEquals(self.model.layers[-1].w,
                                      'global_scope/scope_0/fc/w')
                    self.assertEquals(fc2_output(),
                                      'global_scope/scope_1/fc/output')

    def test_layer_shared_parameter_name_within_same_namescope(self):
        output_dims = 2
        with scope.NameScope('global_scope'):
            with ParameterSharing({'fc_auto_0': 'fc'}):
                self.model.FC(
                    self.model.input_feature_schema.float_features,
                    output_dims
                )
                self.assertEquals(self.model.layers[-1].w,
                                  'global_scope/fc/w')

                self.model.FC(
                    self.model.input_feature_schema.float_features,
                    output_dims
                )
                self.assertEquals(self.model.layers[-1].w,
                                  'global_scope/fc/w')

    def test_layer_shared_parameter_name_within_same_namescope_customized_name(self):
        output_dims = 2
        with scope.NameScope('global_scope'):
            with ParameterSharing({'new_fc': 'shared_fc'}):
                self.model.FC(
                    self.model.input_feature_schema.float_features,
                    output_dims,
                    name='shared_fc'
                )
                self.assertEquals(self.model.layers[-1].w,
                                  'global_scope/shared_fc/w')

                self.model.FC(
                    self.model.input_feature_schema.float_features,
                    output_dims,
                    name='new_fc'
                )
                self.assertEquals(self.model.layers[-1].w,
                                  'global_scope/shared_fc/w')

    def test_layer_shared_parameter_name_different_shapes(self):
        output_dims = 2
        with scope.NameScope('global_scope'):
            with ParameterSharing({'fc_auto_0': 'fc'}):
                self.model.FC(
                    self.model.input_feature_schema.float_features,
                    output_dims
                )
                self.assertEquals(self.model.layers[-1].w,
                                  'global_scope/fc/w')

                with self.assertRaisesRegexp(ValueError, 'Got inconsistent shapes .*'):
                    self.model.FC(
                        self.model.input_feature_schema.float_features,
                        output_dims + 1
                    )


text:
package com.ibm.dcs

import com.typesafe.config.ConfigFactory
import org.scalatest.{Matchers, WordSpec}

class EnvironmentSpec extends WordSpec with Matchers {

  "The Environment" should {
    "default to the first credentials in vcap_services" in {
      val conf = ConfigFactory.parseString(
        "vcap_services = { document-conversion: [{ credentials: { username: foo, password: bar } }] }")
      val env = new Environment(conf)
      env.getUsername should be("foo")
      env.getPassword should be("bar")
    }

    "use specified credentials in vcap_services" in {
      val conf = ConfigFactory.parseString(
        """vcap_services = { document-conversion: [
          |  { name: first, credentials: { username: foo1, password: bar1 } }
          |  { name: second, credentials: { username: foo2, password: bar2 } }
          |]}
          |dcs.vcap_credentials_name = second
        """.stripMargin)
      val env = new Environment(conf)
      env.getUsername should be("foo2")
      env.getPassword should be("bar2")
    }

    "allow manual specification of credentials" in {
      val confs = ConfigFactory.parseString(
        """vcap_services = { document-conversion: [
          |  { name: first, credentials: { username: badU1, password: badP1 } }
          |  { name: second, credentials: { username: badU2, password: badP2 } }
          |]}
          |dcs: {
          |  vcap_credentials_name = second
          |  username: foo
          |  password: bar
          |}
        """.stripMargin) :: ConfigFactory.parseString(
        """vcap_services = { document-conversion: [
          |  { name: first, credentials: { username: badU1, password: badP1 } }
          |  { name: second, credentials: { username: badU2, password: badP2 } }
          |]}
          |dcs: {
          |  vcap_credentials_name = missing
          |  username: foo
          |  password: bar
          |}
        """.stripMargin) :: Nil
      confs foreach { conf =>
        val env = new Environment(conf)
        env.getUsername should be("foo")
        env.getPassword should be("bar")
      }
    }

    "throw exceptions if no credentials are found" in {
      val conf = ConfigFactory.parseString(
        """vcap_services = { document-conversion: [
          |  { name: first, credentials: { username: badU1, password: badP1 } }
          |]}
          |dcs: {
          |  vcap_credentials_name = missing
          |}
        """.stripMargin)
      val env = new Environment(conf)
      an[IllegalStateException] should be thrownBy env.getUsername
      an[IllegalStateException] should be thrownBy env.getPassword
    }
  }
}


text:
class Feefo

  require Rails.root.join('app', 'helpers', 'application_helper')
  include ApplicationHelper
  include Rails.application.routes.url_helpers
  require 'csv'

  def self.generate_feed(start_date = nil, end_date = nil)

    start_date ||= Time.zone.now.beginning_of_day - 1.months
    end_date ||= Time.zone.now.beginning_of_day

    tmp_path = File.join(Rails.root, Spree::Config[:feefo_tmp_feed_location].to_s)
    end_path = File.join(Rails.root, 'public', Spree::Config[:feefo_public_feed_location].to_s)
    FileUtils.mkdir_p(tmp_path)
    FileUtils.mkdir_p(end_path)
    tmp_filepath = File.join(tmp_path, Spree::Config[:feefo_feed_name])
    end_filepath = File.join(end_path, Spree::Config[:feefo_feed_name])

    CSV.open(tmp_filepath, "w", {col_sep: "\t", encoding: "UTF-8"}) do |file|
      file << [
        'name',
        'email',
        'date',
        'description',
        'merchant identifier',
        'category',
        'feedback fate',
        'product search code',
        'order Ref',
        'product link',
        'customer Ref',
        'amount'
      ]

      logon = Spree::Config[:feefo_merchant_identifier]

       Spree::Shipment.where(state: "shipped", shipped_at: start_date..end_date).each do |shipment|
        sku = shipment.manifest.first.line_item.product.sku
        sku = shipment.manifest.first.line_item.product.variants.first.try(:sku) if sku.blank?

        file << [
          shipment.order.name,
          shipment.order.email,
          shipment.shipped_at.strftime('%Y-%m-%d'),
          shipment.manifest.first.line_item.product.name.strip,
          logon,
          shipment.manifest.first.line_item.product.taxons.order(:lft).first.try(:name).to_s,
          '',
          sku,
          shipment.order.number,
          Spree::Core::Engine.routes.url_helpers.product_url(shipment.manifest.first.line_item.product, host: Spree::Store.default.url),
          shipment.order.user ? shipment.order.user.id : '',
          shipment.order.total.to_f
        ] if shipment.present? && shipment.order.email.present?
      end

    end

    FileUtils.cp tmp_filepath, end_filepath
    puts end_filepath
  end
end


text:
let x, y = 1;
if (x !== undefined)
  throw new Error("Declaration1");
if (y !== 1)
  throw new Error("Declaration2");


text:
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [TZNotif showString:@"Here I am, nice notification for you"];
    [TZNotif showString:@"But I am not alone"];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
from setuptools import setup

url = "https://github.com/jic-dtool/dtool-create"
version = "0.23.4"
readme = open('README.rst').read()

setup(
    name="dtool-create",
    packages=["dtool_create"],
    package_data={"dtool_create": ["templates/*"]},
    version=version,
    description="Dtool plugin for creating datasets",
    long_description=readme,
    include_package_data=True,
    author="Tjelvar Olsson",
    author_email="tjelvar.olsson@gmail.com",
    url=url,
    install_requires=[
        "click",
        "dtoolcore>=3.6",
        "dtool_cli>=0.6.0",
        "dtool_symlink>=0.2.0",
        "dtool_http",
        "ruamel.yaml",
    ],
    entry_points={
        "dtool.cli": [
            "create=dtool_create.dataset:create",
            "name=dtool_create.dataset:name",
            "readme=dtool_create.dataset:readme",
            "add=dtool_create.dataset:add",
            "freeze=dtool_create.dataset:freeze",
            "copy=dtool_create.dataset:copy",
            "cp=dtool_create.dataset:cp",
            "publish=dtool_create.publish:publish",
        ],
    },
    download_url="{}/tarball/{}".format(url, version),
    license="MIT"
)