text:
"""Tests for warm_starting_util."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import numpy as np
import six

from tensorflow.python.estimator import warm_starting_util as ws_util
from tensorflow.python.feature_column import feature_column as fc
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.training import saver as saver_lib

ones = init_ops.ones_initializer
norms = init_ops.truncated_normal_initializer
rand = init_ops.random_uniform_initializer

class WarmStartingUtilTest(test.TestCase):

  def _write_vocab(self, string_values, file_name):
    vocab_file = os.path.join(self.get_temp_dir(), file_name)
    with open(vocab_file, "w") as f:
      f.write("\n".join(string_values))
    return vocab_file

  def _write_checkpoint(self, sess):
    sess.run(variables.global_variables_initializer())
    saver = saver_lib.Saver()
    ckpt_prefix = os.path.join(self.get_temp_dir(), "model")
    ckpt_state_name = "checkpoint"
    saver.save(
        sess, ckpt_prefix, global_step=0, latest_filename=ckpt_state_name)

  def _create_prev_run_var(self,
                           var_name,
                           shape=None,
                           initializer=None,
                           partitioner=None):
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        var = variable_scope.get_variable(
            var_name,
            shape=shape,
            initializer=initializer,
            partitioner=partitioner)
        self._write_checkpoint(sess)
        if partitioner:
          self.assertTrue(isinstance(var, variables.PartitionedVariable))
          var = var._get_variable_list()
        return var, sess.run(var)

  def _create_prev_run_multiple_vars(self,
                                     var_names,
                                     initializers,
                                     shapes=None,
                                     partitioners=None):
    if not shapes:
      shapes = [None] * len(var_names)
    if not partitioners:
      partitioners = [None] * len(var_names)
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        var_list = []
        for var_name, shape, initializer, partitioner in zip(
            var_names, shapes, initializers, partitioners):
          var_list.append(
              variable_scope.get_variable(
                  var_name,
                  shape=shape,
                  initializer=initializer,
                  partitioner=partitioner))
        self._write_checkpoint(sess)
        run_vars = []
        for var, partitioner in zip(var_list, partitioners):
          if partitioner:
            self.assertTrue(isinstance(var, variables.PartitionedVariable))
            run_vars.append(sess.run(var._get_variable_list()))
          else:
            run_vars.append(sess.run(var))
        return var_list, run_vars

  def _create_dummy_inputs(self):
    return {
        "sc_int": array_ops.sparse_placeholder(dtypes.int32),
        "sc_hash": array_ops.sparse_placeholder(dtypes.string),
        "sc_keys": array_ops.sparse_placeholder(dtypes.string),
        "sc_vocab": array_ops.sparse_placeholder(dtypes.string),
        "real": array_ops.placeholder(dtypes.float32)
    }

  def _create_linear_model(self, feature_cols, partitioner):
    cols_to_vars = {}
    with variable_scope.variable_scope("", partitioner=partitioner):
      # Create the variables.
      fc.linear_model(
          features=self._create_dummy_inputs(),
          feature_columns=feature_cols,
          units=1,
          cols_to_vars=cols_to_vars)
    # Return a dictionary mapping each column to its variable, dropping the
    # 'bias' key that's also filled.
    cols_to_vars.pop("bias")
    return cols_to_vars

  def _assert_cols_to_vars(self, cols_to_vars, cols_to_expected_values, sess):
    for col, expected_values in six.iteritems(cols_to_expected_values):
      for i, var in enumerate(cols_to_vars[col]):
        self.assertAllClose(expected_values[i], var.eval(sess))

  def testWarmStartVar(self):
    _, prev_val = self._create_prev_run_var(
        "fruit_weights", initializer=[[0.5], [1.], [1.5], [2.]])

    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        fruit_weights = variable_scope.get_variable(
            "fruit_weights", initializer=[[0.], [0.], [0.], [0.]])
        ws_util._warmstart_var(fruit_weights, self.get_temp_dir())
        sess.run(variables.global_variables_initializer())
        self.assertAllEqual(prev_val, fruit_weights.eval(sess))

  def testWarmStartVarPrevVarPartitioned(self):
    _, weights = self._create_prev_run_var(
        "fruit_weights",
        shape=[4, 1],
        initializer=[[0.5], [1.], [1.5], [2.]],
        partitioner=lambda shape, dtype: [2, 1])
    prev_val = np.concatenate([weights[0], weights[1]], axis=0)

    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        fruit_weights = variable_scope.get_variable(
            "fruit_weights", initializer=[[0.], [0.], [0.], [0.]])
        ws_util._warmstart_var(fruit_weights, self.get_temp_dir())
        sess.run(variables.global_variables_initializer())
        self.assertAllEqual(prev_val, fruit_weights.eval(sess))

  def testWarmStartVarCurrentVarPartitioned(self):
    _, prev_val = self._create_prev_run_var(
        "fruit_weights", initializer=[[0.5], [1.], [1.5], [2.]])

    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        fruit_weights = variable_scope.get_variable(
            "fruit_weights",
            shape=[4, 1],
            initializer=[[0.], [0.], [0.], [0.]],
            partitioner=lambda shape, dtype: [2, 1])
        self.assertTrue(
            isinstance(fruit_weights, variables.PartitionedVariable))
        ws_util._warmstart_var(fruit_weights, self.get_temp_dir())
        sess.run(variables.global_variables_initializer())
        fruit_weights = fruit_weights._get_variable_list()
        new_val = np.concatenate(
            [fruit_weights[0].eval(sess), fruit_weights[1].eval(sess)], axis=0)
        self.assertAllEqual(prev_val, new_val)

  def testWarmStartVarBothVarsPartitioned(self):
    _, weights = self._create_prev_run_var(
        "old_scope/fruit_weights",
        shape=[4, 1],
        initializer=[[0.5], [1.], [1.5], [2.]],
        partitioner=lambda shape, dtype: [2, 1])
    prev_val = np.concatenate([weights[0], weights[1]], axis=0)
    # New session and new graph.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        fruit_weights = variable_scope.get_variable(
            "new_scope/fruit_weights",
            shape=[4, 1],
            initializer=[[0.], [0.], [0.], [0.]],
            partitioner=lambda shape, dtype: [2, 1])
        self.assertTrue(
            isinstance(fruit_weights, variables.PartitionedVariable))
        ws_util._warmstart_var(
            fruit_weights,
            self.get_temp_dir(),
            prev_tensor_name="old_scope/fruit_weights")
        sess.run(variables.global_variables_initializer())
        fruit_weights = fruit_weights._get_variable_list()
        new_val = np.concatenate(
            [fruit_weights[0].eval(sess), fruit_weights[1].eval(sess)], axis=0)
        self.assertAllEqual(prev_val, new_val)

  def testWarmStartVarMultipleVars(self):
    _, prev_vals = self._create_prev_run_multiple_vars(
        var_names=["fruit_weights", "other_weights"],
        initializers=[[[0.5], [1.], [1.5], [2.]], [[.05], [.1], [.15], [.2]]])

    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        fruit_weights = variable_scope.get_variable(
            "fruit_weights", initializer=[[0.], [0.], [0.], [0.]])
        other_weights = variable_scope.get_variable(
            "other_weights", initializer=[[0.], [0.], [0.], [0.]])
        ws_util._warmstart_var([fruit_weights, other_weights],
                               self.get_temp_dir())
        sess.run(variables.global_variables_initializer())
        self.assertAllEqual(prev_vals[0], fruit_weights.eval(sess))
        self.assertAllEqual(prev_vals[1], other_weights.eval(sess))

  def testWarmStartVarMultipleVarsBothPartitioned(self):
    _, prev_vals = self._create_prev_run_multiple_vars(
        var_names=["fruit_weights", "other_weights"],
        shapes=[[4, 1], [4, 1]],
        initializers=[[[0.5], [1.], [1.5], [2.]], [[.05], [.1], [.15], [.2]]],
        partitioners=[lambda shape, dtype: [2, 1], lambda shape, dtype: [2, 1]])

    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        fruit_weights = variable_scope.get_variable(
            "fruit_weights",
            shape=[4, 1],
            initializer=[[0.], [0.], [0.], [0.]],
            partitioner=lambda shape, dtype: [2, 1])
        other_weights = variable_scope.get_variable(
            "other_weights",
            shape=[4, 1],
            initializer=[[0.], [0.], [0.], [0.]],
            partitioner=lambda shape, dtype: [2, 1])
        ws_util._warmstart_var([fruit_weights, other_weights],
                               self.get_temp_dir())
        sess.run(variables.global_variables_initializer())
        fruit_weights = fruit_weights._get_variable_list()
        new_fruit_weights_val = np.concatenate(
            [fruit_weights[0].eval(sess), fruit_weights[1].eval(sess)], axis=0)
        other_weights = other_weights._get_variable_list()
        new_other_weights_val = np.concatenate(
            [other_weights[0].eval(sess), other_weights[1].eval(sess)], axis=0)
        self.assertAllEqual(
            np.concatenate(prev_vals[0], axis=0), new_fruit_weights_val)
        self.assertAllEqual(
            np.concatenate(prev_vals[1], axis=0), new_other_weights_val)

  def testWarmStartVarMultipleVarsMixOfPartitions(self):
    # First is not partitioned, but the second two are.
    _, prev_vals = self._create_prev_run_multiple_vars(
        var_names=["fruit_weights", "other_weights", "veggie_weights"],
        shapes=[None, [4, 1], [4, 1]],
        initializers=[[[0.5], [1.], [1.5], [2.]], [[.05], [.1], [.15], [.2]],
                      [[5.], [10.], [15.], [20.]]],
        partitioners=[
            None, lambda shape, dtype: [2, 1], lambda shape, dtype: [2, 1]
        ])

    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        fruit_weights = variable_scope.get_variable(
            "fruit_weights", initializer=[[0.], [0.], [0.], [0.]])
        other_weights = variable_scope.get_variable(
            "other_weights",
            shape=[4, 1],
            initializer=[[0.], [0.], [0.], [0.]],
            partitioner=lambda shape, dtype: [2, 1])
        veggie_weights = variable_scope.get_variable(
            "veggie_weights",
            shape=[4, 1],
            initializer=[[0.], [0.], [0.], [0.]],
            partitioner=lambda shape, dtype: [2, 1])
        # Flatten one of the partitioned variables.
        ws_util._warmstart_var([fruit_weights, other_weights] +
                               veggie_weights._get_variable_list(),
                               self.get_temp_dir())
        sess.run(variables.global_variables_initializer())
        veggie_weights = veggie_weights._get_variable_list()
        new_veggie_weights_val = np.concatenate(
            [veggie_weights[0].eval(sess), veggie_weights[1].eval(sess)],
            axis=0)
        other_weights = other_weights._get_variable_list()
        new_other_weights_val = np.concatenate(
            [other_weights[0].eval(sess), other_weights[1].eval(sess)], axis=0)
        self.assertAllEqual(prev_vals[0], fruit_weights.eval(sess))
        self.assertAllEqual(
            np.concatenate(prev_vals[1], axis=0), new_other_weights_val)
        self.assertAllEqual(
            np.concatenate(prev_vals[2], axis=0), new_veggie_weights_val)

  def testWarmStartVarWithVocab(self):
    prev_vocab_path = self._write_vocab(["apple", "banana", "guava", "orange"],
                                        "old_vocab")
    _, _ = self._create_prev_run_var(
        "fruit_weights", initializer=[[0.5], [1.], [1.5], [2.]])

    # New vocab with elements in reverse order and one new element.
    new_vocab_path = self._write_vocab(
        ["orange", "guava", "banana", "apple", "raspberry"], "new_vocab")
    # New session and new graph.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        fruit_weights = variable_scope.get_variable(
            "fruit_weights", initializer=[[0.], [0.], [0.], [0.], [0.]])
        ws_util._warmstart_var_with_vocab(fruit_weights, new_vocab_path, 5,
                                          self.get_temp_dir(), prev_vocab_path)
        sess.run(variables.global_variables_initializer())
        self.assertAllEqual([[2.], [1.5], [1.], [0.5], [0.]],
                            fruit_weights.eval(sess))

  def testWarmStartVarWithVocabPrevVarPartitioned(self):
    prev_vocab_path = self._write_vocab(["apple", "banana", "guava", "orange"],
                                        "old_vocab")
    _, _ = self._create_prev_run_var(
        "fruit_weights",
        shape=[4, 1],
        initializer=[[0.5], [1.], [1.5], [2.]],
        partitioner=lambda shape, dtype: [2, 1])

    # New vocab with elements in reverse order and one new element.
    new_vocab_path = self._write_vocab(
        ["orange", "guava", "banana", "apple", "raspberry"], "new_vocab")
    # New session and new graph.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        fruit_weights = variable_scope.get_variable(
            "fruit_weights", initializer=[[0.], [0.], [0.], [0.], [0.]])
        ws_util._warmstart_var_with_vocab(fruit_weights, new_vocab_path, 5,
                                          self.get_temp_dir(), prev_vocab_path)
        sess.run(variables.global_variables_initializer())
        self.assertAllEqual([[2.], [1.5], [1.], [0.5], [0.]],
                            fruit_weights.eval(sess))

  def testWarmStartVarWithVocabCurrentVarPartitioned(self):
    prev_vocab_path = self._write_vocab(["apple", "banana", "guava", "orange"],
                                        "old_vocab")
    _, _ = self._create_prev_run_var(
        "fruit_weights", initializer=[[0.5], [1.], [1.5], [2.]])

    # New vocab with elements in reverse order and one new element.
    new_vocab_path = self._write_vocab(
        ["orange", "guava", "banana", "apple", "raspberry"], "new_vocab")
    # New session and new graph.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        fruit_weights = variable_scope.get_variable(
            "fruit_weights",
            shape=[6, 1],
            initializer=[[0.], [0.], [0.], [0.], [0.], [0.]],
            partitioner=lambda shape, dtype: [2, 1])
        ws_util._warmstart_var_with_vocab(
            fruit_weights,
            new_vocab_path,
            5,
            self.get_temp_dir(),
            prev_vocab_path,
            current_oov_buckets=1)
        sess.run(variables.global_variables_initializer())
        self.assertTrue(
            isinstance(fruit_weights, variables.PartitionedVariable))
        fruit_weights_vars = fruit_weights._get_variable_list()
        self.assertAllEqual([[2.], [1.5], [1.]],
                            fruit_weights_vars[0].eval(sess))
        self.assertAllEqual([[0.5], [0.], [0.]],
                            fruit_weights_vars[1].eval(sess))

  def testWarmStartVarWithVocabBothVarsPartitioned(self):
    prev_vocab_path = self._write_vocab(["apple", "banana", "guava", "orange"],
                                        "old_vocab")
    _, _ = self._create_prev_run_var(
        "fruit_weights",
        shape=[4, 1],
        initializer=[[0.5], [1.], [1.5], [2.]],
        partitioner=lambda shape, dtype: [2, 1])

    # New vocab with elements in reverse order and two new elements.
    new_vocab_path = self._write_vocab(
        ["orange", "guava", "banana", "apple", "raspberry",
         "blueberry"], "new_vocab")
    # New session and new graph.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        fruit_weights = variable_scope.get_variable(
            "fruit_weights",
            shape=[6, 1],
            initializer=[[0.], [0.], [0.], [0.], [0.], [0.]],
            partitioner=lambda shape, dtype: [2, 1])
        ws_util._warmstart_var_with_vocab(fruit_weights, new_vocab_path, 6,
                                          self.get_temp_dir(), prev_vocab_path)
        sess.run(variables.global_variables_initializer())
        self.assertTrue(
            isinstance(fruit_weights, variables.PartitionedVariable))
        fruit_weights_vars = fruit_weights._get_variable_list()
        self.assertAllEqual([[2.], [1.5], [1.]],
                            fruit_weights_vars[0].eval(sess))
        self.assertAllEqual([[0.5], [0.], [0.]],
                            fruit_weights_vars[1].eval(sess))

  def testWarmStartInputLayer_SparseColumnIntegerized(self):
    # Create feature column.
    sc_int = fc.categorical_column_with_identity("sc_int", num_buckets=10)

    # Save checkpoint from which to warm-start.
    _, prev_int_val = self._create_prev_run_var(
        "linear_model/sc_int/weights", shape=[10, 1], initializer=ones())
    # Verify we initialized the values correctly.
    self.assertAllEqual(np.ones([10, 1]), prev_int_val)

    partitioner = lambda shape, dtype: [1] * len(shape)
    # New graph, new session WITHOUT warmstarting.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        cols_to_vars = self._create_linear_model([sc_int], partitioner)
        sess.run(variables.global_variables_initializer())
        # Without warmstarting, the weights should be initialized using default
        # initializer (which is init_ops.zeros_initializer).
        self._assert_cols_to_vars(cols_to_vars, {sc_int: [np.zeros([10, 1])]},
                                  sess)

    # New graph, new session with warmstarting.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        cols_to_vars = self._create_linear_model([sc_int], partitioner)
        ws_util._warmstart_input_layer(cols_to_vars,
                                       ws_util._WarmStartSettings(
                                           self.get_temp_dir()))
        sess.run(variables.global_variables_initializer())
        # Verify weights were correctly warmstarted.
        self._assert_cols_to_vars(cols_to_vars, {sc_int: [prev_int_val]}, sess)

  def testWarmStartInputLayer_SparseColumnHashed(self):
    # Create feature column.
    sc_hash = fc.categorical_column_with_hash_bucket(
        "sc_hash", hash_bucket_size=15)

    # Save checkpoint from which to warm-start.
    _, prev_hash_val = self._create_prev_run_var(
        "linear_model/sc_hash/weights", shape=[15, 1], initializer=norms())

    partitioner = lambda shape, dtype: [1] * len(shape)
    # New graph, new session WITHOUT warmstarting.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        cols_to_vars = self._create_linear_model([sc_hash], partitioner)
        sess.run(variables.global_variables_initializer())
        # Without warmstarting, the weights should be initialized using default
        # initializer (which is init_ops.zeros_initializer).
        self._assert_cols_to_vars(cols_to_vars, {sc_hash: [np.zeros([15, 1])]},
                                  sess)

    # New graph, new session with warmstarting.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        cols_to_vars = self._create_linear_model([sc_hash], partitioner)
        ws_util._warmstart_input_layer(cols_to_vars,
                                       ws_util._WarmStartSettings(
                                           self.get_temp_dir()))
        sess.run(variables.global_variables_initializer())
        # Verify weights were correctly warmstarted.
        self._assert_cols_to_vars(cols_to_vars, {sc_hash: [prev_hash_val]},
                                  sess)

  def testWarmStartInputLayer_SparseColumnVocabulary(self):
    # Create vocab for sparse column "sc_vocab".
    vocab_path = self._write_vocab(["apple", "banana", "guava", "orange"],
                                   "vocab")
    # Create feature column.
    sc_vocab = fc.categorical_column_with_vocabulary_file(
        "sc_vocab", vocabulary_file=vocab_path, vocabulary_size=4)

    # Save checkpoint from which to warm-start.
    _, prev_vocab_val = self._create_prev_run_var(
        "linear_model/sc_vocab/weights", shape=[4, 1], initializer=ones())

    partitioner = lambda shape, dtype: [1] * len(shape)
    # New graph, new session WITHOUT warmstarting.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        cols_to_vars = self._create_linear_model([sc_vocab], partitioner)
        sess.run(variables.global_variables_initializer())
        # Without warmstarting, the weights should be initialized using default
        # initializer (which is init_ops.zeros_initializer).
        self._assert_cols_to_vars(cols_to_vars, {sc_vocab: [np.zeros([4, 1])]},
                                  sess)

    # New graph, new session with warmstarting.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        cols_to_vars = self._create_linear_model([sc_vocab], partitioner)
        # Since old vocab is not explicitly set in WarmStartSettings, the old
        # vocab is assumed to be same as new vocab.
        ws_util._warmstart_input_layer(cols_to_vars,
                                       ws_util._WarmStartSettings(
                                           self.get_temp_dir()))
        sess.run(variables.global_variables_initializer())
        # Verify weights were correctly warmstarted.
        self._assert_cols_to_vars(cols_to_vars, {sc_vocab: [prev_vocab_val]},
                                  sess)

  def testWarmStartInputLayer_BucketizedColumn(self):
    # Create feature column.
    real = fc.numeric_column("real")
    real_bucket = fc.bucketized_column(real, boundaries=[0., 1., 2., 3.])

    # Save checkpoint from which to warm-start.
    _, prev_bucket_val = self._create_prev_run_var(
        "linear_model/real_bucketized/weights",
        shape=[5, 1],
        initializer=norms())

    partitioner = lambda shape, dtype: [1] * len(shape)
    # New graph, new session WITHOUT warmstarting.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        cols_to_vars = self._create_linear_model([real_bucket], partitioner)
        sess.run(variables.global_variables_initializer())
        # Without warmstarting, the weights should be initialized using default
        # initializer (which is init_ops.zeros_initializer).
        self._assert_cols_to_vars(cols_to_vars,
                                  {real_bucket: [np.zeros([5, 1])]}, sess)

    # New graph, new session with warmstarting.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        cols_to_vars = self._create_linear_model([real_bucket], partitioner)
        ws_util._warmstart_input_layer(cols_to_vars,
                                       ws_util._WarmStartSettings(
                                           self.get_temp_dir()))
        sess.run(variables.global_variables_initializer())
        # Verify weights were correctly warmstarted.
        self._assert_cols_to_vars(cols_to_vars,
                                  {real_bucket: [prev_bucket_val]}, sess)

  def testWarmStartInputLayer_MultipleCols(self):
    # Create vocab for sparse column "sc_vocab".
    vocab_path = self._write_vocab(["apple", "banana", "guava", "orange"],
                                   "vocab")

    # Create feature columns.
    sc_int = fc.categorical_column_with_identity("sc_int", num_buckets=10)
    sc_hash = fc.categorical_column_with_hash_bucket(
        "sc_hash", hash_bucket_size=15)
    sc_keys = fc.categorical_column_with_vocabulary_list(
        "sc_keys", vocabulary_list=["a", "b", "c", "e"])
    sc_vocab = fc.categorical_column_with_vocabulary_file(
        "sc_vocab", vocabulary_file=vocab_path, vocabulary_size=4)
    real = fc.numeric_column("real")
    real_bucket = fc.bucketized_column(real, boundaries=[0., 1., 2., 3.])
    cross = fc.crossed_column([sc_keys, sc_vocab], hash_bucket_size=20)
    all_linear_cols = [sc_int, sc_hash, sc_keys, sc_vocab, real_bucket, cross]

    # Save checkpoint from which to warm-start.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        sc_int_weights = variable_scope.get_variable(
            "linear_model/sc_int/weights", shape=[10, 1], initializer=ones())
        sc_hash_weights = variable_scope.get_variable(
            "linear_model/sc_hash/weights", shape=[15, 1], initializer=norms())
        sc_keys_weights = variable_scope.get_variable(
            "linear_model/sc_keys/weights", shape=[4, 1], initializer=rand())
        sc_vocab_weights = variable_scope.get_variable(
            "linear_model/sc_vocab/weights", shape=[4, 1], initializer=ones())
        real_bucket_weights = variable_scope.get_variable(
            "linear_model/real_bucketized/weights",
            shape=[5, 1],
            initializer=norms())
        cross_weights = variable_scope.get_variable(
            "linear_model/sc_keys_X_sc_vocab/weights",
            shape=[20, 1],
            initializer=rand())
        self._write_checkpoint(sess)
        (prev_int_val, prev_hash_val, prev_keys_val, prev_vocab_val,
         prev_bucket_val, prev_cross_val) = sess.run([
             sc_int_weights, sc_hash_weights, sc_keys_weights, sc_vocab_weights,
             real_bucket_weights, cross_weights
         ])
        # Verify we initialized the values correctly.
        self.assertAllEqual(np.ones([10, 1]), prev_int_val)

    partitioner = lambda shape, dtype: [1] * len(shape)
    # New graph, new session WITHOUT warmstarting.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        cols_to_vars = self._create_linear_model(all_linear_cols, partitioner)
        sess.run(variables.global_variables_initializer())
        # Without warmstarting, all weights should be initialized using default
        # initializer (which is init_ops.zeros_initializer).
        self._assert_cols_to_vars(cols_to_vars, {
            sc_int: [np.zeros([10, 1])],
            sc_hash: [np.zeros([15, 1])],
            sc_keys: [np.zeros([4, 1])],
            sc_vocab: [np.zeros([4, 1])],
            real_bucket: [np.zeros([5, 1])],
            cross: [np.zeros([20, 1])],
        }, sess)

    # New graph, new session with warmstarting.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        cols_to_vars = self._create_linear_model(all_linear_cols, partitioner)
        ws_util._warmstart_input_layer(cols_to_vars,
                                       ws_util._WarmStartSettings(
                                           self.get_temp_dir()))
        sess.run(variables.global_variables_initializer())
        # Verify weights were correctly warmstarted.
        self._assert_cols_to_vars(cols_to_vars, {
            sc_int: [prev_int_val],
            sc_hash: [prev_hash_val],
            sc_keys: [prev_keys_val],
            sc_vocab: [prev_vocab_val],
            real_bucket: [prev_bucket_val],
            cross: [prev_cross_val],
        }, sess)

  def testWarmStartInputLayerMoreSettings(self):
    # Create old and new vocabs for sparse column "sc_vocab".
    prev_vocab_path = self._write_vocab(["apple", "banana", "guava", "orange"],
                                        "old_vocab")
    new_vocab_path = self._write_vocab(
        ["orange", "guava", "banana", "apple", "raspberry",
         "blueberry"], "new_vocab")
    # Create feature columns.
    sc_hash = fc.categorical_column_with_hash_bucket(
        "sc_hash", hash_bucket_size=15)
    sc_keys = fc.categorical_column_with_vocabulary_list(
        "sc_keys", vocabulary_list=["a", "b", "c", "e"])
    sc_vocab = fc.categorical_column_with_vocabulary_file(
        "sc_vocab", vocabulary_file=new_vocab_path, vocabulary_size=6)
    all_linear_cols = [sc_hash, sc_keys, sc_vocab]

    # Save checkpoint from which to warm-start.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        _ = variable_scope.get_variable(
            "linear_model/sc_hash/weights", shape=[15, 1], initializer=norms())
        sc_keys_weights = variable_scope.get_variable(
            "some_other_name", shape=[4, 1], initializer=rand())
        _ = variable_scope.get_variable(
            "linear_model/sc_vocab/weights",
            initializer=[[0.5], [1.], [2.], [3.]])
        self._write_checkpoint(sess)
        prev_keys_val = sess.run(sc_keys_weights)

    def _partitioner(shape, dtype):  # pylint:disable=unused-argument
      # Partition each var into 2 equal slices.
      partitions = [1] * len(shape)
      partitions[0] = min(2, shape[0].value)
      return partitions

    # New graph, new session with warmstarting.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        cols_to_vars = self._create_linear_model(all_linear_cols, _partitioner)
        ws_settings = ws_util._WarmStartSettings(
            self.get_temp_dir(),
            col_to_prev_vocab={sc_vocab: prev_vocab_path},
            col_to_prev_tensor={sc_keys: "some_other_name"},
            exclude_columns=[sc_hash])
        ws_util._warmstart_input_layer(cols_to_vars, ws_settings)
        sess.run(variables.global_variables_initializer())
        # Verify weights were correctly warmstarted.  Var corresponding to
        # sc_hash should not be warm-started.  Var corresponding to sc_vocab
        # should be correctly warmstarted after vocab remapping.
        self._assert_cols_to_vars(cols_to_vars, {
            sc_keys:
                np.split(prev_keys_val, 2),
            sc_hash: [np.zeros([8, 1]), np.zeros([7, 1])],
            sc_vocab: [
                np.array([[3.], [2.], [1.]]),
                np.array([[0.5], [0.], [0.]])
            ]
        }, sess)

  def testWarmStartInputLayerEmbeddingColumn(self):
    # Create old and new vocabs for embedding column "sc_vocab".
    prev_vocab_path = self._write_vocab(["apple", "banana", "guava", "orange"],
                                        "old_vocab")
    new_vocab_path = self._write_vocab(
        ["orange", "guava", "banana", "apple", "raspberry", "blueberry"],
        "new_vocab")

    # Save checkpoint from which to warm-start.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        _ = variable_scope.get_variable(
            "input_layer/sc_vocab_embedding/embedding_weights",
            initializer=[[0.5, 0.4], [1., 1.1], [2., 2.2], [3., 3.3]])
        self._write_checkpoint(sess)

    def _partitioner(shape, dtype):  # pylint:disable=unused-argument
      # Partition each var into 2 equal slices.
      partitions = [1] * len(shape)
      partitions[0] = min(2, shape[0].value)
      return partitions

    # Create feature columns.
    sc_vocab = fc.categorical_column_with_vocabulary_file(
        "sc_vocab", vocabulary_file=new_vocab_path, vocabulary_size=6)
    emb_vocab = fc.embedding_column(
        categorical_column=sc_vocab,
        dimension=2,
        # Can't use constant_initializer with load_and_remap.  In practice,
        # use a truncated normal initializer.
        initializer=init_ops.random_uniform_initializer(
            minval=0.42, maxval=0.42))
    all_deep_cols = [emb_vocab]
    # New graph, new session with warmstarting.
    with ops.Graph().as_default() as g:
      with self.test_session(graph=g) as sess:
        cols_to_vars = {}
        with variable_scope.variable_scope("", partitioner=_partitioner):
          # Create the variables.
          fc.input_layer(
              features=self._create_dummy_inputs(),
              feature_columns=all_deep_cols,
              cols_to_vars=cols_to_vars)
        ws_settings = ws_util._WarmStartSettings(
            self.get_temp_dir(), col_to_prev_vocab={
                emb_vocab: prev_vocab_path
            })
        ws_util._warmstart_input_layer(cols_to_vars, ws_settings)
        sess.run(variables.global_variables_initializer())
        # Verify weights were correctly warmstarted. Var corresponding to
        # emb_vocab should be correctly warmstarted after vocab remapping.
        # Missing values are filled in with the EmbeddingColumn's initializer.
        self._assert_cols_to_vars(
            cols_to_vars, {
                emb_vocab: [
                    np.array([[3., 3.3], [2., 2.2], [1., 1.1]]),
                    np.array([[0.5, 0.4], [0.42, 0.42], [0.42, 0.42]])
                ]
            }, sess)

  def testErrorConditions(self):
    self.assertRaises(ValueError, ws_util._WarmStartSettings, None)
    x = variable_scope.get_variable(
        "x",
        shape=[4, 1],
        initializer=ones(),
        partitioner=lambda shape, dtype: [2, 1])

    # List of PartitionedVariable is invalid type when warmstarting with vocab.
    self.assertRaises(TypeError, ws_util._warmstart_var_with_vocab, [x], "/tmp",
                      5, "/tmp", "/tmp")
    # Keys of type other than FeatureColumn.
    self.assertRaises(TypeError, ws_util._warmstart_input_layer,
                      {"StringType": x}, ws_util._WarmStartSettings("/tmp"))

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


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace libtcodWrapper
{
    /// <summary>
    /// Generate random names using sylable files
    /// </summary>
    public static class TCODNameGenerator
    {
        // We never clean this up, but since it has global scope, that is OK.
        private static TCODRandom m_random;

        /// <summary>
        /// TCODNameGenerator, and it's unmanaged cousin, both have global scope
        /// </summary>
        static TCODNameGenerator()
        {
            m_random = new TCODRandom();
        }

        /// <summary>
        /// Load a sylable file into the name generator.
        /// May be called more that once.
        /// </summary>
        /// <param name="filename">Relative or absolute path to file.</param>
        public static void LoadSyllableFile(string filename)
        {
            TCOD_namegen_parse(filename, m_random.m_instance);
        }

        /// <summary>
        /// Throw out all parser data structures.
        /// LoadSyllableFile will need to be called again before using again
        /// </summary>
        public static void Reset()
        {
            TCOD_namegen_destroy();
        }

        /// <summary>
        /// Generate a random string based upon a type
        /// </summary>
        /// <param name="type">Type of string, such as "celtic female"</param>
        /// <returns></returns>
        public static string Generate(string type)
        {
            return Marshal.PtrToStringAnsi(TCOD_namegen_generate(type, false));
        }

        /// <summary>
        /// Generate a custom string based on internal string rules
        /// </summary>
        /// <param name="type">Type of string, such as "celtic female"</param>
        /// <param name="rule">Rules to follow, see libtcod documentation for more details</param>
        /// <returns></returns>
        public static string GenerateCustom(string type, string rule)
        {
            return Marshal.PtrToStringAnsi(TCOD_namegen_generate_custom(type, rule, false));
        }

        /// <summary>
        /// Generate a list of available set names.
        /// </summary>
        /// <returns>List of available set names</returns>
        public static List<string> GetSet()
        {
            List<string> returnList = new List<string>();
            IntPtr tcodStringList = TCOD_namegen_get_sets();

            int listSize = TCOD_list_size(tcodStringList);
            for(int i = 0 ; i < listSize ; ++i)
            {
                string str = Marshal.PtrToStringAnsi(TCOD_list_get(tcodStringList, i));
                returnList.Add(str);
            }

            TCOD_list_delete(tcodStringList);
            return returnList;
        }

        #region DllImport
        [DllImport(DLLName.name)]
        private extern static void TCOD_namegen_parse([MarshalAs(UnmanagedType.LPStr)]string filename, IntPtr random);

        [DllImport(DLLName.name)]
        private extern static IntPtr TCOD_namegen_generate([MarshalAs(UnmanagedType.LPStr)]string name, bool allocate);

        [DllImport(DLLName.name)]
        private extern static IntPtr TCOD_namegen_generate_custom(string name, string rule, bool allocate);

        [DllImport(DLLName.name)]
        private extern static void TCOD_namegen_destroy();

        [DllImport(DLLName.name)]
        private extern static IntPtr TCOD_namegen_get_sets();

        [DllImport(DLLName.name)]
        private extern static IntPtr TCOD_list_get(IntPtr l, int idx);

        [DllImport(DLLName.name)]
        private extern static int TCOD_list_size(IntPtr l);

        [DllImport(DLLName.name)]
        private extern static void TCOD_list_delete(IntPtr l);

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by kevinhuron on 09/06/2016.
 */
angular.module('AdminUsersCtrl', ['AdminService']).controller('AdminUsersController', function($scope,$route, Admin,$routeParams, cfpLoadingBar) {
    Admin.get().then(function(users){
        cfpLoadingBar.start();
        var Allusers = users.data.users;
        $scope.Allusers = Allusers;
        cfpLoadingBar.complete();
    });

    $scope.EditUser = {};
    console.log($routeParams.mailUser);
    if ($routeParams.mailUser) {
        Admin.getInfoByMail($routeParams.mailUser).then(function(data){
            $scope.EditUser.firstname = data.data.theuser.local.lastname;
            $scope.EditUser.lastname = data.data.theuser.local.firstname;
            $scope.EditUser.mail = data.data.theuser.local.mail;
            if (data.data.theuser.local.accessLvl == "admin") {
                $scope.EditUser.role = 'admin';
            } else {
                $scope.EditUser.role = 'abonne';
            }

        });
    } else {

    }
    var userData;
    $scope.update = function () {
        cfpLoadingBar.start();
        /** ****** **/
        $scope.firstnameRequired = '';
        $scope.lastnameRequired = '';
        $scope.mailRequired = '';
        $scope.passwordRequired = '';
        $scope.confirmPasswordRequired = '';
        $scope.updateFailed = '';
        $scope.updateSuccess ='';
        /** ****** **/
        userData = {"firstname":$scope.EditUser.firstname, "lastname":$scope.EditUser.lastname, "mail":$scope.EditUser.mail, "password":$scope.EditUser.confirmpassword, "accessLvl":$scope.EditUser.role};
        Admin.update(userData);
        $route.reload();
        /** ****** **/
        cfpLoadingBar.complete();
    }
});


text:
.. blogpost::
    :title: How to fix: HttpHostx64.exe has stopped working
    :keywords: Visual Studio, VsHub, HttpHostx64.exe
    :date: 2016-12-08
    :categories: installation

    If you get the message
    *'Microsoft.VsHub.Server.HttpHostx64.exe has stopped working'*,
    you should read:
    `How to fix: HttpHostx64.exe has stopped working <https://thomas-barthelemy.github.io/2015/05/01/visual-studio-vshub/>`_.


text:
module.exports = function (config) {
    'use strict';

    config.set({
        // base path, that will be used to resolve files and exclude
        basePath: '',

        frameworks: [
            'mocha'
        ],

        // list of files / patterns to load in the browser
        files: [
            'bower_components/chai/chai.js',
            'matches.js',
            'test/*.js'
        ],

        // use dots reporter, as travis terminal does not support escaping sequences
        // possible values: 'dots', 'progress', 'junit', 'teamcity'
        // CLI --reporters progress
        reporters: ['dots'],

        // enable / disable watching file and executing tests whenever any file changes
        // CLI --auto-watch --no-auto-watch
        autoWatch: true,

        // start these browsers
        // CLI --browsers Chrome,Firefox,Safari
        browsers: [
            'Chrome',
            'Firefox'
        ],

        // If browser does not capture in given timeout [ms], kill it
        // CLI --capture-timeout 5000
        captureTimeout: 20000,

        // Auto run tests on start (when browsers are captured) and exit
        // CLI --single-run --no-single-run
        singleRun: false,

        plugins: [
            'karma-mocha',
            'karma-requirejs',
            'karma-chrome-launcher',
            'karma-firefox-launcher',
            'karma-ie-launcher',
            'karma-safari-launcher'
        ]
    });
};


text:
topic: sample
languages:
- cpp
- cppcx
products:
- windows
- windows-uwp
---

<!---
  category: Holographic
  samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=824113
--->

# Holographic face tracking sample

Shows how to acquire video frames from the photo/video (PV) camera and use the FaceAnalysis
API to determine if there are any faces in front of the HoloLens. We display a cube on top of the
detected face and a video stream inside the user's view.

> **Note:** This sample is part of a large collection of UWP feature samples.
> If you are unfamiliar with Git and GitHub, you can download the entire collection as a
> [ZIP file](https://github.com/Microsoft/Windows-universal-samples/archive/master.zip), but be
> sure to unzip everything to access shared dependencies. For more info on working with the ZIP file,
> the samples collection, and GitHub, see [Get the UWP samples from GitHub](https://aka.ms/ovu2uq).
> For more samples, see the [Samples portal](https://aka.ms/winsamples) on the Windows Dev Center.

If multiple faces are detected, then the sample will pick the face closest to the center of the
user's gaze. If no faces are detected then the text "No faces detected" is displayed.

This sample uses the webcam and microphone app capability in order to access the MediaCapture
object and stream video images to the FaceAnalysis API and to the user.

### FaceAnalysis and HoloLens

The FaceTracker class processes images and returns a list of rectangles inside the image where the
faces are detected. This is a very intensive process to run in real-time, and could reduce rendering
performance if it were to slow down the main render thread. It is very important that Holographic
applications maintain 60fps for rendering to reduce user discomfort.

In this sample, we are rendering holograms at 60fps, receiving video frames at 30fps, and running
the FaceTracker as fast as it can process new frames (about 10-15fps). In order to keep rendering
performance at 60fps, we run the FaceAnalysis on an explicit background thread. This adds a bit of
complexity to sychronize between the FaceAnalysis worker thread and the main render thread.

### Handling NV12 images

The HoloLens PV camera provides NV12 video images by default, which can't be directly
used in the shaders for rendering to a RGB backbuffer. Converting the full image from NV12 to RGB
is possible, but it's an expensive operation. We only need to render the portion of the frame where
the face was detected. So instead of converting the full image, we can convert NV12 to RGB in the
pixel shader itself.

NV12 is a 8-bit YUV format for video rendering. To obtain more information about YUV and video formats,
see [Recommended 8-Bit YUV Formats for Video Rendering](https://msdn.microsoft.com/library/windows/desktop/dd206750.aspx).

### Additional remarks

**Note** The Windows universal samples for Windows 10 Holographic require Visual Studio 2017 Update 3
to build, and a Windows Holographic device to execute. Windows Holographic devices include the
Microsoft HoloLens and the Microsoft HoloLens Emulator.

To obtain information about Windows 10 development, go to the [Windows Dev Center](http://go.microsoft.com/fwlink/?LinkID=532421).

To obtain information about the tools used for Windows Holographic development, including
Microsoft Visual Studio 2017 Update 3 and the Microsoft HoloLens Emulator, go to
[Install the tools](https://developer.microsoft.com/windows/holographic/install_the_tools).

## Related topics

### Samples

[BasicFaceDetection](/Samples/BasicFaceDetection)

[BasicFaceTracking](/Samples/BasicFaceTracking)

[CameraFrames](/Sample/CameraFrames)

### Reference

The following types are used in this code sample:
* [Windows.Media.Capture namespace](https://msdn.microsoft.com/library/windows/apps/windows.media.capture.aspx)
  * [MediaCapture class](https://msdn.microsoft.com/library/windows/apps/windows.media.capture.mediacapture.aspx)
* [Windows.Media.Capture.Frames namespace](https://msdn.microsoft.com/library/windows/apps/windows.media.capture.frames.aspx)
  * [MediaFrameReference class](https://msdn.microsoft.com/library/windows/apps/windows.media.capture.frames.mediaframereference.aspx)
  * [MediaFrameReference.CoordinateSystem property](https://msdn.microsoft.com/library/windows/apps/windows.media.capture.frames.mediaframereference.coordinatesystem.aspx)
  * [MediaFrameSource class](https://msdn.microsoft.com/library/windows/apps/windows.media.capture.frames.mediaframesource.aspx)
  * [VideoMediaFrame class](https://msdn.microsoft.com/library/windows/apps/windows.media.capture.frames.videomediaframe.aspx)
  * [VideoMediaFrame.CameraIntrinsics](https://msdn.microsoft.com/library/windows/apps/windows.media.capture.frames.videomediaframe.cameraintrinsics.aspx)
* [Windows.Media.Devices.Core namespace](https://msdn.microsoft.com/library/windows/apps/windows.media.devices.core.aspx)
  * [CameraIntrinsics class](https://msdn.microsoft.com/library/windows/apps/windows.media.devices.core.cameraintrinsics.aspx)
  * [CameraIntrinsics.UnprojectAtUnitDepth method](https://msdn.microsoft.com/library/windows/apps/windows.media.devices.core.cameraintrinsics.unprojectatunitdepth.aspx)
* [Windows.Media.FaceAnalysis namespace](https://msdn.microsoft.com/library/windows/apps/windows.media.faceanalysis.aspx)
  * [FaceTracker class](https://msdn.microsoft.com/library/windows/apps/windows.media.faceanalysis.facetracker.aspx)
  * [FaceTracker.ProcessNextFrameAsync method](https://msdn.microsoft.com/library/windows/apps/windows.media.faceanalysis.facetracker.processnextframeasync.aspx)

## System requirements

**Client:** Windows 10 Holographic build 14393

**Phone:** Not supported

## Build the sample

1. If you download the samples ZIP, be sure to unzip the entire archive, not just the folder with
   the sample you want to build.
2. Start Microsoft Visual Studio 2017 and select **File** \> **Open** \> **Project/Solution**.
3. Starting in the folder where you unzipped the samples, go to the Samples subfolder, then the
   subfolder for this specific sample, then the subfolder for your preferred language (C++, C#, or
   JavaScript). Double-click the Visual Studio Solution (.sln) file.
4. Press Ctrl+Shift+B, or select **Build** \> **Build Solution**.

## Run the sample

The next steps depend on whether you just want to deploy the sample or you want to both deploy and
run it.

### Deploying the sample to the Microsoft HoloLens emulator

- Click the debug target drop-down, and select **Microsoft HoloLens Emulator**.
- Select **Build** \> **Deploy** Solution.

### Deploying the sample to a Microsoft HoloLens

- Developer unlock your Microsoft HoloLens. For instructions, go to [Enable your device for development]
  (https://msdn.microsoft.com/windows/uwp/get-started/enable-your-device-for-development#enable-your-windows-10-devices).
- Find the IP address of your Microsoft HoloLens. The IP address can be found in **Settings**
  \> **Network & Internet** \> **Wi-Fi** \> **Advanced options**. Or, you can ask Cortana for this
  information by saying: "Hey Cortana, what's my IP address?"
- Right-click on your project in Visual Studio, and then select **Properties**.
- In the Debugging pane, click the drop-down and select **Remote Machine**.
- Enter the IP address of your Microsoft HoloLens into the field labelled **Machine Name**.
- Click **OK**.
- Select **Build** \> **Deploy** Solution.

### Pairing your developer-unlocked Microsoft HoloLens with Visual Studio

The first time you deploy from your development PC to your developer-unlocked Microsoft HoloLens,
you will need to use a PIN to pair your PC with the Microsoft HoloLens.
- When you select **Build** \> **Deploy Solution**, a dialog box will appear for Visual Studio to
  accept the PIN.
- On your Microsoft HoloLens, go to **Settings** \> **Update** \> **For developers**, and click on
  **Pair**.
- Type the PIN displayed by your Microsoft HoloLens into the Visual Studio dialog box and click
  **OK**.
- On your Microsoft HoloLens, select **Done** to accept the pairing.
- The solution will then start to deploy.

### Deploying and running the sample

- To debug the sample and then run it, follow the steps listed above to connect your
  developer-unlocked Microsoft HoloLens, then press F5 or select **Debug** \> **Start Debugging**.
  To run  the sample without debugging, press Ctrl+F5 or select **Debug** \> **Start Without Debugging**.


text:
require 'spec_helper'
require 'yt/models/channel'

describe Yt::Channel do
  subject(:channel) { Yt::Channel.new attrs }

  describe '#title' do
    context 'given a snippet with a title' do
      let(:attrs) { {snippet: {"title"=>"Fullscreen"}} }
      it { expect(channel.title).to eq 'Fullscreen' }
    end

    context 'given a snippet without a title' do
      let(:attrs) { {snippet: {}} }
      it { expect(channel.title).to eq '' }
    end
  end

  describe '#description' do
    context 'given a snippet with a description' do
      let(:attrs) { {snippet: {"description"=>"A cool channel."}} }
      it { expect(channel.description).to eq 'A cool channel.' }
    end

    context 'given a snippet without a description' do
      let(:attrs) { {snippet: {}} }
      it { expect(channel.description).to eq '' }
    end
  end

  describe '#thumbnail_url' do
    context 'given a snippet with thumbnails' do
      let(:attrs) { {snippet: {"thumbnails"=>{
        "default"=>{"url"=> "http://example.com/88x88.jpg"},
        "medium"=>{"url"=> "http://example.com/240x240.jpg"},
      }}} }
      it { expect(channel.thumbnail_url).to eq 'http://example.com/88x88.jpg' }
      it { expect(channel.thumbnail_url 'default').to eq 'http://example.com/88x88.jpg' }
      it { expect(channel.thumbnail_url :default).to eq 'http://example.com/88x88.jpg' }
      it { expect(channel.thumbnail_url :medium).to eq 'http://example.com/240x240.jpg' }
      it { expect(channel.thumbnail_url :high).to be_nil }
    end

    context 'given a snippet without thumbnails' do
      let(:attrs) { {snippet: {}} }
      it { expect(channel.thumbnail_url).to be_nil }
    end
  end

  describe '#published_at' do
    context 'given a snippet with a timestamp' do
      let(:attrs) { {snippet: {"publishedAt"=>"2014-04-22T19:14:49.000Z"}} }
      it { expect(channel.published_at.year).to be 2014 }
    end
  end

  describe '#video_count' do
    context 'given a video with videos' do
      let(:attrs) { {statistics: {"videoCount"=>"42"}} }
      it { expect(channel.video_count).to be 42 }
    end
  end

  describe '#subscriber_count' do
    context 'given a video with subscribers' do
      let(:attrs) { {statistics: {"subscriberCount"=>"12"}} }
      it { expect(channel.subscriber_count).to be 12 }
    end
  end

  describe '#subscriber_count_visible?' do
    context 'given a video with publicly visible subscribers' do
      let(:attrs) { {statistics: {"hiddenSubscriberCount"=>false}} }
      it { expect(channel).to be_subscriber_count_visible }
    end

    context 'given a video with hidden subscribers' do
      let(:attrs) { {statistics: {"hiddenSubscriberCount"=>true}} }
      it { expect(channel).not_to be_subscriber_count_visible }
    end
  end

  describe '#content_owner' do
    context 'given a content_owner_detail with a content owner' do
      let(:attrs) { {content_owner_details: {"contentOwner"=>"FullScreen"}} }
      it { expect(channel.content_owner).to eq 'FullScreen' }
    end

    context 'given a content_owner_detail without a content owner' do
      let(:attrs) { {content_owner_details: {}} }
      it { expect(channel.content_owner).to be_nil }
    end
  end

  describe '#linked_at' do
    context 'given a content_owner_detail with a timeLinked' do
      let(:attrs) { {content_owner_details: {"timeLinked"=>"2014-04-22T19:14:49.000Z"}} }
      it { expect(channel.linked_at.year).to be 2014 }
    end

    context 'given a content_owner_detail with a timeLinked' do
      let(:attrs) { {content_owner_details: {}} }
      it { expect(channel.linked_at).to be_nil }
    end
  end

  describe '#snippet' do
    context 'given fetching a channel returns a snippet' do
      let(:attrs) { {snippet: {"title"=>"Fullscreen"}} }
      it { expect(channel.snippet).to be_a Yt::Snippet }
    end
  end

  describe '#status' do
    context 'given fetching a channel returns a status' do
      let(:attrs) { {status: {"privacyStatus"=>"public"}} }
      it { expect(channel.status).to be_a Yt::Status }
    end
  end
end


text:
package org.jboss.pnc.spi.datastore.predicates;

import org.jboss.pnc.model.BuildConfiguration;
import org.jboss.pnc.model.BuildConfigurationSet;
import org.jboss.pnc.model.BuildConfigurationSet_;
import org.jboss.pnc.model.BuildConfiguration_;
import org.jboss.pnc.model.Product;
import org.jboss.pnc.model.ProductVersion;
import org.jboss.pnc.model.ProductVersion_;
import org.jboss.pnc.model.Product_;
import org.jboss.pnc.spi.datastore.repositories.api.Predicate;

import javax.persistence.criteria.Join;
import javax.persistence.criteria.SetJoin;

/**
 * Predicates for {@link org.jboss.pnc.model.ProductVersion} entity.
 */
public class ProductVersionPredicates {

    public static Predicate<ProductVersion> withProductId(Integer productId) {
        return (root, query, cb) -> {
            Join<ProductVersion, Product> product = root.join(ProductVersion_.product);
            return cb.equal(product.get(Product_.id), productId);
        };
    }

    // THIS PREDICATE GIVES ALL THE PRODUCTVERSIONS LINKED TO THE BUILDCONFIGURATIONSETS THAT CONTAIN A CERTAIN BUILDCONFIGURATION
    /*public static Predicate<ProductVersion> withBuildConfigurationId(Integer buildConfigurationId) {
        return (root, query, cb) -> {
            SetJoin<ProductVersion, BuildConfigurationSet> buildConfigurationSetSetJoin = root.join(ProductVersion_.buildConfigurationSets);
            SetJoin<BuildConfigurationSet, BuildConfiguration> buildConfigurationJoin = buildConfigurationSetSetJoin.join( BuildConfigurationSet_.buildConfigurations);
            return cb.equal(buildConfigurationJoin.get(BuildConfiguration_.id), buildConfigurationId);
        };
    }*/

    /**
     * This predicate returns all the ProductVersions linked to a specified BuildConfiguration
     */
    public static Predicate<ProductVersion> withBuildConfigurationId(Integer buildConfigurationId) {
        return (root, query, cb) -> {
            SetJoin<ProductVersion, BuildConfiguration> buildConfigurationJoin = root.join(ProductVersion_.buildConfigurations);
            return cb.equal(buildConfigurationJoin.get(BuildConfiguration_.id), buildConfigurationId);
        };
    }

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>subinstrinit</title>
    <link rel="stylesheet" type="text/css" href="csound.css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.78.1" />
    <link rel="home" href="index.html" title="The Canonical Csound Reference Manual" />
    <link rel="up" href="OpcodesTop.html" title="Orchestra Opcodes and Operators" />
    <link rel="prev" href="subinstr.html" title="subinstr" />
    <link rel="next" href="sum.html" title="sum" />

          subinstrinit

          Prev
          Orchestra Opcodes and Operators
           Next

          subinstrinit

subinstrinit —
      Creates and runs a numbered instrument instance at init-time.

Description

      Same as subinstr, but init-time only and has no output arguments.

Syntax

subinstrinit instrnum [, p4] [, p5] [...]

subinstrinit "insname" [, p4] [, p5] [...]

Initialization

      instrnum -- Number of the instrument to be called.

      "insname" -- A string (in double-quotes) representing a named instrument.

      p4, p5, ... -- Additional input values the are mapped to the called instrument p-fields, starting with p4.

      The called instrument's p2 and p3 values will be identical to the host instrument's values. While the host instrument can control its own duration, any such attempts inside the called instrument will most likely have no effect.

See Also

      event,
      schedule,
      subinstr

Credits

New in version 4.23

          Prev

            Up

           Next

          subinstr

            Home

           sum


text:
package org.sgc.rak.rest;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sgc.rak.model.Compound;
import org.sgc.rak.model.CompoundCountPair;
import org.sgc.rak.reps.PagedDataRep;
import org.sgc.rak.services.CompoundService;
import org.sgc.rak.util.TestUtil;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.util.Arrays;
import java.util.List;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;

public class StatControllerTest {

    @Mock
    private CompoundService mockCompoundService;

    @InjectMocks
    private StatController controller;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testGetCompoundsMissingActivityProfiles_happyPath() {

        CompoundCountPair pairA = new CompoundCountPair("compoundA", 3);
        CompoundCountPair pairB = new CompoundCountPair("compoundB", 4);
        List<CompoundCountPair> pairs = Arrays.asList(pairA, pairB);

        Pageable pageable = PageRequest.of(3, 2);

        PageImpl<CompoundCountPair> page = new PageImpl<>(pairs, pageable, 100);
        doReturn(page).when(mockCompoundService).getCompoundsMissingActivityProfiles(any(), any(Pageable.class));

        PagedDataRep<CompoundCountPair> actualResponse = controller.getCompoundsMissingActivityProfiles(null, pageable);
        Assert.assertEquals(6, actualResponse.getStart());
        Assert.assertEquals(2, actualResponse.getCount());
        Assert.assertEquals(100, actualResponse.getTotal());
        Assert.assertEquals(pairs.size(), actualResponse.getData().size());
        for (int i = 0; i < pairs.size(); i++) {
            CompoundCountPair expected = pairs.get(i);
            CompoundCountPair actual = actualResponse.getData().get(i);
            Assert.assertEquals(expected.getCompoundName(), actual.getCompoundName());
            Assert.assertEquals(expected.getCount(), actual.getCount());
        }
    }

    @Test
    public void testGetCompoundsMissingPublicationInfo_happyPath() {

        List<Compound> compounds = Arrays.asList(
            TestUtil.createCompound("compoundA"),
            TestUtil.createCompound("compoundB")
        );

        Pageable pageable = PageRequest.of(3, 2);

        PageImpl<Compound> page = new PageImpl<>(compounds, pageable, 100);
        doReturn(page).when(mockCompoundService).getCompoundsMissingPublicationInfo(any(), any(Pageable.class));

        PagedDataRep<Compound> actualResponse = controller.getCompoundsMissingPublicationInfo(null, pageable);
        Assert.assertEquals(6, actualResponse.getStart());
        Assert.assertEquals(2, actualResponse.getCount());
        Assert.assertEquals(100, actualResponse.getTotal());
        Assert.assertEquals(compounds.size(), actualResponse.getData().size());
        for (int i = 0; i < compounds.size(); i++) {
            TestUtil.assertCompoundsEqual(compounds.get(i), actualResponse.getData().get(i));
        }
    }

    @Test
    public void testGetHiddenCompounds_happyPath() {

        List<Compound> compounds = Arrays.asList(
            TestUtil.createCompound("compoundA"),
            TestUtil.createCompound("compoundB")
        );

        Pageable pageable = PageRequest.of(3, 2);

        PageImpl<Compound> page = new PageImpl<>(compounds, pageable, 100);
        doReturn(page).when(mockCompoundService).getHiddenCompounds(any(), any(Pageable.class));

        PagedDataRep<Compound> actualResponse = controller.getHiddenCompounds(null, pageable);
        Assert.assertEquals(6, actualResponse.getStart());
        Assert.assertEquals(2, actualResponse.getCount());
        Assert.assertEquals(100, actualResponse.getTotal());
        Assert.assertEquals(compounds.size(), actualResponse.getData().size());
        for (int i = 0; i < compounds.size(); i++) {
            TestUtil.assertCompoundsEqual(compounds.get(i), actualResponse.getData().get(i));
        }
    }

    @Test
    public void testGetIncompleteCompounds_happyPath() {

        List<Compound> compounds = Arrays.asList(
            TestUtil.createCompound("compoundA"),
            TestUtil.createCompound("compoundB")
        );

        Pageable pageable = PageRequest.of(3, 2);

        PageImpl<Compound> page = new PageImpl<>(compounds, pageable, 100);
        doReturn(page).when(mockCompoundService).getIncompleteCompounds(any(), any(Pageable.class));

        PagedDataRep<Compound> actualResponse = controller.getIncompleteCompounds(null, pageable);
        Assert.assertEquals(6, actualResponse.getStart());
        Assert.assertEquals(2, actualResponse.getCount());
        Assert.assertEquals(100, actualResponse.getTotal());
        Assert.assertEquals(compounds.size(), actualResponse.getData().size());
        for (int i = 0; i < compounds.size(); i++) {
            TestUtil.assertCompoundsEqual(compounds.get(i), actualResponse.getData().get(i));
        }
    }
}


text:
namespace Dg
{
  //! @ingroup DgMath_types
  //!
  //! @class Ray
  //!
  //! A Ray is defined by a point of origin and direction extending infinitely in one
  //! direction. It is represented by a Point and a normalized Vector. This file
  //! also declares methods to test Rays against other geometric entities.
  //!
  template<typename Real, int R>
  class Ray
  {
  public:

    Ray();
    Ray(Vector<Real, R> const &origin, Vector<Real, R> const &direction);
    Ray(Ray const &);
    Ray& operator=(Ray const &);

    Vector<Real, R> const & Origin() const { return m_origin; }
    Vector<Real, R> const & Direction() const { return m_direction; }

    //! Set ray from an origin and direction
    ErrorCode Set(Vector<Real, R> const & origin, Vector<Real, R> const & direction);

  private:

    //Data members
    Vector<Real, R> m_origin;
    Vector<Real, R> m_direction;
  };

  //--------------------------------------------------------------------------------
  //	Typedefs
  //--------------------------------------------------------------------------------

  template<typename Real>
  using Ray2 = Ray<Real, 2>;

  template<typename Real>
  using Ray3 = Ray<Real, 3>;

  //--------------------------------------------------------------------------------
  //	Definitions
  //--------------------------------------------------------------------------------

  template<typename Real, int R>
  Ray<Real, R>::Ray()
    : m_origin(Zeros<Real, R>())
    , m_direction(XAxis<Real, R>())
  {
  }

  template<typename Real, int R>
  Ray<Real, R>::Ray(Vector<Real, R> const &origin, Vector<Real, R> const &direction)
    : m_origin(origin)
    , m_direction(direction)
  {
    Set(origin, direction);
  }

  template<typename Real, int R>
  Ray<Real, R>::Ray(Ray<Real, R> const & a_other)
    : m_origin(a_other.m_origin)
    , m_direction(a_other.m_direction)
  {
  }

  template<typename Real, int R>
  Ray<Real, R> & Ray<Real, R>::operator=(Ray<Real, R> const & a_other)
  {
    m_origin = a_other.m_origin;
    m_direction = a_other.m_direction;

    return *this;
  }

  template<typename Real, int R>
  ErrorCode Ray<Real, R>::Set(Vector<Real, R> const & a_origin, Vector<Real, R> const & a_direction)
  {
    m_origin = a_origin;
    m_direction = Normalize(a_direction);
    return ErrorCode::None;
  }
}

#endif


text:
using System;
using System.Diagnostics;
using System.Runtime.Serialization;

namespace STAR.Originations.MegaRunbook.Contracts.Data
{
    [DataContract(Namespace = "http://services.nationstarmtg.net/Capital/Markets/2014/09")]
    [DebuggerDisplay("{DebuggerDisplay}")]
    public class ApplicationType
    {
        [DataMember] public string Code { get; set; }
        [DataMember] public string Description { get; set; }

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        private string DebuggerDisplay => String.Format("Code: {0}", this.Code);
    }
}


text:
<!doctype html>

    <meta charset="utf-8">

<title>Courses | Jérémie</title>
<meta name="description" content="Here is the list of the Courses I have received and the one I have given.">

  <meta name="author" content="Jérémie Kalfon">

<meta property="og:type" content="website">
<meta property="og:locale" content="en_US">
<meta property="og:site_name" content="Jérémie">
<meta property="og:title" content="Courses">
<meta property="og:url" content="http://localhost:4000/courses/">

  <meta property="og:description" content="Here is the list of the Courses I have received and the one I have given.">

  <meta property="og:image" content="http://localhost:4000/assets/images/feynman.jpeg">

  <meta name="twitter:site" content="@jkobject">
  <meta name="twitter:title" content="Courses">
  <meta name="twitter:description" content="Here is the list of the Courses I have received and the one I have given.">
  <meta name="twitter:url" content="http://localhost:4000/courses/">

    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:image" content="http://localhost:4000/assets/images/feynman.jpeg">

    <meta property="article:publisher" content="https://www.facebook.com/jkobject">

<link rel="canonical" href="http://localhost:4000/courses/">

  <link href="/feed.xml" type="application/atom+xml" rel="alternate" title="Jérémie Feed">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="/assets/css/main.css">
<link rel="preload" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5/css/all.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5/css/all.min.css">

<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="theme-color" content="#ffffff">

Skip to primary navigation

Skip to content

Skip to footer

          Jérémie K.

              <a href="/about/" title="I am a human. I wish to make the world better with science. <3">About

              Projects

              Opinions

              Ideas

              Blog

              Papers

              Courses

              Culture

              Subjects

        <button class="search__toggle" type="button">
          Toggle search

        </button>

        <button class="greedy-nav__toggle hidden" type="button">
          Toggle menu

        </button>

          Courses

Here is the list of the Courses I have received and the one I have given.

    Feynman, my Hero…

          Home

          <meta itemprop="position" content="1" />

        /

Courses

    <meta itemprop="headline" content="Courses">
    <meta itemprop="description" content="Here is the list of the Courses I have received and the one I have given.">

 On this page

Courses I have followed

Courses to follow (or following)

videos

Slides

ECE - ING5 - SANTE 2017-2018 (to review)

Courses I have given

HighSchool

undergraduate level

Presenations

Knowledge in informatics

Courses I have followed

Courses to follow (or following)

videos

ML to see: (100) <input type="range" disabled="disabled" value="80" />

mathematical monk: (160) <input type="range" disabled="disabled" value="100" />

dev to see (50) <input type="range" disabled="disabled" value="10" />

DeepMind's DL and RL course <input type="range" disabled="disabled" value="0" />

Oxford's Strachey Lecture <input type="range" disabled="disabled" value="10" />

Slides

most slides here have not been made public by the authors

gene duplication L3 UE genomic ENS <input type="range" disabled="disabled" value="100" />

the human aging problem L3 UE genomic ENS <input type="range" disabled="disabled" value="100" />

MEG eukaryotic transcription and regulation ENS <input type="range" disabled="disabled" value="100" />

elements in genome and UE introduction L3 UE genomic ENS <input type="range" disabled="disabled" value="100" />

Advanced Biomed imaging ECE M2 <input type="range" disabled="disabled" value="0" />

Riemannian geometry ENS Math M2 <input type="range" disabled="disabled" value="20" />

Human Anatomy ECE M2 <input type="range" disabled="disabled" value="0" />

Baptiste Tesson's ENS Y3 <input type="range" disabled="disabled" value="0" />

Baptiste Tesson's ENS Y4 <input type="range" disabled="disabled" value="0" />

Temporal Difference <input type="range" disabled="disabled" value="0" />

CS231 <input type="range" disabled="disabled" value="0" />

Reinforcement Learning Class <input type="range" disabled="disabled" value="0" />

ECE - ING5 - SANTE 2017-2018 (to review)

Neurosciences et implants

Physique de la matière molle

Biopuces

Objet co en santé

Handicaps et techno

Smart data et santé

Cristaux liquides

Telemédecine

Chirurgie assisté par ordinateur

Physiopathologie & biocompatibilité

Chirurgie à distance

Physique des nanocomposants

Prothèses

Structures MIS

Spéctroscopie UV-Visible

Les techniques de lithographie

Courses I have given

HighSchool

as a private teacher

math

physics

chemistry

biology

undergraduate level

as a private teacher

optics

integrals (calculus)

Presenations

Knowledge in informatics

VHDL <input type="range" disabled="disabled" value="30" />

simple counting machine

simple games

Arduino <input type="range" disabled="disabled" value="50" />

robots

car

drones

gazebo <input type="range" disabled="disabled" value="40" />

shapes

events

controls

C <input type="range" disabled="disabled" value="30" />

OccamPi <input type="range" disabled="disabled" value="20" />

Google Go <input type="range" disabled="disabled" value="10" />

C++ <input type="range" disabled="disabled" value="30" />

Java <input type="range" disabled="disabled" value="70" />

graphics

android

server

simple J2E

R <input type="range" disabled="disabled" value="20" />

Python <input type="range" disabled="disabled" value="90" />

numpy

conda

bioconda

biopython

tensorflow

pandas

scikit learn

bokeh

jupyter

Matlab <input type="range" disabled="disabled" value="50" />

GUI

signal proc

functions

parrallel

arrays

computational genomics <input type="range" disabled="disabled" value="70" />

blast

ensembl

star

rsem

absolute

macs

ros

mutect

fastqc

gatk

strelka

samtools

bowtie

deeptools

bamtools

picard

terra

cromwell

wdl

gcp

nextflow

gsea

phylogenetics

RNAseq

DNAseq (targeted/ exome / whole)

Chip

HiC

CI <input type="range" disabled="disabled" value="50" />

travis

shipeable

sentry

jest

nose

CD <input type="range" disabled="disabled" value="50" />

fastlane

android

ios

macOS

Latex <input type="range" disabled="disabled" value="40" />

Markdown <input type="range" disabled="disabled" value="100" />

HTML <input type="range" disabled="disabled" value="70" />

CSS <input type="range" disabled="disabled" value="70" />

JavaScript <input type="range" disabled="disabled" value="90" />

react native

angular.js

react.js

node

ES6

JSX

flow

mobx

webpack

electron

expo

async

navigation

npm, yarn

PHP <input type="range" disabled="disabled" value="20" />

20 pages simple server

DNS management <input type="range" disabled="disabled" value="40" />

namecheap

goDaddy

Shell <input type="range" disabled="disabled" value="70" />

basics

server connection

git

brew

vim <input type="range" disabled="disabled" value="20" />

sublime <input type="range" disabled="disabled" value="70" />

intelIJ <input type="range" disabled="disabled" value="70" />

vscode <input type="range" disabled="disabled" value="70" />

SQL <input type="range" disabled="disabled" value="50" />

nosql

firebase

Json

XML

MySQL

MaMp

google cloud platform <input type="range" disabled="disabled" value="50" />

aws <input type="range" disabled="disabled" value="30" />

scientific computing

web hosting

Versioning

svn

github

gitKraken

github Desktop

sourceTree

Google Suite

Adobe <input type="range" disabled="disabled" value="40" />

AE

XD

PS

AI

3D printing <input type="range" disabled="disabled" value="30" />

preform

solidworks

other software based programming

LabVIEW

emergent

NRP

NMP

FluoroCT

Osirix

<form class="search-content__form" onkeydown="return event.key != 'Enter';" role="search">

      Enter your search term...

    <input type="search" id="search" class="search-input" tabindex="-1" placeholder="Enter your search term..." />
  </form>

Follow:

 Email

 Twitter

 GitHub

 ResearchGate

 Scholar

 LinkedIn

 Feed

© 2022 Jérémie Kalfon. Powered by Jekyll & Minimal Mistakes.


text:
import {Inject, State} from "fd-angular-core";
import TMPL from "./Form.html!";
import CSS from "./Form.css!";

let nextCtrlId = 0;

export function Form(opts) {
	nextCtrlId++;

	@State({
		templateUrl: TMPL,
		controllerName: `fd.admin.form.${nextCtrlId}`,
	})
	@Inject("module", '$mdDialog')
	class FormController {

		constructor(module, $mdDialog) {
			this.$mdDialog = $mdDialog;
			this.module = module;
			this.formTMPL = (opts.templateUrl);
		}

		@Inject("$stateParams")
		activate($stateParams) {
			if (!$stateParams.id) {
				this.item = {};
				this.isCreate = true;
				return undefined;
			}

			this.isUpdate = true;
			return this.module.fetch($stateParams.id)
				.then(item => this.item = item);
		}

		@Inject('$state', "$element")
		attach($state, $element) {
			this.$state = $state;
			$element.addClass(CSS.fdForm);
		}

		@Inject("$element")
		detach($element) {
			$element.removeClass(CSS.fdForm);
		}

		cancel($event) {
			$event.stopImmediatePropagation();
			$event.preventDefault();
			if (this.isCreate) {
				this.$state.go("^.index");
			} else {
				if (this.module.hasUpdate) {
					this.$state.go("^.show", {id: this.item.id});
				} else {
					this.$state.go("^.index");
				}
			}
		}

		submit() {
			let p;

			if (this.isCreate) {
				p = this.module.create(this.item);
				if (!p) { throw Error(".create(item) must return a Promise"); }
			} else {
				p = this.module.update(this.item);
				if (!p) { throw Error(".update(item) must return a Promise"); }
			}

			p = p
				.then(item => this.item = item)
				.then(item => this.$state.go("^.show", {id: item.id}));

			p = p.catch(error => {
				let message = (error && error.message) || error;

				if (error.status === 403) {
					message = "You are not allowed to do this.";
				}

				let alert = this.$mdDialog.alert()
					.title('Oops, something went wrong.')
					.content(`${message}`)
					.ok('Close');
				return this.$mdDialog.show(alert);
			});

			return p;
		}

	}

	return FormController;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="caps.ua.edu.materialdemo" >

    <application
        android:allowBackup="true"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Activities.MyActivity"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name=".Activities.LoginActivity"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppThemeNoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Activities.RegisterActivity"
            android:label="@string/title_activity_register"
            android:theme="@style/AppThemeRegister"
            android:uiOptions="splitActionBarWhenNarrow" >
        </activity>
        <activity
            android:name=".Activities.BaseActivity"
            android:label="@string/title_activity_base" >
        </activity>
    </application>

</manifest>


text:
package generator.panels;

import generator.extenders.RandomiserInstance;
import generator.extenders.RandomiserPanel;

import java.util.LinkedHashMap;

import javax.swing.JOptionPane;

/*
 * dgMaster: A versatile, open source data generator.
 *(c) 2007 M. Michalakopoulos, mmichalak@gmail.com
 */
public class PanelGenericStageDataContext  extends RandomiserPanel{

	private static final long serialVersionUID = 8797054440294377030L;
	/** Creates new form PanelSequencer */
    public PanelGenericStageDataContext()
    {
        initComponents();
    }

    public void initialise(RandomiserInstance ri)
    {
        txtName.setText( ri.getName() );
        txtDescription.setText( ri.getDescription() );

        String ref, pre, post;
        LinkedHashMap<String,String> hashMap;

        hashMap = ri.getProperties();
        ref  = (String) hashMap.get("sdcontextReference");
        pre  = (String) hashMap.get("preFix");
        post = (String) hashMap.get("postFix");

        stageDataRef .setText(ref);
        preFix.setText(pre);
        postFix.setText(post);
    }

    public RandomiserInstance getRandomiserInstance()
    {
        String name, description;
        String ref, pre, post;
        LinkedHashMap<String,String> hashMap = new LinkedHashMap<String,String>();
        RandomiserInstance ri = new RandomiserInstance();

        //get field values
        name = txtName.getText().trim();
        description  = txtDescription.getText().trim();
        ref =  stageDataRef .getText().trim();
        pre = 	preFix.getText().trim();
        post = 	postFix.getText().trim();

        //create the hashmap
        hashMap.put("sdcontextReference",ref.toString());
        hashMap.put("preFix",pre.toString());
        hashMap.put("postFix",post.toString());

        ri.setRandomiserType("PartialDuplicateFieldRandomiser");
        ri.setName(name);
        ri.setDescription(description);
        ri.setProperties(hashMap);

        return ri;
    }

    public boolean isFormValid()
    {
        String name;
        Integer nullField;
        //get field values
        name = txtName.getText().trim();
       // nullField = (Integer) preFix.getModel().getValue();

        //run checks
        if(name.length()==0)
        {
            JOptionPane.showMessageDialog(this,"Please provide a value for the name.","Required field",JOptionPane.ERROR_MESSAGE);
            return false;
        }
        return true;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtDescription = new javax.swing.JTextArea();
        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        stageDataRef  = new javax.swing.JTextField();
        preFix = new javax.swing.JTextField();
        postFix = new javax.swing.JTextField();

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Case description"));

        jLabel4.setText("Name:");

        jLabel5.setText("Description:");

        txtDescription.setColumns(20);
        txtDescription.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
        txtDescription.setLineWrap(true);
        txtDescription.setRows(5);
        txtDescription.setWrapStyleWord(true);
        jScrollPane1.setViewportView(txtDescription);

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel4)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel5))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(txtName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 207, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 559, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(txtName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel5)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 85, Short.MAX_VALUE))
                .addContainerGap())
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Percentages of generated values"));

        jLabel3.setText("Stage Data Ref:");

        jLabel2.setText("PreFix:");

        jLabel6.setText("PostFix:");

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jLabel3)
                    .add(jLabel2)
                    .add(jLabel6))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(stageDataRef, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 207, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(preFix,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 207, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(postFix,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 207, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(stageDataRef , org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(preFix, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel6)
                    .add(postFix, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                )

        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 698, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField stageDataRef ;
    private javax.swing.JTextField preFix;
    private javax.swing.JTextField  postFix;
    private javax.swing.JTextArea txtDescription;
    private javax.swing.JTextField txtName;
    // End of variables declaration//GEN-END:variables
}


text:
"""Checker functions for filtering."""

from warnings import warn

import numpy as np

###################################################################################################
###################################################################################################

def check_filter_definition(pass_type, f_range):
    """Check a filter definition for validity, and get f_lo and f_hi.

    Parameters
    ----------
    pass_type : {'bandpass', 'bandstop', 'lowpass', 'highpass'}
        Which kind of filter to apply:

        * 'bandpass': apply a bandpass filter
        * 'bandstop': apply a bandstop (notch) filter
        * 'lowpass': apply a lowpass filter
        * 'highpass' : apply a highpass filter
    f_range : tuple of (float, float) or float
        Cutoff frequency(ies) used for filter, specified as f_lo & f_hi.
        For 'bandpass' & 'bandstop', must be a tuple.
        For 'lowpass' or 'highpass', can be a float that specifies pass frequency, or can be
        a tuple and is assumed to be (None, f_hi) for 'lowpass', and (f_lo, None) for 'highpass'.

    Returns
    -------
    f_lo : float or None
        The lower frequency range of the filter, specifying the highpass frequency, if specified.
    f_hi : float or None
        The higher frequency range of the filter, specifying the lowpass frequency, if specified.
    """

    if pass_type not in ['bandpass', 'bandstop', 'lowpass', 'highpass']:
        raise ValueError('Filter passtype not understood.')

    ## Check that frequency cutoff inputs are appropriate
    # For band filters, 2 inputs required & second entry must be > first
    if pass_type in ('bandpass', 'bandstop'):
        if isinstance(f_range, tuple) and f_range[0] >= f_range[1]:
            raise ValueError('Second cutoff frequency must be greater than first.')
        elif isinstance(f_range, (int, float)) or len(f_range) != 2:
            raise ValueError('Two cutoff frequencies required for bandpass and bandstop filters')

        # Map f_range to f_lo and f_hi
        f_lo, f_hi = f_range

    # For lowpass and highpass can be tuple or int/float
    if pass_type == 'lowpass':
        if isinstance(f_range, (int, float)):
            f_hi = f_range
        elif isinstance(f_range, tuple):
            f_hi = f_range[1]
        f_lo = None

    if pass_type == 'highpass':
        if isinstance(f_range, (int, float)):
            f_lo = f_range
        elif isinstance(f_range, tuple):
            f_lo = f_range[0]
        f_hi = None

    # Make sure pass freqs are floats
    f_lo = float(f_lo) if f_lo else f_lo
    f_hi = float(f_hi) if f_hi else f_hi

    return f_lo, f_hi

def check_filter_properties(b_vals, a_vals, fs, pass_type, f_range, transitions=(-20, -3), verbose=True):
    """Check a filters properties, including pass band and transition band.

    Parameters
    ----------
    b_vals : 1d array
        B value filter coefficients for a filter.
    a_vals : 1d array
        A value filter coefficients for a filter.
    fs : float
        Sampling rate, in Hz.
    pass_type : {'bandpass', 'bandstop', 'lowpass', 'highpass'}
        Which kind of filter to apply:

        * 'bandpass': apply a bandpass filter
        * 'bandstop': apply a bandstop (notch) filter
        * 'lowpass': apply a lowpass filter
        * 'highpass' : apply a highpass filter
    f_range : tuple of (float, float) or float
        Cutoff frequency(ies) used for filter, specified as f_lo & f_hi.
        For 'bandpass' & 'bandstop', must be a tuple.
        For 'lowpass' or 'highpass', can be a float that specifies pass frequency, or can be
        a tuple and is assumed to be (None, f_hi) for 'lowpass', and (f_lo, None) for 'highpass'.
    transitions : tuple of (float, float), optional, default: (-20, -3)
        Cutoffs, in dB, that define the transition band.
    verbose : bool, optional, default: True
        Whether to print out transition and pass bands.

    Returns
    -------
    passes : bool
        Whether all the checks pass. False if one or more checks fail.
    """

    # Import utility functions inside function to avoid circular imports
    from neurodsp.filt.utils import (compute_frequency_response,
                                     compute_pass_band, compute_transition_band)

    # Initialize variable to keep track if all checks pass
    passes = True

    # Compute the frequency response
    f_db, db = compute_frequency_response(b_vals, a_vals, fs)

    # Check that frequency response goes below transition level (has significant attenuation)
    if np.min(db) >= transitions[0]:
        passes = False
        warn('The filter attenuation never goes below {} dB.'\
             'Increase filter length.'.format(transitions[0]))
        # If there is no attenuation, cannot calculate bands, so return here
        return passes

    # Check that both sides of a bandpass have significant attenuation
    if pass_type == 'bandpass':
        if db[0] >= transitions[0] or db[-1] >= transitions[0]:
            passes = False
            warn('The low or high frequency stopband never gets attenuated by'\
                 'more than {} dB. Increase filter length.'.format(abs(transitions[0])))

    # Compute pass & transition bandwidth
    pass_bw = compute_pass_band(fs, pass_type, f_range)
    transition_bw = compute_transition_band(f_db, db, transitions[0], transitions[1])

    # Raise warning if transition bandwidth is too high
    if transition_bw > pass_bw:
        passes = False
        warn('Transition bandwidth is  {:.1f}  Hz. This is greater than the desired'\
             'pass/stop bandwidth of  {:.1f} Hz'.format(transition_bw, pass_bw))

    # Print out transition bandwidth and pass bandwidth to the user
    if verbose:
        print('Transition bandwidth is {:.1f} Hz.'.format(transition_bw))
        print('Pass/stop bandwidth is {:.1f} Hz.'.format(pass_bw))

    return passes


text: from .random_n_for_each_ap import RandomNForEachAPInSample


text:
@class NSMutableArray;

@interface WFVolumeGestureRecognizer : NSObject
{
    float lastVolume;
    NSMutableArray *supportGestures;
    BOOL _enabled;
    id <WFVolumeGestureRecognizerDelegate> _delegate;
}

@property BOOL enabled; // @synthesize enabled=_enabled;
@property __weak id <WFVolumeGestureRecognizerDelegate> delegate; // @synthesize delegate=_delegate;
- (void).cxx_destruct;
- (BOOL)isHistoryValidGestureForType:(int)arg1;
- (void)volumeDidChangeNotification:(id)arg1;
- (float)ipodVolume;
- (unsigned int)volumeHistoryLength;
- (void)resetVolumeHistory;
- (void)addVolumeState:(struct WF_VOLUME_STATE)arg1;
- (struct WF_VOLUME_STATE)volumeStateAtPosition:(unsigned char)arg1;
- (void)cancelAllGestureDispatches;
- (void)dispatchVolumeGestureWithInfo:(id)arg1;
- (void)disableVolumeNotifications;
- (void)enableVolumeNotifications;
- (void)dealloc;
- (void)clearAllSupportedGestures;
- (void)addSupportGestureType:(int)arg1;
- (id)init;

@end