text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace ForkandBeard.Util.UI
{
    public class ListViewSorter : IComparer
    {
        /// <summary>
        /// Case insensitive comparer object
        /// </summary>
        private CaseInsensitiveComparer ObjectCompare;

        /// <summary>
        /// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0').
        /// </summary>
        public int SortColumn { get; set; }

        /// <summary>
        /// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending').
        /// </summary>
        public SortOrder Order { get; set; }

        public ListViewSorter()
        {
            // Initialize the column to '0'
            this.SortColumn = 0;
            // Initialize the sort order to 'none'
            this.Order = SortOrder.None;
            // Initialize the CaseInsensitiveComparer object
            this.ObjectCompare = new CaseInsensitiveComparer();
        }

        public static void SortListViewColumn(System.Windows.Forms.ListView listView, int columnIndex, SortOrder order)
        {
            ListViewSorter sorter;
            if (listView.ListViewItemSorter == null)
            {
                ListView.MakeListViewSortable(listView);
            }
            sorter = (ListViewSorter)listView.ListViewItemSorter;

            sorter.Order = order;
            sorter.SortColumn = columnIndex;
            listView.Sort();
        }

        public void HandleColumnClicked(System.Windows.Forms.ListView listView, ColumnClickEventArgs e)
        {
            // Determine if clicked column is already the column that is being sorted.
            if (e.Column == this.SortColumn)
            {
                // Reverse the current sort direction for this column.
                if (this.Order == SortOrder.Ascending)
                {
                    this.Order = SortOrder.Descending;
                }
                else
                {
                    this.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // Set the column number that is to be sorted; default to ascending.
                this.SortColumn = e.Column;
                this.Order = SortOrder.Ascending;
            }

            // Perform the sort with these new sort options.
            listView.Sort();
        }

        public int Compare(object x, object y)
        {
            int compareResult;
            ListViewItem listviewX, listviewY;
            string textA;
            string textB;
            DateTime dateA;
            DateTime dateB;
            decimal numA;
            decimal numB;

            // Cast the objects to be compared to ListViewItem objects
            listviewX = (ListViewItem)x;
            listviewY = (ListViewItem)y;

            textA = listviewX.SubItems[this.SortColumn].Text;
            textB = listviewY.SubItems[this.SortColumn].Text;

            // Compare the two items
            if (
                DateTime.TryParse(textA, out dateA)
                && DateTime.TryParse(textB, out dateB)
                )
            {
                compareResult = Convert.ToInt32(dateA.Subtract(dateB).TotalSeconds);
            }
            else if (
                    Decimal.TryParse(textA, out numA)
                    && Decimal.TryParse(textB, out numB)
                    )
            {
                compareResult = Decimal.Compare(numA, numB);
            }
            else
            {
                compareResult = this.ObjectCompare.Compare(textA, textB);
            }

            // Calculate correct return value based on object comparison
            if (this.Order == SortOrder.Ascending)
            {
                // Ascending sort is selected, return normal result of compare operation
                return compareResult;
            }
            else if (this.Order == SortOrder.Descending)
            {
                // Descending sort is selected, return negative result of compare operation
                return (-compareResult);
            }
            else
            {
                // Return '0' to indicate they are equal
                return 0;
            }
        }
    }
}


text:
/* global define */

/* eslint-disable no-param-reassign */

;(function () {
  'use strict'

  /**
   * Object.assign polyfill
   *
   * @param {object} obj1 First object
   * @param {object} obj2 Second object
   * @returns {object} Merged object
   */
  function extend(obj1, obj2) {
    var prop
    for (prop in obj2) {
      if (Object.prototype.hasOwnProperty.call(obj2, prop)) {
        obj1[prop] = obj2[prop]
      }
    }
    return obj1
  }
  /**
   * Helper constructor
   *
   * @class
   * @param {*} query jQuery type query argument
   */
  function Helper(query) {
    if (!this || this.find !== Helper.prototype.find) {
      // Called as function instead of as constructor,
      // so we simply return a new instance:
      return new Helper(query)
    }
    this.length = 0
    if (query) {
      if (typeof query === 'string') {
        query = this.find(query)
      }
      if (query.nodeType || query === query.window) {
        // Single HTML element
        this.length = 1
        this[0] = query
      } else {
        // HTML element collection
        var i = query.length
        this.length = i
        while (i) {
          i -= 1
          this[i] = query[i]
        }
      }
    }
  }

  Helper.extend = extend

  Helper.contains = function (container, element) {
    do {
      element = element.parentNode
      if (element === container) {
        return true
      }
    } while (element)
    return false
  }

  Helper.parseJSON = function (string) {
    return window.JSON && JSON.parse(string)
  }

  extend(Helper.prototype, {
    find: function (query) {
      var container = this[0] || document
      if (typeof query === 'string') {
        if (container.querySelectorAll) {
          query = container.querySelectorAll(query)
        } else if (query.charAt(0) === '#') {
          query = container.getElementById(query.slice(1))
        } else {
          query = container.getElementsByTagName(query)
        }
      }
      return new Helper(query)
    },

    hasClass: function (className) {
      if (!this[0]) {
        return false
      }
      return new RegExp('(^|\\s+)' + className + '(\\s+|$)').test(
        this[0].className
      )
    },

    addClass: function (className) {
      var i = this.length
      var element
      while (i) {
        i -= 1
        element = this[i]
        if (!element.className) {
          element.className = className
          return this
        }
        if (this.hasClass(className)) {
          return this
        }
        element.className += ' ' + className
      }
      return this
    },

    removeClass: function (className) {
      var regexp = new RegExp('(^|\\s+)' + className + '(\\s+|$)')
      var i = this.length
      var element
      while (i) {
        i -= 1
        element = this[i]
        element.className = element.className.replace(regexp, ' ')
      }
      return this
    },

    on: function (eventName, handler) {
      var eventNames = eventName.split(/\s+/)
      var i
      var element
      while (eventNames.length) {
        eventName = eventNames.shift()
        i = this.length
        while (i) {
          i -= 1
          element = this[i]
          if (element.addEventListener) {
            element.addEventListener(eventName, handler, false)
          } else if (element.attachEvent) {
            element.attachEvent('on' + eventName, handler)
          }
        }
      }
      return this
    },

    off: function (eventName, handler) {
      var eventNames = eventName.split(/\s+/)
      var i
      var element
      while (eventNames.length) {
        eventName = eventNames.shift()
        i = this.length
        while (i) {
          i -= 1
          element = this[i]
          if (element.removeEventListener) {
            element.removeEventListener(eventName, handler, false)
          } else if (element.detachEvent) {
            element.detachEvent('on' + eventName, handler)
          }
        }
      }
      return this
    },

    empty: function () {
      var i = this.length
      var element
      while (i) {
        i -= 1
        element = this[i]
        while (element.hasChildNodes()) {
          element.removeChild(element.lastChild)
        }
      }
      return this
    },

    first: function () {
      return new Helper(this[0])
    }
  })

  if (typeof define === 'function' && define.amd) {
    define(function () {
      return Helper
    })
  } else {
    window.blueimp = window.blueimp || {}
    window.blueimp.helper = Helper
  }
})()

redpajama_set_name: RedPajamaGithub


text:
require "test_helper"

class CustomNoticesTest < ActionDispatch::IntegrationTest
  def valid_params
    {document: {name: "Sample"}}
  end

  def test_has_a_notice
    post "/custom_notices", params: valid_params

    assert_equal "A new document was created", flash[:notice]
    assert_redirected_to root_path
  end

  def test_has_an_alert
    params = valid_params.merge id: 100
    put "/custom_notices/100", params: params

    assert_equal "There are some errors", flash[:alert]
    assert_redirected_to root_path
  end
end


text:
package org.semtag.dao.sql;

/**
 * @author Ari Weiland
 */

import org.jooq.Cursor;
import org.jooq.Record;
import org.semtag.dao.DaoException;

import java.util.Iterator;

/**
 * This iterable is used by the SQL Daos to convert a jOOQ Cursor into an
 * Iterable of the appropriate class. This iterable can only be iterated
 * over once, and will throw exceptions if a user tries otherwise.
 *
 * @author Ari Weiland
 */
public abstract class SqlDaoIterable<E> implements Iterable<E> {
    private Cursor<Record> result;
    private Iterator<Record> iterator;

    private boolean usedUp = false;
    private boolean finished = false;

    /**
     * Constructs a SqlDaoIterable that generates E objects from result.
     * @param result a collection of Records to be converted into outputs
     */
    public SqlDaoIterable(Cursor<Record> result){
        this.result = result;
        this.iterator = result.iterator();
    }

    /**
     * Abstract method to be implemented at use. Describes how the SqlDaoIterable
     * converts records from the input iterator to E items to be outputted.
     * @param record an element from the input iterator.
     * @return an object of class E
     * @throws DaoException
     */
    public abstract E transform(Record record) throws DaoException;

    /**
     * Closes this iterable, disabling all functionality.
     */
    public void close() {
        usedUp = true;
        finished = true;
        while (iterator.hasNext()) {
            iterator.next();
        }
        if (!result.isClosed()) {
            result.close();
        }
    }

    @Override
    public Iterator<E> iterator() {
        if (usedUp) {
            throw new IllegalStateException("SqlDaoIterable can only be iterated over once.");
        }
        usedUp = true;
        return new Iterator<E>() {

            @Override
            public boolean hasNext() {
                try {
                    finished = !iterator.hasNext();
                    if (finished) {
                        close();
                    }
                    return !finished;
                } catch (Exception e) {
                    close();
                    throw new RuntimeException(e);
                }
            }

            @Override
            public E next() {
                try {
                    Record item = iterator.next();
                    if (finished || item == null) {
                        finished = true;
                        close();
                        return null;
                    }
                    return transform(item);
                } catch (Exception e) {
                    close();
                    throw new RuntimeException(e);
                }
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }
}


text:
import os

from migrate.versioning.shell import main

REPOSITORY = os.path.abspath(os.path.dirname(__file__))

if __name__ == '__main__':
    main(debug='False', repository=REPOSITORY)


text:
<?php
require_once (dirname(__FILE__) . DIRECTORY_SEPARATOR . '../includes/Master2.php');

/**
 * @author fcsistemas - www.fcsistemas.com.ar
 * @version 2.1
 * @created 01-oct-2014 04:40:11 p.m.
 */
class ActaTareaRealizadaContratoItemVO extends Master2 {
	public $idActaTareaRealizadaContratoItem = ["valor" => "",
		"obligatorio" => FALSE,
		"tipo" => "integer",
		"nombre" => "ID",
	];
	public $idActaTareaRealizada = ["valor" => "",
		"obligatorio" => TRUE,
		"tipo" => "combo",
		"nombre" => "ATR",
		"referencia" => "",
	];
	public $idContratoItem = ["valor" => "",
		"obligatorio" => TRUE,
		"tipo" => "combo",
		"nombre" => "Contrato ítem",
		"referencia" => "",
	];
	public $cantidad = ["valor" => "",
		"obligatorio" => TRUE,
		"tipo" => "float",
		"nombre" => "cantidad",
		"validador" => ["admiteMenorAcero" => FALSE,
			"admiteCero" => TRUE,
			"admiteMayorAcero" => TRUE,
		],
	];
	public $observaciones = ["valor" => "",
		"obligatorio" => FALSE,
		"tipo" => "string",
		"nombre" => "observaciones",
	];

	public function __construct(){
		parent::__construct();
		$this->result = new Result();
		$this->setTableName('actaTareasRealizada_contratosItems');
		$this->setFieldIdName('idActaTareaRealizadaContratoItem');
		$this->idActaTareaRealizada['referencia'] =  new ActaTareaRealizadaVO();
		$this->idContratoItem['referencia'] =  new ContratoItemVO();
	}

	/*
	 * Funcion que valida cierta logica de negocios
	 */
	public function validarLogicasNegocio($operacion){
		return $resultMessage;
	}

	public function getComboList($data = null){
		$sql = 'select CONCAT("(", posicion, ")", item) as label, b.idActaTareaRealizadaContratoItem as data, b.idActaTareaRealizada as selected
				from contratosItems as a
				inner JOIN actaTareasRealizada_contratosItems as b on a.idContratoItem = b.idContratoItem ';
		if($data['valorCampoWhere'])
			$sql .= ' and b.'.$data['nombreCampoWhere'].' = '.$data['valorCampoWhere'];
		else
			$sql .= ' and b.'.$data['nombreCampoWhere'].' is null ';
		$sql .= ' group by data ';
		$sql .= ' order by label';
		//die($sql);
		try{
			$ro = $this->conn->prepare($sql);
			if($ro->execute()){
				$rs = $ro->fetchAll(PDO::FETCH_ASSOC);
				$this->result->setData($rs);
				$this->result->setStatus(STATUS_OK);
			}else{
				$this->result->setData($this);
				$this->result->setStatus(STATUS_ERROR);
				$this->result->setMessage('ERROR: Ocurrió un error al realizar la operación.\nReintente o contactese con el Administrador.');
			}
		}catch(Exception $e){
			$this->result->setData($this);
			$this->result->setStatus(STATUS_ERROR);
			$this->result->setMessage('ERROR: Ocurrió un error al realizar la operación.\nReintente o contactese con el Administrador.');
			myExceptionHandler($e);
		}
		return $this;
	}
}

// debug zone
if($_GET['debug'] == 'ActaTareaRealizadaContratoItemVO' or false){
	echo "DEBUG<br>";
	$kk = new ActaTareaRealizadaVO();
	//print_r($kk->getAllRows());
	$kk->idProyectoUnidadEconomica = 116;
	$kk->usuario = 'hhh2';
	//print_r($kk->getRowById());
	//print_r($kk->insertData());
	//print_r($kk->updateData());
	//print_r($kk->deleteData());
	//echo $kk->getResultMessage();
}


text:
const window  = require('global/window');
const slugify = require('slugificate');
const react   = require('react');

const dom = react.DOM;

const blocks = [
  'basics',
  'wercker.yml',
  'containers',
  'pipelines',
  'steps',
  'build',
  'deploy'
];

/**
 * Create class.
 */
module.exports = react.createClass({
  displayName: 'learnblocks',
  render: render
});

/**
 * Render.
 */
function render() {
  return dom.div({className: 'learnblocks'},
    blocks.map(function(block) {
      return dom.div({className: createClassName(block), key: block},
        dom.a({
          className: 'learnblocks-item-icon',
          href: '/learn/' + slugify(block) + '/index.html'
        }, dom.img({src: '/images/icon-' + block + '.svg', alt: block}),
          dom.div({className: 'learnblocks-item-title'}, block)
        )
      );
    })
  );
}

/**
 * Create className.
 *
 * @param {String} block
 */
function createClassName(block) {
  const head = window.location.pathname.split('/')[2];
  const active = (head == slugify(block));

  return 'learnblocks-item '
   + 'learnblocks-item_'
   + block.replace(/(\.)/gm, '_')
   + (active ? ' active' : '')
}


text:
"""Tests for Keras' base preprocessing layer."""

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

import json

from absl.testing import parameterized
import numpy as np

from tensorflow.python import keras

from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.eager import context
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.keras import keras_parameterized
from tensorflow.python.keras import testing_utils
from tensorflow.python.keras.engine import base_preprocessing_layer
from tensorflow.python.keras.engine import base_preprocessing_layer_v1
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import sparse_ops
from tensorflow.python.ops.ragged import ragged_factory_ops
from tensorflow.python.platform import test
from tensorflow.python.util import compat

# Define a test-only implementation of CombinerPreprocessingLayer to validate
# its correctness directly.
class AddingPreprocessingLayer(
    base_preprocessing_layer.CombinerPreprocessingLayer):
  _SUM_NAME = "sum"

  def __init__(self, **kwargs):
    super(AddingPreprocessingLayer, self).__init__(
        combiner=self.AddingCombiner(), **kwargs)

  def build(self, input_shape):
    super(AddingPreprocessingLayer, self).build(input_shape)
    self._sum = self._add_state_variable(
        name=self._SUM_NAME,
        shape=(1,),
        dtype=dtypes.float32,
        initializer=init_ops.zeros_initializer)

  def set_total(self, sum_value):
    """This is an example of how a subclass would implement a direct setter.

    These methods should generally just create a dict mapping the correct names
    to the relevant passed values, and call self._set_state_variables() with the
    dict of data.

    Args:
      sum_value: The total to set.
    """
    self._set_state_variables({self._SUM_NAME: [sum_value]})

  def call(self, inputs):
    return inputs + self._sum

  # Define a Combiner for this layer class.
  class AddingCombiner(base_preprocessing_layer.Combiner):

    def compute(self, batch_values, accumulator=None):
      """Compute a step in this computation, returning a new accumulator."""
      new_accumulator = 0 if batch_values is None else np.sum(batch_values)
      if accumulator is None:
        return new_accumulator
      else:
        return self.merge([accumulator, new_accumulator])

    def merge(self, accumulators):
      """Merge several accumulators to a single accumulator."""
      # Combine accumulators and return the result.
      result = accumulators[0]
      for accumulator in accumulators[1:]:
        result = np.sum([np.sum(result), np.sum(accumulator)])
      return result

    def extract(self, accumulator):
      """Convert an accumulator into a dict of output values."""
      # We have to add an additional dimension here because the weight shape
      # is (1,) not None.
      return {AddingPreprocessingLayer._SUM_NAME: [accumulator]}

    def restore(self, output):
      """Create an accumulator based on 'output'."""
      # There is no special internal state here, so we just return the relevant
      # internal value. We take the [0] value here because the weight itself
      # is of the shape (1,) and we want the scalar contained inside it.
      return output[AddingPreprocessingLayer._SUM_NAME][0]

    def serialize(self, accumulator):
      """Serialize an accumulator for a remote call."""
      return compat.as_bytes(json.dumps(accumulator))

    def deserialize(self, encoded_accumulator):
      """Deserialize an accumulator received from 'serialize()'."""
      return json.loads(compat.as_text(encoded_accumulator))

class AddingPreprocessingLayerV1(
    AddingPreprocessingLayer,
    base_preprocessing_layer_v1.CombinerPreprocessingLayer):
  pass

def get_layer():
  if context.executing_eagerly():
    return AddingPreprocessingLayer()
  else:
    return AddingPreprocessingLayerV1()

@keras_parameterized.run_all_keras_modes
class PreprocessingLayerTest(keras_parameterized.TestCase):

  def test_adapt_list_fails(self):
    """Test that non-Dataset/Numpy inputs cause a reasonable error."""
    input_dataset = [1, 2, 3, 4, 5]

    layer = get_layer()
    with self.assertRaisesRegex(ValueError, "requires a"):
      layer.adapt(input_dataset)

  def test_adapt_infinite_dataset_fails(self):
    """Test that preproc layers fail if an infinite dataset is passed."""
    input_dataset = dataset_ops.Dataset.from_tensor_slices(
        np.array([[1], [2], [3], [4], [5], [0]])).repeat()

    layer = get_layer()
    with self.assertRaisesRegex(ValueError, ".*infinite number of elements.*"):
      layer.adapt(input_dataset)

  def test_pre_build_injected_update_with_no_build_fails(self):
    """Test external update injection before build() is called fails."""
    input_dataset = np.array([1, 2, 3, 4, 5])

    layer = get_layer()
    combiner = layer._combiner
    updates = combiner.extract(combiner.compute(input_dataset))

    with self.assertRaisesRegex(RuntimeError, ".*called after build.*"):
      layer._set_state_variables(updates)

  def test_setter_update(self):
    """Test the prototyped setter method."""
    input_data = keras.Input(shape=(1,))
    layer = get_layer()
    output = layer(input_data)
    model = keras.Model(input_data, output)
    model._run_eagerly = testing_utils.should_run_eagerly()

    layer.set_total(15)

    self.assertAllEqual([[16], [17], [18]], model.predict([1., 2., 3.]))

  def test_pre_build_adapt_update_numpy(self):
    """Test that preproc layers can adapt() before build() is called."""
    input_dataset = np.array([1, 2, 3, 4, 5])

    layer = get_layer()
    layer.adapt(input_dataset)

    input_data = keras.Input(shape=(1,))
    output = layer(input_data)
    model = keras.Model(input_data, output)
    model._run_eagerly = testing_utils.should_run_eagerly()

    self.assertAllEqual([[16], [17], [18]], model.predict([1., 2., 3.]))

  def test_post_build_adapt_update_numpy(self):
    """Test that preproc layers can adapt() after build() is called."""
    input_dataset = np.array([1, 2, 3, 4, 5])

    input_data = keras.Input(shape=(1,))
    layer = get_layer()
    output = layer(input_data)
    model = keras.Model(input_data, output)
    model._run_eagerly = testing_utils.should_run_eagerly()

    layer.adapt(input_dataset)

    self.assertAllEqual([[16], [17], [18]], model.predict([1., 2., 3.]))

  def test_pre_build_injected_update(self):
    """Test external update injection before build() is called."""
    input_dataset = np.array([1, 2, 3, 4, 5])

    layer = get_layer()
    combiner = layer._combiner
    updates = combiner.extract(combiner.compute(input_dataset))

    layer.build((1,))
    layer._set_state_variables(updates)

    input_data = keras.Input(shape=(1,))
    output = layer(input_data)
    model = keras.Model(input_data, output)
    model._run_eagerly = testing_utils.should_run_eagerly()

    self.assertAllEqual([[16], [17], [18]], model.predict([1., 2., 3.]))

  def test_post_build_injected_update(self):
    """Test external update injection after build() is called."""
    input_dataset = np.array([1, 2, 3, 4, 5])
    input_data = keras.Input(shape=(1,))
    layer = get_layer()
    output = layer(input_data)
    model = keras.Model(input_data, output)
    model._run_eagerly = testing_utils.should_run_eagerly()

    combiner = layer._combiner
    updates = combiner.extract(combiner.compute(input_dataset))
    layer._set_state_variables(updates)

    self.assertAllEqual([[16], [17], [18]], model.predict([1., 2., 3.]))

  def test_pre_build_adapt_update_dataset(self):
    """Test that preproc layers can adapt() before build() is called."""
    input_dataset = dataset_ops.Dataset.from_tensor_slices(
        np.array([[1], [2], [3], [4], [5], [0]]))

    layer = get_layer()
    layer.adapt(input_dataset)

    input_data = keras.Input(shape=(1,))
    output = layer(input_data)
    model = keras.Model(input_data, output)
    model._run_eagerly = testing_utils.should_run_eagerly()

    self.assertAllEqual([[16], [17], [18]], model.predict([1., 2., 3.]))

  def test_post_build_adapt_update_dataset(self):
    """Test that preproc layers can adapt() after build() is called."""
    input_dataset = dataset_ops.Dataset.from_tensor_slices(
        np.array([[1], [2], [3], [4], [5], [0]]))

    input_data = keras.Input(shape=(1,))
    layer = get_layer()
    output = layer(input_data)
    model = keras.Model(input_data, output)
    model._run_eagerly = testing_utils.should_run_eagerly()

    layer.adapt(input_dataset)

    self.assertAllEqual([[16], [17], [18]], model.predict([1., 2., 3.]))

  def test_further_tuning(self):
    """Test that models can be tuned with multiple calls to 'adapt'."""

    input_dataset = np.array([1, 2, 3, 4, 5])

    layer = get_layer()
    layer.adapt(input_dataset)

    input_data = keras.Input(shape=(1,))
    output = layer(input_data)
    model = keras.Model(input_data, output)
    model._run_eagerly = testing_utils.should_run_eagerly()

    self.assertAllEqual([[16], [17], [18]], model.predict([1., 2., 3.]))

    layer.adapt(np.array([1, 2]), reset_state=False)
    self.assertAllEqual([[19], [20], [21]], model.predict([1., 2., 3.]))

  def test_further_tuning_post_injection(self):
    """Test that models can be tuned with multiple calls to 'adapt'."""

    input_dataset = np.array([1, 2, 3, 4, 5])

    layer = get_layer()

    input_data = keras.Input(shape=(1,))
    output = layer(input_data)
    model = keras.Model(input_data, output)
    model._run_eagerly = testing_utils.should_run_eagerly()

    combiner = layer._combiner
    updates = combiner.extract(combiner.compute(input_dataset))
    layer._set_state_variables(updates)
    self.assertAllEqual([[16], [17], [18]], model.predict([1., 2., 3.]))

    layer.adapt(np.array([1, 2]), reset_state=False)
    self.assertAllEqual([[19], [20], [21]], model.predict([1., 2., 3.]))

  def test_weight_based_state_transfer(self):
    """Test that preproc layers can transfer state via get/set weights.."""

    def get_model():
      input_data = keras.Input(shape=(1,))
      layer = get_layer()
      output = layer(input_data)
      model = keras.Model(input_data, output)
      model._run_eagerly = testing_utils.should_run_eagerly()
      return (model, layer)

    input_dataset = np.array([1, 2, 3, 4, 5])
    model, layer = get_model()
    layer.adapt(input_dataset)
    self.assertAllEqual([[16], [17], [18]], model.predict([1., 2., 3.]))

    # Create a new model and verify it has no state carryover.
    weights = model.get_weights()
    model_2, _ = get_model()
    self.assertAllEqual([[1], [2], [3]], model_2.predict([1., 2., 3.]))

    # Transfer state from model to model_2 via get/set weights.
    model_2.set_weights(weights)
    self.assertAllEqual([[16], [17], [18]], model_2.predict([1., 2., 3.]))

  def test_weight_based_state_transfer_with_further_tuning(self):
    """Test that transferred state can be used to further tune a model.."""

    def get_model():
      input_data = keras.Input(shape=(1,))
      layer = get_layer()
      output = layer(input_data)
      model = keras.Model(input_data, output)
      model._run_eagerly = testing_utils.should_run_eagerly()
      return (model, layer)

    input_dataset = np.array([1, 2, 3, 4, 5])
    model, layer = get_model()
    layer.adapt(input_dataset)
    self.assertAllEqual([[16], [17], [18]], model.predict([1., 2., 3.]))

    # Transfer state from model to model_2 via get/set weights.
    weights = model.get_weights()
    model_2, layer_2 = get_model()
    model_2.set_weights(weights)

    # Further adapt this layer based on the transferred weights.
    layer_2.adapt(np.array([1, 2]), reset_state=False)
    self.assertAllEqual([[19], [20], [21]], model_2.predict([1., 2., 3.]))

@keras_parameterized.run_all_keras_modes
class ConvertToListTest(keras_parameterized.TestCase):

  # Note: We need the inputs to be lambdas below to avoid some strangeness with
  # TF1.x graph mode - specifically, if the inputs are created outside the test
  # function body, the graph inside the test body will not contain the tensors
  # that were created in the parameters.
  @parameterized.named_parameters(
      {
          "testcase_name": "ndarray",
          "inputs": lambda: np.array([[1, 2, 3], [4, 5, 6]]),
          "expected": [[1, 2, 3], [4, 5, 6]]
      }, {
          "testcase_name": "list",
          "inputs": lambda: [[1, 2, 3], [4, 5, 6]],
          "expected": [[1, 2, 3], [4, 5, 6]]
      }, {
          "testcase_name": "tensor",
          "inputs": lambda: constant_op.constant([[1, 2, 3], [4, 5, 6]]),
          "expected": [[1, 2, 3], [4, 5, 6]]
      }, {
          "testcase_name":
              "ragged_tensor",
          "inputs":
              lambda: ragged_factory_ops.constant([[1, 2, 3, 4], [4, 5, 6]]),
          "expected": [[1, 2, 3, 4], [4, 5, 6]]
      }, {
          "testcase_name": "sparse_tensor",
          "inputs": lambda: sparse_ops.from_dense([[1, 2, 0, 4], [4, 5, 6, 0]]),
          "expected": [[1, 2, -1, 4], [4, 5, 6, -1]]
      })
  def test_conversion(self, inputs, expected):
    values = base_preprocessing_layer.convert_to_list(inputs())
    self.assertAllEqual(expected, values)

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


text:
import os
import shutil
import sys
import tempfile
import time
from datetime import datetime, timedelta
try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

try:
    import threading
except ImportError:
    import dummy_threading as threading

from django.conf import settings
from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured
from django.core.files.base import ContentFile, File
from django.core.files.images import get_image_dimensions
from django.core.files.storage import FileSystemStorage, get_storage_class
from django.core.files.uploadedfile import UploadedFile
from django.utils import unittest

# Try to import PIL in either of the two ways it can end up installed.
# Checking for the existence of Image is enough for CPython, but
# for PyPy, you need to check for the underlying modules
try:
    from PIL import Image, _imaging
except ImportError:
    try:
        import Image, _imaging
    except ImportError:
        Image = None

class GetStorageClassTests(unittest.TestCase):
    def assertRaisesErrorWithMessage(self, error, message, callable,
        *args, **kwargs):
        self.assertRaises(error, callable, *args, **kwargs)
        try:
            callable(*args, **kwargs)
        except error, e:
            self.assertEqual(message, str(e))

    def test_get_filesystem_storage(self):
        """
        get_storage_class returns the class for a storage backend name/path.
        """
        self.assertEqual(
            get_storage_class('django.core.files.storage.FileSystemStorage'),
            FileSystemStorage)

    def test_get_invalid_storage_module(self):
        """
        get_storage_class raises an error if the requested import don't exist.
        """
        self.assertRaisesErrorWithMessage(
            ImproperlyConfigured,
            "NonExistingStorage isn't a storage module.",
            get_storage_class,
            'NonExistingStorage')

    def test_get_nonexisting_storage_class(self):
        """
        get_storage_class raises an error if the requested class don't exist.
        """
        self.assertRaisesErrorWithMessage(
            ImproperlyConfigured,
            'Storage module "django.core.files.storage" does not define a '\
                '"NonExistingStorage" class.',
            get_storage_class,
            'django.core.files.storage.NonExistingStorage')

    def test_get_nonexisting_storage_module(self):
        """
        get_storage_class raises an error if the requested module don't exist.
        """
        # Error message may or may not be the fully qualified path.
        self.assertRaisesRegexp(
            ImproperlyConfigured,
            ('Error importing storage module django.core.files.non_existing_'
                'storage: "No module named .*non_existing_storage"'),
            get_storage_class,
            'django.core.files.non_existing_storage.NonExistingStorage'
        )

class FileStorageTests(unittest.TestCase):
    storage_class = FileSystemStorage

    def setUp(self):
        self.temp_dir = tempfile.mktemp()
        os.makedirs(self.temp_dir)
        self.storage = self.storage_class(location=self.temp_dir,
            base_url='/test_media_url/')

    def tearDown(self):
        shutil.rmtree(self.temp_dir)

    def test_file_access_options(self):
        """
        Standard file access options are available, and work as expected.
        """
        self.assertFalse(self.storage.exists('storage_test'))
        f = self.storage.open('storage_test', 'w')
        f.write('storage contents')
        f.close()
        self.assertTrue(self.storage.exists('storage_test'))

        f = self.storage.open('storage_test', 'r')
        self.assertEqual(f.read(), 'storage contents')
        f.close()

        self.storage.delete('storage_test')
        self.assertFalse(self.storage.exists('storage_test'))

    def test_file_accessed_time(self):
        """
        File storage returns a Datetime object for the last accessed time of
        a file.
        """
        self.assertFalse(self.storage.exists('test.file'))

        f = ContentFile('custom contents')
        f_name = self.storage.save('test.file', f)
        atime = self.storage.accessed_time(f_name)

        self.assertEqual(atime, datetime.fromtimestamp(
            os.path.getatime(self.storage.path(f_name))))
        self.assertTrue(datetime.now() - self.storage.accessed_time(f_name) < timedelta(seconds=2))
        self.storage.delete(f_name)

    def test_file_created_time(self):
        """
        File storage returns a Datetime object for the creation time of
        a file.
        """
        self.assertFalse(self.storage.exists('test.file'))

        f = ContentFile('custom contents')
        f_name = self.storage.save('test.file', f)
        ctime = self.storage.created_time(f_name)

        self.assertEqual(ctime, datetime.fromtimestamp(
            os.path.getctime(self.storage.path(f_name))))
        self.assertTrue(datetime.now() - self.storage.created_time(f_name) < timedelta(seconds=2))

        self.storage.delete(f_name)

    def test_file_modified_time(self):
        """
        File storage returns a Datetime object for the last modified time of
        a file.
        """
        self.assertFalse(self.storage.exists('test.file'))

        f = ContentFile('custom contents')
        f_name = self.storage.save('test.file', f)
        mtime = self.storage.modified_time(f_name)

        self.assertEqual(mtime, datetime.fromtimestamp(
            os.path.getmtime(self.storage.path(f_name))))
        self.assertTrue(datetime.now() - self.storage.modified_time(f_name) < timedelta(seconds=2))

        self.storage.delete(f_name)

    def test_file_save_without_name(self):
        """
        File storage extracts the filename from the content object if no
        name is given explicitly.
        """
        self.assertFalse(self.storage.exists('test.file'))

        f = ContentFile('custom contents')
        f.name = 'test.file'

        storage_f_name = self.storage.save(None, f)

        self.assertEqual(storage_f_name, f.name)

        self.assertTrue(os.path.exists(os.path.join(self.temp_dir, f.name)))

        self.storage.delete(storage_f_name)

    def test_file_path(self):
        """
        File storage returns the full path of a file
        """
        self.assertFalse(self.storage.exists('test.file'))

        f = ContentFile('custom contents')
        f_name = self.storage.save('test.file', f)

        self.assertEqual(self.storage.path(f_name),
            os.path.join(self.temp_dir, f_name))

        self.storage.delete(f_name)

    def test_file_url(self):
        """
        File storage returns a url to access a given file from the Web.
        """
        self.assertEqual(self.storage.url('test.file'),
            '%s%s' % (self.storage.base_url, 'test.file'))

        # should encode special chars except ~!*()'
        # like encodeURIComponent() JavaScript function do
        self.assertEqual(self.storage.url(r"""~!*()'@#$%^&*abc`+=.file"""),
            """/test_media_url/~!*()'%40%23%24%25%5E%26*abc%60%2B%3D.file""")

        # should stanslate os path separator(s) to the url path separator
        self.assertEqual(self.storage.url("""a/b\\c.file"""),
            """/test_media_url/a/b/c.file""")

        self.storage.base_url = None
        self.assertRaises(ValueError, self.storage.url, 'test.file')

    def test_file_with_mixin(self):
        """
        File storage can get a mixin to extend the functionality of the
        returned file.
        """
        self.assertFalse(self.storage.exists('test.file'))

        class TestFileMixin(object):
            mixed_in = True

        f = ContentFile('custom contents')
        f_name = self.storage.save('test.file', f)

        self.assertTrue(isinstance(
            self.storage.open('test.file', mixin=TestFileMixin),
            TestFileMixin
        ))

        self.storage.delete('test.file')

    def test_listdir(self):
        """
        File storage returns a tuple containing directories and files.
        """
        self.assertFalse(self.storage.exists('storage_test_1'))
        self.assertFalse(self.storage.exists('storage_test_2'))
        self.assertFalse(self.storage.exists('storage_dir_1'))

        f = self.storage.save('storage_test_1', ContentFile('custom content'))
        f = self.storage.save('storage_test_2', ContentFile('custom content'))
        os.mkdir(os.path.join(self.temp_dir, 'storage_dir_1'))

        dirs, files = self.storage.listdir('')
        self.assertEqual(set(dirs), set([u'storage_dir_1']))
        self.assertEqual(set(files),
                         set([u'storage_test_1', u'storage_test_2']))

        self.storage.delete('storage_test_1')
        self.storage.delete('storage_test_2')
        os.rmdir(os.path.join(self.temp_dir, 'storage_dir_1'))

    def test_file_storage_prevents_directory_traversal(self):
        """
        File storage prevents directory traversal (files can only be accessed if
        they're below the storage location).
        """
        self.assertRaises(SuspiciousOperation, self.storage.exists, '..')
        self.assertRaises(SuspiciousOperation, self.storage.exists, '/etc/passwd')

class CustomStorage(FileSystemStorage):
    def get_available_name(self, name):
        """
        Append numbers to duplicate files rather than underscores, like Trac.
        """
        parts = name.split('.')
        basename, ext = parts[0], parts[1:]
        number = 2
        while self.exists(name):
            name = '.'.join([basename, str(number)] + ext)
            number += 1

        return name

class CustomStorageTests(FileStorageTests):
    storage_class = CustomStorage

    def test_custom_get_available_name(self):
        first = self.storage.save('custom_storage', ContentFile('custom contents'))
        self.assertEqual(first, 'custom_storage')
        second = self.storage.save('custom_storage', ContentFile('more contents'))
        self.assertEqual(second, 'custom_storage.2')
        self.storage.delete(first)
        self.storage.delete(second)

class UnicodeFileNameTests(unittest.TestCase):
    def test_unicode_file_names(self):
        """
        Regression test for #8156: files with unicode names I can't quite figure
        out the encoding situation between doctest and this file, but the actual
        repr doesn't matter; it just shouldn't return a unicode object.
        """
        uf = UploadedFile(name=u'¿Cómo?',content_type='text')
        self.assertEqual(type(uf.__repr__()), str)

# Tests for a race condition on file saving (#4948).
# This is written in such a way that it'll always pass on platforms
# without threading.

class SlowFile(ContentFile):
    def chunks(self):
        time.sleep(1)
        return super(ContentFile, self).chunks()

class FileSaveRaceConditionTest(unittest.TestCase):
    def setUp(self):
        self.storage_dir = tempfile.mkdtemp()
        self.storage = FileSystemStorage(self.storage_dir)
        self.thread = threading.Thread(target=self.save_file, args=['conflict'])

    def tearDown(self):
        shutil.rmtree(self.storage_dir)

    def save_file(self, name):
        name = self.storage.save(name, SlowFile("Data"))

    def test_race_condition(self):
        self.thread.start()
        name = self.save_file('conflict')
        self.thread.join()
        self.assertTrue(self.storage.exists('conflict'))
        self.assertTrue(self.storage.exists('conflict_1'))
        self.storage.delete('conflict')
        self.storage.delete('conflict_1')

class FileStoragePermissions(unittest.TestCase):
    def setUp(self):
        self.old_perms = settings.FILE_UPLOAD_PERMISSIONS
        settings.FILE_UPLOAD_PERMISSIONS = 0666
        self.storage_dir = tempfile.mkdtemp()
        self.storage = FileSystemStorage(self.storage_dir)

    def tearDown(self):
        settings.FILE_UPLOAD_PERMISSIONS = self.old_perms
        shutil.rmtree(self.storage_dir)

    def test_file_upload_permissions(self):
        name = self.storage.save("the_file", ContentFile("data"))
        actual_mode = os.stat(self.storage.path(name))[0] & 0777
        self.assertEqual(actual_mode, 0666)

class FileStoragePathParsing(unittest.TestCase):
    def setUp(self):
        self.storage_dir = tempfile.mkdtemp()
        self.storage = FileSystemStorage(self.storage_dir)

    def tearDown(self):
        shutil.rmtree(self.storage_dir)

    def test_directory_with_dot(self):
        """Regression test for #9610.

        If the directory name contains a dot and the file name doesn't, make
        sure we still mangle the file name instead of the directory name.
        """

        self.storage.save('dotted.path/test', ContentFile("1"))
        self.storage.save('dotted.path/test', ContentFile("2"))

        self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path')))
        self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test')))
        self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test_1')))

    def test_first_character_dot(self):
        """
        File names with a dot as their first character don't have an extension,
        and the underscore should get added to the end.
        """
        self.storage.save('dotted.path/.test', ContentFile("1"))
        self.storage.save('dotted.path/.test', ContentFile("2"))

        self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test')))
        # Before 2.6, a leading dot was treated as an extension, and so
        # underscore gets added to beginning instead of end.
        if sys.version_info < (2, 6):
            self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/_1.test')))
        else:
            self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_1')))

class DimensionClosingBug(unittest.TestCase):
    """
    Test that get_image_dimensions() properly closes files (#8817)
    """
    @unittest.skipUnless(Image, "PIL not installed")
    def test_not_closing_of_files(self):
        """
        Open files passed into get_image_dimensions() should stay opened.
        """
        empty_io = StringIO()
        try:
            get_image_dimensions(empty_io)
        finally:
            self.assertTrue(not empty_io.closed)

    @unittest.skipUnless(Image, "PIL not installed")
    def test_closing_of_filenames(self):
        """
        get_image_dimensions() called with a filename should closed the file.
        """
        # We need to inject a modified open() builtin into the images module
        # that checks if the file was closed properly if the function is
        # called with a filename instead of an file object.
        # get_image_dimensions will call our catching_open instead of the
        # regular builtin one.

        class FileWrapper(object):
            _closed = []
            def __init__(self, f):
                self.f = f
            def __getattr__(self, name):
                return getattr(self.f, name)
            def close(self):
                self._closed.append(True)
                self.f.close()

        def catching_open(*args):
            return FileWrapper(open(*args))

        from django.core.files import images
        images.open = catching_open
        try:
            get_image_dimensions(os.path.join(os.path.dirname(__file__), "test1.png"))
        finally:
            del images.open
        self.assertTrue(FileWrapper._closed)

class InconsistentGetImageDimensionsBug(unittest.TestCase):
    """
    Test that get_image_dimensions() works properly after various calls
    using a file handler (#11158)
    """
    @unittest.skipUnless(Image, "PIL not installed")
    def test_multiple_calls(self):
        """
        Multiple calls of get_image_dimensions() should return the same size.
        """
        from django.core.files.images import ImageFile

        img_path = os.path.join(os.path.dirname(__file__), "test.png")
        image = ImageFile(open(img_path, 'rb'))
        image_pil = Image.open(img_path)
        size_1, size_2 = get_image_dimensions(image), get_image_dimensions(image)
        self.assertEqual(image_pil.size, size_1)
        self.assertEqual(size_1, size_2)


text:
import Emitter = require('component-emitter');
import { SCServer } from 'socketcluster-server';
import { SCAuthEngine } from 'sc-auth';
import { SocketProtocolIgnoreStatuses, SocketProtocolErrorStatuses } from 'sc-errors';
import { SCChannel } from 'sc-channel';
import WebSocket = require('ws');

declare class SCClientSocket extends Emitter {
    constructor(opts: SCClientSocket.ClientOptions);

    id: string;
    clientId: string;

    channels: {
        [channelName: string]: SCChannel;
    };

    readonly CONNECTING: 'connecting';
    readonly OPEN: 'open';
    readonly CLOSED: 'closed';

    state: SCClientSocket.States;
    getState(): SCClientSocket.States;

    readonly AUTHENTICATED: 'authenticated';
    readonly UNAUTHENTICATED: 'unauthenticated';

    authState: SCClientSocket.AuthStates;

    readonly PENDING: 'pending';

    pendingReconnect: boolean;
    pendingReconnectTimeout: number;

    ackTimeout: number;
    connectTimeout: number;

    pingTimeout: number;
    pingTimeoutDisabled: boolean;

    channelPrefix: string | null;
    disconnectOnUnload: boolean;

    authTokenName: string;

    connectAttempts: number;

    options: SCClientSocket.ClientOptions;

    authEngine: SCAuthEngine;
    codecEngine: SCServer.SCCodecEngine;

    readonly ignoreStatuses: SocketProtocolIgnoreStatuses;
    readonly errorStatuses: SocketProtocolErrorStatuses;

    getBytesReceived(): number;

    deauthenticate(callback?: (err: Error) => void): void;

    connect(): void;
    open(): void;
    disconnect(code?: number, data?: string | object): void;
    reconnect(code?: number, data?: string | object): void;
    destroy(code?: number, data?: string | object): void;

    decodeBase64(encodedString: string): string;
    encodeBase64(decodedString: string): string;

    getAuthToken(): object | null;
    authToken: object | null;

    getSignedAuthToken(): string | null;
    signedAuthToken: string | null;

    // Perform client-initiated authentication by providing an encrypted token string.
    authenticate(signedAuthToken: string, callback?: (err: Error, authStatus: SCClientSocket.AuthStatus) => void): void;

    decode(message: any): any;
    encode(object: any): any;

    send(data: any): void;

    emit(event: string, ...args: any[]): this;
    emit(event: string, data: any, callback?: (err: Error, responseData: any) => void): void;

    publish(channelName: string, data: any, callback?: (err: Error, ackData: any) => void): void;

    subscribe(channelName: string, options?: SCChannel.SCChannelOptions): SCChannel;
    unsubscribe(channelName: string): void;

    channel(channelName: string, options?: SCChannel.SCChannelOptions): SCChannel;

    destroyChannel(channelName: string): void;

    subscriptions(includePending?: boolean): string[];
    isSubscribed(channelName: string, includePending?: boolean): boolean;

    processPendingSubscriptions(): void;

    watch(channelName: string, handler: SCClientSocket.WatcherFunction): void;
    unwatch(channelName: string, handler?: SCClientSocket.WatcherFunction): void;
    watchers(channelName: string): SCClientSocket.WatcherFunction[];

    on(event: string, listener: SCClientSocket.AnyFunction): this;
    on(event: 'connecting', listener: () => void): this;
    on(
        event: 'connect',
        listener: (status: SCClientSocket.ConnectStatus, processSubscriptions: () => void) => void,
    ): this;
    on(event: 'connectAbort' | 'disconnect' | 'close', listener: (code: number, data: string | object) => void): this;
    on(event: 'kickOut', listener: (message: string, channelName: string) => void): this;
    on(event: 'authenticate', listener: (signedAuthToken: string | null) => void): this;
    on(event: 'deauthenticate', listener: (oldSignedToken: string | null) => void): this;
    on(event: 'authStateChange', listener: (stateChangeData: SCClientSocket.AuthStateChangeData) => void): this;
    on(event: 'removeAuthToken', listener: (oldToken: object | null) => void): this;
    on(
        event: 'subscribe' | 'subscribeRequest',
        listener: (channelName: string, subscriptionOptions: SCChannel.SCChannelOptions) => void,
    ): this;
    on(
        event: 'subscribeStateChange',
        listener: (stateChangeData: SCClientSocket.SubscribeStateChangeData) => void,
    ): this;
    on(
        event: 'subscribeFail',
        listener: (err: Error, channelName: string, subscriptionOptions: SCChannel.SCChannelOptions) => void,
    ): this;
    on(event: 'unsubscribe', listener: (channelName: string) => void): this;
    on(event: 'error', listener: (err: Error) => void): this;
    on(event: 'raw', listener: (data: any) => void): this;
    on(event: 'message', listener: (message: WebSocket.Data) => void): this;

    once(event: string, listener: SCClientSocket.AnyFunction): this;
    once(event: 'connecting', listener: () => void): this;
    once(
        event: 'connect',
        listener: (status: SCClientSocket.ConnectStatus, processSubscriptions: () => void) => void,
    ): this;
    once(event: 'connectAbort' | 'disconnect' | 'close', listener: (code: number, data: string | object) => void): this;
    once(event: 'kickOut', listener: (message: string, channelName: string) => void): this;
    once(event: 'authenticate', listener: (signedAuthToken: string | null) => void): this;
    once(event: 'deauthenticate', listener: (oldSignedToken: string | null) => void): this;
    once(event: 'authStateChange', listener: (stateChangeData: SCClientSocket.AuthStateChangeData) => void): this;
    once(event: 'removeAuthToken', listener: (oldToken: object | null) => void): this;
    once(
        event: 'subscribe' | 'subscribeRequest',
        listener: (channelName: string, subscriptionOptions: SCChannel.SCChannelOptions) => void,
    ): this;
    once(
        event: 'subscribeStateChange',
        listener: (stateChangeData: SCClientSocket.SubscribeStateChangeData) => void,
    ): this;
    once(
        event: 'subscribeFail',
        listener: (err: Error, channelName: string, subscriptionOptions: SCChannel.SCChannelOptions) => void,
    ): this;
    once(event: 'unsubscribe', listener: (channelName: string) => void): this;
    once(event: 'error', listener: (err: Error) => void): this;
    once(event: 'raw', listener: (data: any) => void): this;
    once(event: 'message', listener: (message: WebSocket.Data) => void): this;

    off(event?: string, listener?: SCClientSocket.AnyFunction): this;
    off(event: 'connecting', listener?: () => void): this;
    off(
        event: 'connect',
        listener?: (status: SCClientSocket.ConnectStatus, processSubscriptions: () => void) => void,
    ): this;
    off(event: 'connectAbort' | 'disconnect' | 'close', listener?: (code: number, data: string | object) => void): this;
    off(event: 'kickOut', listener?: (message: string, channelName: string) => void): this;
    off(event: 'authenticate', listener?: (signedAuthToken: string | null) => void): this;
    off(event: 'deauthenticate', listener?: (oldSignedToken: string | null) => void): this;
    off(event: 'authStateChange', listener?: (stateChangeData: SCClientSocket.AuthStateChangeData) => void): this;
    off(event: 'removeAuthToken', listener?: (oldToken: object | null) => void): this;
    off(
        event: 'subscribe' | 'subscribeRequest',
        listener?: (channelName: string, subscriptionOptions: SCChannel.SCChannelOptions) => void,
    ): this;
    off(
        event: 'subscribeStateChange',
        listener?: (stateChangeData: SCClientSocket.SubscribeStateChangeData) => void,
    ): this;
    off(
        event: 'subscribeFail',
        listener?: (err: Error, channelName: string, subscriptionOptions: SCChannel.SCChannelOptions) => void,
    ): this;
    off(event: 'unsubscribe', listener?: (channelName: string) => void): this;
    off(event: 'error', listener?: (err: Error) => void): this;
    off(event: 'raw', listener?: (data: any) => void): this;
    off(event: 'message', listener?: (message: WebSocket.Data) => void): this;
}

export = SCClientSocket;

declare namespace SCClientSocket {
    type AnyFunction = (...args: any[]) => any;

    interface ClientOptions {
        host?: string | undefined;

        // Defaults to the current host (read from the URL).
        hostname?: string | undefined;

        // Defaults to false.
        secure?: boolean | undefined;

        // Defaults to 80 if !secure otherwise defaults to 443.
        port?: number | undefined;

        // The URL which SC uses to make the initial handshake for the WebSocket. Defaults to '/socketcluster/'.
        path?: string | undefined;

        // A map of key-value pairs which will be used as query parameters for the initial HTTP handshake which will initiate the WebSocket connection.
        query?: string | { [key: string]: string } | undefined;

        // (milliseconds) - This is the timeout for getting a response to a SCSocket emit event (when a callback is provided).
        ackTimeout?: number | undefined;

        // (milliseconds)
        connectTimeout?: number | undefined;

        // Whether or not to automatically connect the socket as soon as it is created. Default is true.
        autoConnect?: boolean | undefined;

        // Whether or not to automatically reconnect the socket when it loses the connection.
        autoReconnect?: boolean | undefined;

        // Valid properties are: initialDelay (milliseconds), randomness (milliseconds), multiplier (decimal; default is 1.5) and maxDelay (milliseconds).
        autoReconnectOptions?: AutoReconnectOptions | undefined;

        // Whether or not a client automatically disconnects on page unload. If enabled, the client will disconnect when a user navigates away from the page.
        // This can happen when a user closes the tab/window, clicks a link to leave the page, or types a new URL into the address bar. Defaults to true.
        disconnectOnUnload?: boolean | undefined;

        // Turn on/off per-message deflate compression. If this is true, you need to make sure that this property is also set to true on the server-side.
        //  Note that this option is only relevant when running the client from Node.js. Most modern browsers will automatically use perMessageDeflate so
        // you only need to turn it on from the server-side.
        perMessageDeflate?: boolean | undefined;

        // Defaults to true; multiplexing allows you to reuse a socket instead of creating a second socket to the same address.
        multiplex?: boolean | undefined;

        // Defaults to null (0 milliseconds); this property affects channel subscription batching; it determines the period in milliseconds for batching
        // multiple subscription requests together. It only affects channels that have the batch option set to true. A value of null or 0 means that all
        // subscribe or unsubscribe requests which were made within the same call stack will be batched together. This property was introduced on the
        // client-side in SC version 8 (both the client and server versions need to be >= 8.0.0). Note that there is also a separate property with the
        // same name which can be configured on the server.
        pubSubBatchDuration?: number | undefined;

        // Whether or not to add a timestamp to the WebSocket handshake request.
        timestampRequests?: boolean | undefined;

        // The query parameter name to use to hold the timestamp.
        timestampParam?: string | undefined;

        // A custom engine to use for storing and loading JWT auth tokens on the client side.
        authEngine?: SCAuthEngine | null | undefined;

        // The name of the JWT auth token (provided to the authEngine - By default this is the localStorage variable name); defaults to 'socketCluster.authToken'.
        authTokenName?: string | undefined;

        // The type to use to represent binary on the client. Defaults to 'arraybuffer'.
        binaryType?: string | undefined;

        // Set this to false during debugging - Otherwise client connection will fail when using self-signed certificates.
        rejectUnauthorized?: boolean | undefined;

        // If you set this to true, any data/objects/arrays that you pass to the client socket will be cloned before being sent/queued up. If the socket
        // is disconnected and you emit an event, it will be added to a queue which will be processed upon reconnection. The cloneData option is false
        // by default; this means that if you emit/publish an object and that object changes somewhere else in your code before the queue is processed,
        // then the changed version of that object will be sent out to the server.
        cloneData?: boolean | undefined;

        // This is true by default. If you set this to false, then the socket will not automatically try to subscribe to pending subscriptions on
        // connect - Instead, you will have to manually invoke the processSubscriptions callback from inside the 'connect' event handler on the client side.
        // See SCSocket Client API. This gives you more fine-grained control with regards to when pending subscriptions are processed after the socket
        // connection is established (or re-established).
        autoSubscribeOnConnect?: boolean | undefined;

        // Lets you set a custom codec engine. This allows you to specify how data gets encoded before being sent over the wire and how it gets decoded
        // once it reaches the other side. The codecEngine must be an object which exposes an encode(object) and a decode(encodedData) function.
        // The encode function can return any data type - Commonly a string or a Buffer/ArrayBuffer. The decode function needs to return a JavaScript
        // object which adheres to the SC protocol. The idea of using a custom codec is that it allows you to compress SC packets in any format you like
        // (optimized for any use case) - By decoding these packets back into their original protocol form, SC will be able process them appropriately.
        // Note that if you provide a codecEngine when creating a client socket see 'codecEngine', you will need to make sure that the server uses the
        // same codec by passing the same engine to `worker.scServer.setCodecEngine(codecEngine)` when your SC worker initializes on the server side
        // (see 'setCodecEngine' method here). The default codec engine used by SC is here.
        codecEngine?: SCServer.SCCodecEngine | null | undefined;

        // A prefix to add to the channel names.
        channelPrefix?: string | null | undefined;

        subscriptionRetryOptions?: object | null | undefined;
    }

    interface AutoReconnectOptions {
        initialDelay?: number | undefined;
        randomness?: number | undefined;
        multiplier?: number | undefined;
        maxDelay?: number | undefined;
    }

    interface AuthStatus {
        isAuthenticated: AuthStates;
        authError: Error;
    }

    interface AuthStateChangeData {
        oldState: AuthStates;
        newState: AuthStates;
    }

    interface ConnectStatus {
        id: string;
        pingTimeout: number;
        isAuthenticated: boolean;
        authToken?: object | undefined;
        authError?: Error | undefined;
    }

    interface SubscribeStateChangeData {
        channel: string;
        oldState: SCChannel.ChannelState;
        newState: SCChannel.ChannelState;
        subscriptionOptions: SCChannel.SCChannelOptions;
    }

    type WatcherFunction = (data: any) => void;
    type AuthStates = 'authenticated' | 'unauthenticated';
    type States = 'connecting' | 'open' | 'closed';
}


text:
C++ library to help you handle dates from the Gregorian Calendar. Programming with dates should be almost as simple and easy as programming with strings and integers. Applications with lots of date-time related computations can be simplified significantly by having a robust set of operators and calculation capabilities.

## dateformat Functionalities

The `dateformat` class defines the format in which a date is output or input.

### Accepted Date Formats:

#### Date Formats:
* **`"0"`**: No date provided. For output only.
* **`"d"`**: Single digit date in one digit *(9)*, Double Digit date in two digits *(25)*.
* **`"dd"`**: All dates in two digits. Single digit dates with leading 0 *(09, 25)*.

#### Month Format:
* **`"0"`**: Full names of months *(February, November)*. For output only.
* **`"m"`**: Single digit month in one digit *(2)*, Double Digit month in two digits *(11)*.
* **`"mm"`**: All months in two digits. Single digit months with leading 0 *(02, 11)*.
* **`"mmm"`**: First three letters of month name *(Feb, Nov)*. For output only.

#### Year Format:
* **`"0"`**: No year provided. For output only.
* **`"yy"`**: Year in last two digits *(61, 16)*.
* **`"yyyy"`**: Year in four digits *(1961, 2016)*.

### Constructors

* `DateFormat (const char* dateFormat, const char* monthFormat, const char* yearFormat)` - Three C-strings format with Date Format, Month Format, and Year Format provided. `DateFormat format ("d", "mm", "yyyy")`.

* `DateFormat (const char* format)` - Single C-string format where Date Format, Month Format, and Year Format are separated by '-'. `DateFormat format ("d-mm-yyyy")`.

* `DateFormat ()` - Creates default `DateFormat` - "dd-mmm-yy".

### Methods

* `char* get_dateFormat () const` - Get Date Format.
* `char* get_monthFormat () const` - Get Month Format.
* `char* get_yearFormat () const` - Get Year Format.

### Usage with `date` Class

To define the format in which `Date` objects are input and output, set the value of the static `format` member as follows:

```cpp
DateFormat form ("dd-mm-yyyy");
Date::setFormat (form);
```

## date Functionalities

The `date` class gives functionalities to use dates and perform operation on them, in C++ programs.

### Date Data Types

* `Day` - `DXX` representing the XXth Day of the Month, (`D28`, 28th), (`D01`, 1st).
* `Month` - `MXX` representing the XXth Month of the Year, (`M09`, September).
* `Year` - Unsigned Integer values.
* `WeekDay` - `Mon` representing Monday.
* `WeekNumber` - `WXX` representing the XXth Week of the Year, (`W34`, Week Number 34).

### Constructors

* `Date (Day d, Month m, Year y)` - Construct a Date from (d, m, y) values.
* `Date (const char* date)` - Date in string format - parsed as specified by static `format` member.
* `Date ()` - Default Constructor - construct Today's date.
* `Date (const Date&)` - Copy Constructor.

### Methods

#### Arithmetic Operators

```cpp
Date example_date (D25, M05, 2015);
```

* `Date& operator++ ()` - Next day (`++example_date` gives 26th March, 2015).
* `Date& operator++ (int)` -  Same day next week (`example_date++` gives 1st April, 2015).
* `Date& operator-- ()` - Previous day (`--example_date` gives 24th March, 2015).
* `Date& operator-- (int)` - Same day previous week (`example_date--` gives 18th March, 2015).
* `unsigned int operator- (const Date& otherDate)` - Number of days between `otherDate` and current date. (`Date (D22, M04, 2015) - Date (D22, M05, 2015)` will return 30).
* `Date operator+ (int noOfDays)` - Day `noOfDays` after (before) the current date. Ahead or behind current date depends on sign of `noOfDays`.

#### Relational Operators

The following operators can be used to compare dates:

```cpp
bool operator== (const Date& otherDate);
bool operator!= (const Date& otherDate);
bool operator< (const Date& otherDate);
bool operator<= (const Date& otherDate);
bool operator> (const Date& otherDate);
bool operator>= (const Date& otherDate);
```

For example, `Date () >= Date (D01, M01, 2016)` will return `true`.

#### Casting Operators

* `operator WeekNumber () const` - Cast to the week number of the year in which the current date falls.
* `operator Month () const` - Cast to the month of the year in which the current date falls.
* `operator WeekDay () const` - Cast to the day of the week of the current date.

#### Date Format Setting

* `static void setFormat (DateFormat&)` - Set/Change Input/Output `DateFormat` for dates.
* `static DateFormat& getFormat ()` - Get Input/Output `DateFormat` for dates.

#### Global Methods

* `ostream& operator<< (ostream&, const Date&)` - Output dates as per the `format`.

```cpp
Date test_date (D28, M03, 2005);
std::cout << test_date;
```

* `istream& operator>> (istream&, Date&)` - Input dates as per the `format`.

```cpp
Date test_date (D28, M03, 2005);
std::cin >> test_date;
```

#### Other Methods

* `Date& operator= (const Date&)` - Assignment operator for Date objects.
* `bool leapYear () const` - Check if the year of the current date is a leap year.


text:
package com.laststandstudio.java.engine.src.images;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL12;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.ByteBuffer;

import static org.lwjgl.opengl.GL11.*;

public class Texture {

    public final int target = GL_TEXTURE_2D;
    public final int id;
    public final int width;
    public final int height;

    public static final int LINEAR = GL_LINEAR;
    public static final int NEAREST = GL_NEAREST;

    public static final int CLAMP = GL_CLAMP;
    public static final int CLAMP_TO_EDGE = GL12.GL_CLAMP_TO_EDGE;
    public static final int REPEAT = GL_REPEAT;

    public Texture(URI pngRef) throws IOException {
        this(pngRef, GL_NEAREST);
    }

    public Texture(URI pngRef, int filter) throws IOException {
        this(pngRef, filter, GL12.GL_CLAMP_TO_EDGE);
    }

    public Texture(URI pngRef, int filter, int wrap) throws IOException {
        InputStream input = null;
        try {
            //get an InputStream from our URL
            input = pngRef.toURL().openStream();

            //initialize the decoder
            PNGDecoder dec = new PNGDecoder(input);

            //set up image dimensions
            width = dec.getWidth();
            height = dec.getHeight();

            //we are using RGBA, i.e. 4 components or "bytes per pixel"
            final int bpp = 4;

            //create a new byte buffer which will hold our pixel data
            ByteBuffer buf = BufferUtils.createByteBuffer(bpp * width * height);

            //decode the image into the byte buffer, in RGBA format
            dec.decode(buf, width * bpp, PNGDecoder.Format.RGBA);

            //flip the buffer into "read mode" for OpenGL
            buf.flip();

            //enable textures and generate an ID
            glEnable(target);
            id = glGenTextures();

            //bind texture
            bind();

            //setup unpack mode
            glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

            //setup parameters
            glTexParameteri(target, GL_TEXTURE_MIN_FILTER, filter);
            glTexParameteri(target, GL_TEXTURE_MAG_FILTER, filter);
            glTexParameteri(target, GL_TEXTURE_WRAP_S, wrap);
            glTexParameteri(target, GL_TEXTURE_WRAP_T, wrap);

            //pass RGBA data to OpenGL
            glTexImage2D(target, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buf);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public void bind() {
        glBindTexture(target, id);
    }
}


text:
package net.automatalib.modelchecking;

import java.util.Collection;

import net.automatalib.automata.fsa.DFA;
import net.automatalib.automata.transducers.MealyMachine;

/**
 * A model checker that caches calls to {@link #findCounterExample(Object, Collection, Object)}.
 *
 * @param
 *         the input type
 * @param
 *         the automaton type
 * @param

 *         the property type
 * @param <R>
 *         the type of a counterexample
 *
 * @author Jeroen Meijer
 */
public interface ModelCheckerCache extends ModelChecker {

    /**
     * Clears the cache.
     */
    void clear();

    interface DFAModelCheckerCache extends ModelCheckerCache<I, DFA<?, I>, P, R>, DFAModelChecker {}

    interface MealyModelCheckerCache
            extends ModelCheckerCache<I, MealyMachine<?, I, ?, O>, P, R>, MealyModelChecker {}
}


text:
<configuration  scan="true" scanPeriod="70 seconds" debug="true">
	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<!-- encoder 默认配置为PatternLayoutEncoder -->
		<encoder>
			<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
			</pattern>
		</encoder>
	</appender>

	<logger name="java.sql" level="DEBUG" additivity="false">
		<appender-ref ref="STDOUT" />
	</logger>
	<logger name="cn.telling" level="DEBUG" additivity="false">
		<appender-ref ref="STDOUT" />
	</logger>
	<logger
		name="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"
		level="DEBUG" additivity="false">
		<appender-ref ref="STDOUT" />
	</logger>
	<root level="INFO">
		<appender-ref ref="STDOUT" />
	</root>
</configuration>