text:
package com.sleepycat.je.dbi;

import java.nio.ByteBuffer;
import java.util.Arrays;

import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.log.BasicVersionedWriteLoggable;
import com.sleepycat.je.log.LogUtils;
import com.sleepycat.je.log.Loggable;
import com.sleepycat.je.log.VersionedWriteLoggable;

/**
 * This class contains all fields of the database configuration which are
 * persistent. This class is logged as part of a nameLN so that databases can
 * be created on replica nodes with the correct configuration.
 */
public class ReplicatedDatabaseConfig extends BasicVersionedWriteLoggable {

    /**
     * The log version of the most recent format change for this loggable.
     *
     * @see #getLastFormatChange
     */
    public static final int LAST_FORMAT_CHANGE = 8;

    private byte flags;
    private int maxTreeEntriesPerNode;
    private byte[] btreeComparatorBytes = LogUtils.ZERO_LENGTH_BYTE_ARRAY;
    private byte[] duplicateComparatorBytes = LogUtils.ZERO_LENGTH_BYTE_ARRAY;
    private byte[][] triggerBytes = null;

    /** For reading */
    public ReplicatedDatabaseConfig() {
    }

    /** For writing */
    ReplicatedDatabaseConfig(byte flags,
                             int maxTreeEntriesPerNode,
                             byte[] btreeComparatorBytes,
                             byte[] duplicateComparatorBytes,
                             byte[][] triggerBytes) {

        this.flags = flags;
        this.maxTreeEntriesPerNode = maxTreeEntriesPerNode;

        if (btreeComparatorBytes != null) {
            this.btreeComparatorBytes = btreeComparatorBytes;
        }

        if (duplicateComparatorBytes != null) {
            this.duplicateComparatorBytes = duplicateComparatorBytes;
        }

        if (triggerBytes != null) {
            this.triggerBytes = triggerBytes;
        }
    }

    /**
     * Create a database config for use on the replica which contains
     * all the configuration options that were conveyed by way of this class.
     */
    public DatabaseConfig getReplicaConfig(EnvironmentImpl envImpl) {
        DatabaseConfig replicaConfig = new DatabaseConfig();
        replicaConfig.setTransactional(true);
        replicaConfig.setSortedDuplicates
            (DatabaseImpl.getSortedDuplicates(flags));

        /*
         * KeyPrefixing is set to true if dups are enabled, to account for the
         * upgrade scenario where the Master has not yet been upgraded but the
         * Replica has been.
         */
        replicaConfig.setKeyPrefixing(DatabaseImpl.getKeyPrefixing(flags) ||
                                      DatabaseImpl.getSortedDuplicates(flags));
        replicaConfig.setTemporary(DatabaseImpl.isTemporary(flags));
        replicaConfig.setReplicated(true);
        replicaConfig.setNodeMaxEntries(maxTreeEntriesPerNode);

        DatabaseImpl.ComparatorReader reader =
            new DatabaseImpl.ComparatorReader(btreeComparatorBytes,
                                              "Btree",
                                              envImpl.getClassLoader());
        if (reader.isClass()) {
            replicaConfig.setBtreeComparator(reader.getComparatorClass());
        } else {
            replicaConfig.setBtreeComparator(reader.getComparator());
        }

        reader = new DatabaseImpl.ComparatorReader(duplicateComparatorBytes,
                                                   "Duplicate",
                                                   envImpl.getClassLoader());
        if (reader.isClass()) {
            replicaConfig.setDuplicateComparator(reader.getComparatorClass());
        } else {
            replicaConfig.setDuplicateComparator(reader.getComparator());
        }

        replicaConfig.setTriggers(TriggerUtils.
                                  unmarshallTriggers(null, triggerBytes,
                                                     envImpl.getClassLoader()));

        return replicaConfig;
    }

    /** @see Loggable#getLogSize */
    @Override
    public int getLogSize() {
        return 1 + // flags, 1 byte
            LogUtils.getPackedIntLogSize(maxTreeEntriesPerNode) +
            LogUtils.getByteArrayLogSize(btreeComparatorBytes) +
            LogUtils.getByteArrayLogSize(duplicateComparatorBytes) +
            TriggerUtils.logSize(triggerBytes);
    }

    /** @see VersionedWriteLoggable#getLastFormatChange */
    @Override
    public int getLastFormatChange() {
        return LAST_FORMAT_CHANGE;
    }

    /** @see Loggable#writeToLog */
    @Override
    public void writeToLog(ByteBuffer logBuffer) {
        logBuffer.put(flags);
        LogUtils.writePackedInt(logBuffer, maxTreeEntriesPerNode);
        LogUtils.writeByteArray(logBuffer, btreeComparatorBytes);
        LogUtils.writeByteArray(logBuffer, duplicateComparatorBytes);
        TriggerUtils.writeTriggers(logBuffer, triggerBytes);
    }

    /** @see Loggable#readFromLog */
    @Override
    public void readFromLog(ByteBuffer itemBuffer, int entryVersion) {

        /*
         * ReplicatedDatabaseConfigs didn't exist before version 6 so they are
         * always packed.
         */
        flags = itemBuffer.get();
        maxTreeEntriesPerNode =
            LogUtils.readInt(itemBuffer, false/*unpacked*/);
        if (entryVersion < 8) {
            /* Discard maxDupTreeEntriesPerNode. */
            LogUtils.readInt(itemBuffer, false/*unpacked*/);
        }
        btreeComparatorBytes =
            LogUtils.readByteArray(itemBuffer, false/*unpacked*/);
        duplicateComparatorBytes =
            LogUtils.readByteArray(itemBuffer, false/*unpacked*/);
        triggerBytes = (entryVersion < 8) ?
                null :
                TriggerUtils.readTriggers(itemBuffer, entryVersion);
    }

    /** @see Loggable#dumpLog */
    @Override
    public void dumpLog(StringBuilder sb, boolean verbose) {
        sb.append("<config ");
        DatabaseImpl.dumpFlags(sb, verbose, flags);
        sb.append(" btcmpSet=\"").append(btreeComparatorBytes !=
                                         LogUtils.ZERO_LENGTH_BYTE_ARRAY);
        sb.append("\" dupcmpSet=\"").append(duplicateComparatorBytes !=
                                            LogUtils.ZERO_LENGTH_BYTE_ARRAY
                                            ).append("\"");
        TriggerUtils.dumpTriggers(sb, triggerBytes, null);
        sb.append(" />");
    }

    /** @see Loggable#getTransactionId */
    @Override
    public long getTransactionId() {
        return 0;
    }

    /** @see Loggable#logicalEquals */
    @Override
    public boolean logicalEquals(Loggable other) {
        if (!(other instanceof ReplicatedDatabaseConfig)) {
            return false;
        }

        ReplicatedDatabaseConfig otherConfig =
            (ReplicatedDatabaseConfig) other;

        if (flags != otherConfig.flags) {
            return false;
        }

        if (maxTreeEntriesPerNode !=
            otherConfig.maxTreeEntriesPerNode) {
            return false;
        }

        if (!Arrays.equals(btreeComparatorBytes,
                           otherConfig.btreeComparatorBytes)) {
            return false;
        }

        if (!Arrays.equals(duplicateComparatorBytes,
                           otherConfig.duplicateComparatorBytes)) {
            return false;
        }

        return true;
    }
}


text:
'frans': minor
---

Move clamp to ts

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by Nemina on 7/13/2015.
 */

function setCookie(cookieName, cookieValue) {

    if (navigator.cookieEnabled) {
        var date = new Date();

        date.setTime(date.getTime() + (1000));

        var expiers = "; expiers=" + date.toUTCString();

        document.cookie = cookieName + "=" + cookieValue + expiers + ";path=/";
    }
}

function getCookie() {

    var cookie = document.cookie.split(';');

    return cookie.length;
}

$(document).ready(function () {

    var screenWidth = screen.width;
    var screenHeight = screen.height;
    var pixelDepth = screen.pixelDepth;
    var isTouch = Modernizr.touch;

    setCookie("screen-width", screenWidth);
    setCookie("screen-height", screenHeight);
    setCookie("pixelDepth", pixelDepth);
    setCookie("isTouch", isTouch);

    if (getCookie() < 4) {

        location.reload(true);
    }
});
/*

 function ClickMe(){
 $("#recaptcha_area").find("#recaptcha_table").find("#recaptcha_response_field").keypress(function(){
 setCookie("KeyPressed","true");
 })
 }
 */


text:
import React from 'react'
import { CSSTransition } from 'react-transition-group' // ES6

const Fade = ({ children, ...props }) => (
 <CSSTransition
    {...props}
    timeout={1000}
    classNames="order"
  >
    {children}
  </CSSTransition>
);

const Slide = ({ children, ...props }) => (
 <CSSTransition
    {...props}
    timeout={1000}
    classNames="slidedown"
  >
    {children}
  </CSSTransition>
);

export {
  Fade,
  Slide
}


text:
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace FluentErgast.Http
{
    public class HttpClientWrapper : IHttpClient
    {
        private readonly static HttpClient HttpClient = new HttpClient();

        public async Task<T> GetAsync<T>(string requestUri)
        {
            var responseJson = await HttpClient.GetStringAsync(requestUri);
            var response = JsonConvert.DeserializeObject<T>(responseJson);

            return response;
        }
    }
}


text:
<?php

/**
 * PHP version 7.1
 *
 * @category Integration
 * @package  Intaro\RetailCrm\Component\ApiClient
 * @author   RetailCRM <integration@retailcrm.ru>
 * @license  MIT
 * @link     http://retailcrm.ru
 * @see      http://retailcrm.ru/docs
 */

namespace Intaro\RetailCrm\Component\ApiClient\Traits;

use RetailCrm\ApiClient;

/**
 * Trait BaseClientTrait
 *
 * @package Intaro\RetailCrm\Component\ApiClient\Traits
 */
trait BaseClientTrait
{
    /** @var \RetailCrm\ApiClient */
    private $client;

    /**
     * ClientFacade constructor.
     *
     * @param string      $url
     * @param string      $apiKey
     * @param string|null $site
     */
    public function __construct(string $url, string $apiKey, $site = null)
    {
        $this->client = new ApiClient($url, $apiKey, $site);
    }
}


text:
"""Parser for Unicode data files (as distributed by unicode.org)."""

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

import os
import re
from six.moves import urllib

# Directory or URL where Unicode tables reside.
_UNICODE_DIR = "https://www.unicode.org/Public/13.0.0/ucd"

# Largest valid Unicode code value.
_RUNE_MAX = 0x10FFFF

class Error(Exception):
  """Unicode error base class."""

class InputError(Error):
  """Unicode input error class.  Raised on invalid input."""

def _UInt(s):
  """Converts string to Unicode code point ('263A' => 0x263a).

  Args:
    s: string to convert

  Returns:
    Unicode code point

  Raises:
    InputError: the string is not a valid Unicode value.
  """

  try:
    v = int(s, 16)
  except ValueError:
    v = -1
  if len(s) < 4 or len(s) > 6 or v < 0 or v > _RUNE_MAX:
    raise InputError("invalid Unicode value %s" % (s,))
  return v

def _URange(s):
  """Converts string to Unicode range.

    '0001..0003' => [1, 2, 3].
    '0001' => [1].

  Args:
    s: string to convert

  Returns:
    Unicode range

  Raises:
    InputError: the string is not a valid Unicode range.
  """
  a = s.split("..")
  if len(a) == 1:
    return [_UInt(a[0])]
  if len(a) == 2:
    lo = _UInt(a[0])
    hi = _UInt(a[1])
    if lo < hi:
      return range(lo, hi + 1)
  raise InputError("invalid Unicode range %s" % (s,))

def _UStr(v):
  """Converts Unicode code point to hex string.

    0x263a => '0x263A'.

  Args:
    v: code point to convert

  Returns:
    Unicode string

  Raises:
    InputError: the argument is not a valid Unicode value.
  """
  if v < 0 or v > _RUNE_MAX:
    raise InputError("invalid Unicode value %s" % (v,))
  return "0x%04X" % (v,)

def _ParseContinue(s):
  """Parses a Unicode continuation field.

  These are of the form '<Name, First>' or '<Name, Last>'.
  Instead of giving an explicit range in a single table entry,
  some Unicode tables use two entries, one for the first
  code value in the range and one for the last.
  The first entry's description is '<Name, First>' instead of 'Name'
  and the second is '<Name, Last>'.

    '<Name, First>' => ('Name', 'First')
    '<Name, Last>' => ('Name', 'Last')
    'Anything else' => ('Anything else', None)

  Args:
    s: continuation field string

  Returns:
    pair: name and ('First', 'Last', or None)
  """

  match = re.match("<(.*), (First|Last)>", s)
  if match is not None:
    return match.groups()
  return (s, None)

def ReadUnicodeTable(filename, nfields, doline):
  """Generic Unicode table text file reader.

  The reader takes care of stripping out comments and also
  parsing the two different ways that the Unicode tables specify
  code ranges (using the .. notation and splitting the range across
  multiple lines).

  Each non-comment line in the table is expected to have the given
  number of fields.  The first field is known to be the Unicode value
  and the second field its description.

  The reader calls doline(codes, fields) for each entry in the table.
  If fn raises an exception, the reader prints that exception,
  prefixed with the file name and line number, and continues
  processing the file.  When done with the file, the reader re-raises
  the first exception encountered during the file.

  Arguments:
    filename: the Unicode data file to read, or a file-like object.
    nfields: the number of expected fields per line in that file.
    doline: the function to call for each table entry.

  Raises:
    InputError: nfields is invalid (must be >= 2).
  """

  if nfields < 2:
    raise InputError("invalid number of fields %d" % (nfields,))

  if type(filename) == str:
    if filename.startswith("https://"):
      fil = urllib.request.urlopen(filename)
    else:
      fil = open(filename, "rb")
  else:
    fil = filename

  first = None        # first code in multiline range
  expect_last = None  # tag expected for "Last" line in multiline range
  lineno = 0          # current line number
  for line in fil:
    lineno += 1
    try:
      line = line.decode('latin1')

      # Chop # comments and white space; ignore empty lines.
      sharp = line.find("#")
      if sharp >= 0:
        line = line[:sharp]
      line = line.strip()
      if not line:
        continue

      # Split fields on ";", chop more white space.
      # Must have the expected number of fields.
      fields = [s.strip() for s in line.split(";")]
      if len(fields) != nfields:
        raise InputError("wrong number of fields %d %d - %s" %
                         (len(fields), nfields, line))

      # The Unicode text files have two different ways
      # to list a Unicode range.  Either the first field is
      # itself a range (0000..FFFF), or the range is split
      # across two lines, with the second field noting
      # the continuation.
      codes = _URange(fields[0])
      (name, cont) = _ParseContinue(fields[1])

      if expect_last is not None:
        # If the last line gave the First code in a range,
        # this one had better give the Last one.
        if (len(codes) != 1 or codes[0] <= first or
            cont != "Last" or name != expect_last):
          raise InputError("expected Last line for %s" %
                           (expect_last,))
        codes = range(first, codes[0] + 1)
        first = None
        expect_last = None
        fields[0] = "%04X..%04X" % (codes[0], codes[-1])
        fields[1] = name
      elif cont == "First":
        # Otherwise, if this is the First code in a range,
        # remember it and go to the next line.
        if len(codes) != 1:
          raise InputError("bad First line: range given")
        expect_last = name
        first = codes[0]
        continue

      doline(codes, fields)

    except Exception as e:
      print("%s:%d: %s" % (filename, lineno, e))
      raise

  if expect_last is not None:
    raise InputError("expected Last line for %s; got EOF" %
                     (expect_last,))

def CaseGroups(unicode_dir=_UNICODE_DIR):
  """Returns list of Unicode code groups equivalent under case folding.

  Each group is a sorted list of code points,
  and the list of groups is sorted by first code point
  in the group.

  Args:
    unicode_dir: Unicode data directory

  Returns:
    list of Unicode code groups
  """

  # Dict mapping lowercase code point to fold-equivalent group.
  togroup = {}

  def DoLine(codes, fields):
    """Process single CaseFolding.txt line, updating togroup."""
    (_, foldtype, lower, _) = fields
    if foldtype not in ("C", "S"):
      return
    lower = _UInt(lower)
    togroup.setdefault(lower, [lower]).extend(codes)

  ReadUnicodeTable(unicode_dir+"/CaseFolding.txt", 4, DoLine)

  groups = list(togroup.values())
  for g in groups:
    g.sort()
  groups.sort()
  return togroup, groups

def Scripts(unicode_dir=_UNICODE_DIR):
  """Returns dict mapping script names to code lists.

  Args:
    unicode_dir: Unicode data directory

  Returns:
    dict mapping script names to code lists
  """

  scripts = {}

  def DoLine(codes, fields):
    """Process single Scripts.txt line, updating scripts."""
    (_, name) = fields
    scripts.setdefault(name, []).extend(codes)

  ReadUnicodeTable(unicode_dir+"/Scripts.txt", 2, DoLine)
  return scripts

def Categories(unicode_dir=_UNICODE_DIR):
  """Returns dict mapping category names to code lists.

  Args:
    unicode_dir: Unicode data directory

  Returns:
    dict mapping category names to code lists
  """

  categories = {}

  def DoLine(codes, fields):
    """Process single UnicodeData.txt line, updating categories."""
    category = fields[2]
    categories.setdefault(category, []).extend(codes)
    # Add codes from Lu into L, etc.
    if len(category) > 1:
      short = category[0]
      categories.setdefault(short, []).extend(codes)

  ReadUnicodeTable(unicode_dir+"/UnicodeData.txt", 15, DoLine)
  return categories


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreatePluginSettingsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('plugin_settings', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('name');
			$table->text('value', 65535);
			$table->text('field_type', 65535);
			$table->text('field_parameters', 65535);
			$table->integer('plugin_id');
			$table->integer('application_id');
			$table->softDeletes();
			$table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('plugin_settings');
	}

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tag_project;

import bropals.lib.simplegame.gui.GuiGroup;
import bropals.lib.simplegame.gui.GuiImage;
import bropals.lib.simplegame.gui.GuiText;
import bropals.lib.simplegame.state.GameState;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;

/**
 *
 * @author Jonathon
 */
public class GameOverState extends GameState {

    private int biscuits;
    private int furniture;
    private GuiGroup gui;
    private Font font;

    public GameOverState(int biscuits, int furniture) {
        this.biscuits = biscuits;
        this.furniture = furniture;
    }

    @Override
    public void update() {

    }

    @Override
    public void render(Object graphicsObj) {
        Graphics g = (Graphics)graphicsObj;
        gui.render(graphicsObj);
    }

    @Override
    public void onEnter() {
        playSoundEffect("dogSad");
        gui = new GuiGroup();
        font = new Font(Font.SANS_SERIF, Font.BOLD, 32);
        gui.addElement(new GuiImage(0, 0, 800, 600, getImage("gameOverBackground")));
        GuiText b, f;
        b = new GuiText("" + biscuits, 160, 380, 0, 0, false);
        b.setFont(font);
        f = new GuiText("" + furniture, 510, 380, 0, 0, false);
        f.setFont(font);
        gui.addElement(b);
        gui.addElement(f);
    }

    @Override
    public void onExit() {
    }

    @Override
    public void key(KeyEvent kr, boolean pressed) {
        if (kr.getKeyCode() == KeyEvent.VK_ESCAPE && pressed) {
            getGameStateRunner().setState(new MainMenuState());
        }
    }

    @Override
    public void mouse(MouseEvent m, boolean pressed) {
    }

}


text:
package org.elasticsearch.xpack.searchablesnapshots;

import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.indices.SystemIndexDescriptor;
import org.elasticsearch.license.XPackLicenseState;
import org.elasticsearch.plugins.SystemIndexPlugin;
import org.elasticsearch.xpack.core.LocalStateCompositeXPackPlugin;

import java.nio.file.Path;
import java.util.Collection;

public class LocalStateSearchableSnapshots extends LocalStateCompositeXPackPlugin implements SystemIndexPlugin {

    private final SearchableSnapshots plugin;

    public LocalStateSearchableSnapshots(final Settings settings, final Path configPath) {
        super(settings, configPath);
        this.plugin = new SearchableSnapshots(settings) {

            @Override
            protected XPackLicenseState getLicenseState() {
                return LocalStateSearchableSnapshots.this.getLicenseState();
            }

        };
        plugins.add(plugin);
    }

    @Override
    public Collection<SystemIndexDescriptor> getSystemIndexDescriptors(Settings settings) {
        return plugin.getSystemIndexDescriptors(settings);
    }

    @Override
    public String getFeatureName() {
        return plugin.getFeatureName();
    }

    @Override
    public String getFeatureDescription() {
        return plugin.getFeatureDescription();
    }
}


text:
cask 'league-of-legends' do
  version :latest
  sha256 :no_check

  # riotgames.com is the official download host per the vendor homepage
  url 'http://l3cdn.riotgames.com/Installer/NA_Mac_Installer/League%20of%20Legends%20NA.dmg'
  name 'League of Legends'
  homepage 'http://leagueoflegends.com/'
  license :gratis

  app 'League of Legends.app'
end


text:
package karyon.math.collections;

import karyon.exceptions.InvalidParameterException;
import karyon.testing.KaryonTest;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 * Created with IntelliJ IDEA.
 * User: kmchugh
 * Date: 25/7/13
 * Time: 4:07 PM
 * To change this template use File | Settings | File Templates.
 */
public class SparseDoubleVectorTest
        extends KaryonTest
{
    @Test
    public void testConstructor() throws Exception
    {
        startMarker();
        SparseDoubleVector loVec = new SparseDoubleVector();
        assertNotNull(loVec);
    }

    @Test
    public void testConstructor_long_float_boolean() throws Exception
    {
        startMarker();
        assertTrue(
                willThrow(InvalidParameterException.class, new Runnable()
                {
                    @Override
                    public void run()
                    {
                        SparseDoubleVector loVec = new SparseDoubleVector(0, .75f, true);
                    }
                }));

        assertTrue(
                willThrow(InvalidParameterException.class, new Runnable(){
                    @Override
                    public void run()
                    {
                        SparseDoubleVector loVec = new SparseDoubleVector(10, 1.5f, true);
                    }
                }));

        SparseDoubleVector loVec = new SparseDoubleVector(10, .75f, true);
        assertTrue(loVec.isHorizontal());

        loVec = new SparseDoubleVector(10, .75f, false);
        assertFalse(loVec.isHorizontal());
    }

    @Test
    public void testConstructor_array() throws Exception
    {
        startMarker();
        double[] laDouble = new double[]{1,2,3,4,5};
        SparseDoubleVector loVec = new SparseDoubleVector(laDouble);

        assertEquals(laDouble.length, loVec.size());
        for(int i=0; i<laDouble.length; i++)
        {
            assertEquals(laDouble[i], loVec.getDouble(i), 0);
        }
    }

    @Test
    public void testConstructor_array_boolean() throws Exception
    {
        startMarker();
        double[] laDouble = new double[]{1,2,3,4,5};
        SparseDoubleVector loVec = new SparseDoubleVector(laDouble, true);
        assertTrue(loVec.isHorizontal());

        loVec = new SparseDoubleVector(laDouble, false);
        assertFalse(loVec.isHorizontal());
    }

    @Test
    public void testIsHorizontal() throws Exception
    {
        startMarker();
        assertTrue(new SparseDoubleVector(new double[0], true).isHorizontal());
        assertFalse(new SparseDoubleVector(new double[0], false).isHorizontal());
    }

    @Test
    public void testGetCapacity() throws Exception
    {
        startMarker();
        assertEquals(10, new SparseDoubleVector(10,0.75f, true).getCapacity());
        assertEquals(20, new SparseDoubleVector(20,0.75f, true).getCapacity());
    }

    @Test
    public void testIsEmpty() throws Exception
    {
        startMarker();
        assertTrue(new SparseDoubleVector().isEmpty());
        assertTrue(new SparseDoubleVector(new double[0]).isEmpty());
        assertTrue(new SparseDoubleVector(new double[]{}).isEmpty());
        assertFalse(new SparseDoubleVector(new double[]{0, 1, 2, 3}).isEmpty());
    }

    @Test
    public void testAddDouble() throws Exception
    {
        startMarker();
        double[] laDouble = new double[]{1,2,3,4,5};
        SparseDoubleVector loVec = new SparseDoubleVector(laDouble);
        assertEquals(5, loVec.size());
        loVec.addDouble(6);
        assertEquals(6, loVec.size());
        loVec.addDouble(7);
        assertEquals(7, loVec.size());
        loVec.addDouble(8);
        assertEquals(8, loVec.size());
        loVec.addDouble(9);
        assertEquals(9, loVec.size());

        for(int i=0; i<9; i++)
        {
            assertEquals(i+1, loVec.getDouble(i), 0);
        }
    }

    @Test
    public void testSize() throws Exception
    {
        startMarker();
        SparseDoubleVector loVec = new SparseDoubleVector();
        assertEquals(0, loVec.size());
        loVec.addDouble(1);
        assertEquals(1, loVec.size());
        double[] laDouble = new double[]{1,2,3,4,5};
        loVec.addAllDouble(laDouble);
        assertEquals(6, loVec.size());

        loVec.addDouble(100, 1);
        assertEquals(101, loVec.size());
        loVec.addDouble(2);
        assertEquals(102, loVec.size());
    }

    @Test
    public void testCount() throws Exception
    {
        startMarker();

        SparseDoubleVector loVec = new SparseDoubleVector();
        assertEquals(0, loVec.count());
        loVec.addDouble(1);
        assertEquals(1, loVec.count());
        double[] laDouble = new double[]{1,2,3,4,5};
        loVec.addAllDouble(laDouble);
        assertEquals(6, loVec.count());

        loVec.addDouble(100, 1);
        assertEquals(7, loVec.count());
        loVec.addDouble(2);
        assertEquals(8, loVec.count());
    }

    @Test
    public void testAddAllDouble() throws Exception
    {
        startMarker();
        double[] laDouble = new double[]{1,2,3,4,5};
        SparseDoubleVector loVec = new SparseDoubleVector();
        assertEquals(0, loVec.size());

        loVec.addAllDouble(laDouble);
        assertEquals(5, loVec.size());

        loVec.addAllDouble(laDouble);
        assertEquals(10, loVec.size());

        for(int i=0; i<loVec.size(); i++)
        {
            assertEquals(laDouble[i%5], loVec.getDouble(i), 0);
        }
    }
}


text:
![Universal Simulator Logo](/src/images/UniSIMLogo.png)

Created by Wheaton College's Spring 2013 Software Development class.

##Description

Welcome to UniSIM. This program provides the user with a blank slate (a grid), and all the tools that he or she needs to populate that grid with "agents," which can be anything from a rabbit in a predator-prey simulation, to "alive" squares in Conway's Game of Life. In addition, the user can specify interactions between these objects, called "triggers," and the outcome of those interactions ("behaviors"). Ultimately, this provides the user with a sandbox to create almost any interaction possible for a grid-based system.

##How to Contribute

1. Fork this repository
  * Click *Fork* in the upper right
2. Make changes and contributions to the forked repository
  * Clone the repository to your computer with git clone https://github.com/username/simulator.git
  * See below for steps on importing the project into Eclipse
  * Commit changes and push them to the forked project
  * If you need to add changes that have been made to the original repository, use git pull --rebase upstream/master
3. Finally, use a [pull request](https://help.github.com/articles/using-pull-requests) to add your code to the original repository.

##Eclipse Details

To add the project to Eclipse:
File -> Import -> General -> Existing Projects into Workspace
Select the repository directory, then click "Finish"

To import the Coding Standard into Eclipse:
Window -> Preferences -> Java -> Code Style -> Formatter -> Import
Select the CodingStandard.xml file from the root directory of the repository and click "Apply" and "OK"


text:
require 'open3'

module Clipboard; end

module Clipboard::Windows
  extend self

  CF_TEXT = 1
  CF_UNICODETEXT = 13
  GMEM_MOVEABLE = 2

  # get ffi function handlers
  begin
    require 'ffi'
  rescue LoadError
    raise LoadError, 'Could not load the required ffi gem, install it with: gem install ffi'
  end

  module User32
    extend FFI::Library
    ffi_lib "user32"
    ffi_convention :stdcall

    attach_function :open,  :OpenClipboard,    [ :long ], :long
    attach_function :close, :CloseClipboard,   [       ], :long
    attach_function :empty, :EmptyClipboard,   [       ], :long
    attach_function :get,   :GetClipboardData, [ :long ], :long
    attach_function :set,   :SetClipboardData, [ :long, :long ], :long
  end

  module Kernel32
    extend FFI::Library
    ffi_lib 'kernel32'
    ffi_convention :stdcall

    attach_function :lock,   :GlobalLock,   [ :long ], :pointer
    attach_function :unlock, :GlobalUnlock, [ :long ], :long
    attach_function :size,   :GlobalSize,   [ :long ], :long
    attach_function :alloc,  :GlobalAlloc,  [ :long, :long ], :long
  end

  # see http://www.codeproject.com/KB/clipboard/archerclipboard1.aspx
  def paste(_ = nil)
    ret = ""
      if 0 != User32.open( 0 )
        hclip = User32.get( CF_UNICODETEXT )
        if hclip && 0 != hclip
          pointer_to_data = Kernel32.lock( hclip )
          data = ""
          # Windows Unicode is ended by to null bytes, so get the whole string
          size = Kernel32.size( hclip )
          data << pointer_to_data.get_bytes( 0, size - 2 )
          if RUBY_VERSION >= '1.9'
            ret = data.force_encoding("UTF-16LE").encode(Encoding.default_external) # TODO catch bad encodings
          else # 1.8: fallback to simple CP850 encoding
            require 'iconv'
            utf8 = Iconv.iconv( "UTF-8", "UTF-16LE", data)[0]
            ret = Iconv.iconv( "CP850", "UTF-8", utf8)[0]
          end
        if data && 0 != data
          Kernel32.unlock( hclip )
        end
      end
      User32.close( )
    end
    ret || ""
  end

  def clear
    if 0 != User32.open( 0 )
      User32.empty( )
      User32.close( )
    end
    paste
  end

  def copy(data_to_copy)
    if ( RUBY_VERSION >= '1.9' ) && 0 != User32.open( 0 )
      User32.empty( )
      data = data_to_copy.encode("UTF-16LE") # TODO catch bad encodings
      data << 0
      handler = Kernel32.alloc( GMEM_MOVEABLE, data.bytesize )
      pointer_to_data = Kernel32.lock( handler )
      pointer_to_data.put_bytes( 0, data, 0, data.bytesize )
      Kernel32.unlock( handler )
      User32.set( CF_UNICODETEXT, handler )
      User32.close( )
    else # don't touch anything
      Open3.popen3( 'clip' ){ |input,_,_| input << data_to_copy } # depends on clip (available by default since Vista)
    end
    paste
  end
end


text:
import markdown2
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter(is_safe=True)
@stringfilter
def markdown(value, arg=None):
    return mark_safe(markdown2.markdown(value,safe_mode=True))


text:
package com.twitter.finagle.http2.exp.transport

import com.twitter.finagle.Status
import com.twitter.finagle.http2.transport.ClientSession
import com.twitter.finagle.transport.Transport
import com.twitter.util.{Future, Time}

/**
 * [[ClientSession]] proxy that waits for the latch before allowing the session to close.
 *
 * This is useful for the H2C and TLS clients that have to manage the possibility that
 * the connection can be either H1 or H2. In those cases, the first request will be
 * initialized using a standard `Transport` oriented dispatch model but uses a stream from
 * the underlying `ClientSession`. In that case we don't want to close the whole session
 * while that dispatch is still outstanding.
 */
private class DeferredCloseSession(underlying: ClientSession, latch: Future[Unit])
    extends ClientSession {

  def newChildTransport(): Future[Transport[Any, Any]] =
    underlying.newChildTransport()

  def status: Status = underlying.status

  def close(deadline: Time): Future[Unit] =
    latch.before(underlying.close(deadline))
}


text:
using System;

namespace Hallmanac.CryptoHelpers
{
    /// <summary>
    ///     Class to hold the result of a function that wraps an operation which will return a value.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class CommandResult<T> : CommandResult
    {
        /// <summary>
        ///     Constructor for the CommandResult with a Value result
        /// </summary>
        /// <param name="value"></param>
        /// <param name="isSuccessful"></param>
        /// <param name="message"></param>
        public CommandResult(T value, bool isSuccessful, string message = null)
            : base(isSuccessful, message)
        {
            Value = value;
        }

        /// <summary>
        ///     Returns whether the <see cref="Value" /> property contains a value and that it's NOT Empty or Whitespace in the
        ///     case of a string
        /// </summary>
        public bool HasValue
        {
            get
            {
                if (typeof(T) != typeof(string))
                    return Value != null;
                var strVal = Value as string;
                return !String.IsNullOrWhiteSpace(strVal);
            }
        }

        /// <summary>
        ///     The Value of the result. This could potentially be nullable. It is recommended that you check
        ///     the <see cref="HasValue" /> property before trying to access this value.
        /// </summary>
        public T Value { get; }
    }

    /// <summary>
    ///     Class to hold the result of a function that wraps an action operation which will NOT return a value.
    /// </summary>
    public class CommandResult
    {
        /// <summary>
        ///     Constructor for a CommandResult without a value
        /// </summary>
        /// <param name="isSuccessful"></param>
        /// <param name="message"></param>
        public CommandResult(bool isSuccessful, string message)
        {
            if (!isSuccessful && String.IsNullOrWhiteSpace(message)) throw new InvalidOperationException("No error message provided for a non-successful value");
            IsSuccessful = isSuccessful;
            Message = message;
        }

        /// <summary>
        ///     Determines whether or not the operation was successful
        /// </summary>
        public bool IsSuccessful { get; }

        /// <summary>
        ///     Text that can be used to convey an error or success message
        /// </summary>
        public string Message { get; }

        /// <summary>
        ///     Determines whether the operation was a failure
        /// </summary>
        public bool IsFailure => !IsSuccessful;
    }
}


text:
package com.gochinatv.cdn.api.proxy;

public class UserServiceImpl implements UserService{//实现类

    @Override
    public void addUser(String name, String password) {
        System.out.println("++++执行addUser()方法++++++");
    }

    @Override
    public void getUser(String id) {
        System.out.println("++++执行getUser()方法++++++");
    }
}


text:
Imports System.ComponentModel
Imports System.Web.UI

Namespace Cisco

    Partial Public Class CiscoIPPhoneError

		#Region " Rendering Methods "

	        Protected Overrides Sub Render( _
	            ByVal output As System.Web.UI.HtmlTextWriter _
	        )

	            Select Case [Error]

	                Case CiscoIPPhoneErrorCodes.AuthenticationError
	                    output.WriteLine("<CiscoIPPhoneError Number=""4"" />")

	                Case CiscoIPPhoneErrorCodes.CiscoIPPhoneExecuteParsingError
	                    output.WriteLine("<CiscoIPPhoneError Number=""1"" />")

	                Case CiscoIPPhoneErrorCodes.CiscoIPPhoneResponseResponseFramingError
	                    output.WriteLine("<CiscoIPPhoneError Number=""2"" />")

	                Case CiscoIPPhoneErrorCodes.InternalError
	                    output.WriteLine("<CiscoIPPhoneError Number=""3"" />")

	            End Select

	        End Sub

		#End Region

    End Class

End Namespace


text:
class Jarre implements IAmbient {
   hum() {
      console.log("mmmMmmmMMmm")
   }
}

export var Music = new Jarre();


text:
package com.sensorberg.sdk.internal.transport.model;

import com.google.gson.annotations.Expose;

import com.sensorberg.sdk.internal.interfaces.Clock;
import com.sensorberg.sdk.model.persistence.ActionConversion;
import com.sensorberg.sdk.model.persistence.BeaconAction;
import com.sensorberg.sdk.model.persistence.BeaconScan;

import java.util.Date;
import java.util.List;

//serialized by gson
@SuppressWarnings({"unused", "WeakerAccess"})
public class HistoryBody {

    @Expose
    public final List<BeaconScan> events;

    @Expose
    public final List<BeaconAction> actions;

    @Expose
    public final List<ActionConversion> conversions;

    @Expose
    public final Date deviceTimestamp;

    public HistoryBody(List<BeaconScan> scans, List<BeaconAction> actions, List<ActionConversion> conversions, Clock clock) {
        this.events = scans;
        this.deviceTimestamp = new Date(clock.now());
        this.actions = actions;
        this.conversions = conversions;
    }
}


text:
package org.commcare.tasks;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import androidx.core.util.Pair;

import net.sqlcipher.database.SQLiteDatabase;

import org.apache.commons.lang3.StringUtils;
import org.commcare.CommCareApplication;
import org.commcare.android.database.app.models.FormDefRecord;
import org.commcare.android.database.app.models.UserKeyRecord;
import org.commcare.android.database.user.models.ACase;
import org.commcare.cases.ledger.Ledger;
import org.commcare.cases.util.InvalidCaseGraphException;
import org.commcare.core.encryption.CryptUtil;
import org.commcare.core.network.AuthenticationInterceptor;
import org.commcare.core.network.CaptivePortalRedirectException;
import org.commcare.core.network.bitcache.BitCache;
import org.commcare.data.xml.DataModelPullParser;
import org.commcare.engine.cases.CaseUtils;
import org.commcare.google.services.analytics.AnalyticsParamValue;
import org.commcare.interfaces.CommcareRequestEndpoints;
import org.commcare.models.FormRecordProcessor;
import org.commcare.models.database.SqlStorage;
import org.commcare.models.database.user.models.AndroidCaseIndexTable;
import org.commcare.models.database.user.models.EntityStorageCache;
import org.commcare.models.encryption.ByteEncrypter;
import org.commcare.modern.models.RecordTooLargeException;
import org.commcare.network.DataPullRequester;
import org.commcare.network.HttpUtils;
import org.commcare.network.RemoteDataPullResponse;
import org.commcare.preferences.HiddenPreferences;
import org.commcare.preferences.ServerUrls;
import org.commcare.resources.model.CommCareOTARestoreListener;
import org.commcare.services.CommCareSessionService;
import org.commcare.sync.ExternalDataUpdateHelper;
import org.commcare.tasks.templates.CommCareTask;
import org.commcare.util.LogTypes;
import org.commcare.utils.FormSaveUtil;
import org.commcare.utils.SessionUnavailableException;
import org.commcare.utils.SyncDetailCalculations;
import org.commcare.utils.UnknownSyncError;
import org.commcare.xml.AndroidTransactionParserFactory;
import org.javarosa.core.model.User;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.util.PropertyUtils;
import org.javarosa.xml.util.ActionableInvalidStructureException;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Hashtable;
import java.util.NoSuchElementException;

import javax.crypto.SecretKey;

/**
 * @author ctsims
 */
public abstract class DataPullTask<R>
        extends CommCareTask<Void, Integer, ResultAndError<DataPullTask.PullTaskResult>, R>
        implements CommCareOTARestoreListener {
    private final String server;
    private final String username;
    private final String password;
    protected final Context context;

    private int mCurrentProgress;
    private int mTotalItems;
    private long mSyncStartTime;

    public static final int DATA_PULL_TASK_ID = 10;

    public static final int PROGRESS_STARTED = 0;
    public static final int PROGRESS_CLEANED = 1;
    public static final int PROGRESS_AUTHED = 2;
    private static final int PROGRESS_DONE = 4;
    public static final int PROGRESS_RECOVERY_NEEDED = 8;
    public static final int PROGRESS_RECOVERY_STARTED = 16;
    private static final int PROGRESS_RECOVERY_FAIL_SAFE = 32;
    private static final int PROGRESS_RECOVERY_FAIL_BAD = 64;
    public static final int PROGRESS_PROCESSING = 128;
    public static final int PROGRESS_DOWNLOADING = 256;
    public static final int PROGRESS_DOWNLOADING_COMPLETE = 512;
    public static final int PROGRESS_SERVER_PROCESSING = 1024;

    private final DataPullRequester dataPullRequester;
    private final AsyncRestoreHelper asyncRestoreHelper;
    private final boolean blockRemoteKeyManagement;

    private boolean loginNeeded;
    private UserKeyRecord ukrForLogin;
    private boolean wasKeyLoggedIn;

    public DataPullTask(String username, String password, String userId,
                        String server, Context context, DataPullRequester dataPullRequester,
                        boolean blockRemoteKeyManagement) {
        this.server = server;
        this.username = username;
        this.password = password;
        this.context = context;
        this.taskId = DATA_PULL_TASK_ID;
        this.dataPullRequester = dataPullRequester;
        this.requestor = dataPullRequester.getHttpGenerator(username, password, userId);
        this.asyncRestoreHelper = CommCareApplication.instance().getAsyncRestoreHelper(this);
        this.blockRemoteKeyManagement = blockRemoteKeyManagement;

        TAG = DataPullTask.class.getSimpleName();
    }

    public DataPullTask(String username, String password, String userId,
                        String server, Context context) {
        this(username, password, userId, server, context, CommCareApplication.instance().getDataPullRequester(),
                false);
    }

    // TODO PLM: once this task is refactored into manageable components, it should use the
    // ManagedAsyncTask pattern of checking for isCancelled() and aborting at safe places.
    @Override
    protected void onCancelled() {
        super.onCancelled();
        wipeLoginIfItOccurred();
    }

    private final CommcareRequestEndpoints requestor;

    @Override
    protected ResultAndError<PullTaskResult> doTaskBackground(Void... params) {
        if (!CommCareSessionService.sessionAliveLock.tryLock()) {
            // Don't try to sync if logging out is occurring
            return new ResultAndError<>(PullTaskResult.SESSION_EXPIRE,
                    "Cannot sync while a logout is in process");
        }
        try {
            return doTaskBackgroundHelper();
        } finally {
            CommCareSessionService.sessionAliveLock.unlock();
        }
    }

    private ResultAndError<PullTaskResult> doTaskBackgroundHelper() {
        if (StringUtils.isEmpty(server)) {
            return new ResultAndError<>(PullTaskResult.EMPTY_URL, Localization.get("sync.fail.empty.url"));
        }

        publishProgress(PROGRESS_STARTED);
        HiddenPreferences.setPostUpdateSyncNeeded(false);
        Logger.log(LogTypes.TYPE_USER, "Starting Sync");
        determineIfLoginNeeded();

        AndroidTransactionParserFactory factory = getTransactionParserFactory();
        byte[] wrappedEncryptionKey = getEncryptionKey();
        if (wrappedEncryptionKey == null) {
            this.publishProgress(PROGRESS_DONE);
            return new ResultAndError<>(PullTaskResult.ENCRYPTION_FAILURE,
                    "Unable to get or generate encryption key");
        }

        factory.initUserParser(wrappedEncryptionKey);

        if (!loginNeeded) {
            //Only purge cases if we already had a logged in user. Otherwise we probably can't read the DB.
            try {
                CaseUtils.purgeCases();
            } catch (InvalidCaseGraphException e) {
                try {
                    return handleBadLocalState(factory);
                } catch (UnknownSyncError unknownSyncError) {
                    e.printStackTrace();
                    Logger.log(LogTypes.TYPE_WARNING_NETWORK, "Couldn't sync due to Unknown Error|" + e.getMessage());
                    return new ResultAndError<>(PullTaskResult.UNKNOWN_FAILURE);
                }
            }
        }

        return getRequestResultOrRetry(factory);
    }

    private void determineIfLoginNeeded() {
        try {
            loginNeeded = !CommCareApplication.instance().getSession().isActive();
        } catch (SessionUnavailableException sue) {
            // expected if we aren't initialized.
            loginNeeded = true;
        }
    }

    private AndroidTransactionParserFactory getTransactionParserFactory() {
        return new AndroidTransactionParserFactory(context, requestor) {
            boolean publishedAuth = false;

            @Override
            public void reportProgress(int progress) {
                if (!publishedAuth) {
                    DataPullTask.this.publishProgress(PROGRESS_AUTHED, progress);
                    publishedAuth = true;
                }
            }
        };
    }

    private byte[] getEncryptionKey() {
        byte[] key;
        if (loginNeeded) {
            initUKRForLogin();
            if (ukrForLogin == null) {
                return null;
            }
            key = ukrForLogin.getEncryptedKey();
        } else {
            key = CommCareApplication.instance().getSession().getLoggedInUser().getWrappedKey();
        }
        this.publishProgress(PROGRESS_CLEANED); // Either way, we don't want to do this step again
        return key;
    }

    private void initUKRForLogin() {
        if (blockRemoteKeyManagement || shouldGenerateFirstKey()) {
            SecretKey newKey = CryptUtil.generateSemiRandomKey();
            if (newKey == null) {
                return;
            }
            String sandboxId = PropertyUtils.genUUID().replace("-", "");
            ukrForLogin = new UserKeyRecord(username, UserKeyRecord.generatePwdHash(password),
                    ByteEncrypter.wrapByteArrayWithString(newKey.getEncoded(), password),
                    new Date(), new Date(Long.MAX_VALUE), sandboxId);
        } else {
            ukrForLogin = UserKeyRecord.getCurrentValidRecordByPassword(
                    CommCareApplication.instance().getCurrentApp(), username, password, true);
            if (ukrForLogin == null) {
                Logger.log(LogTypes.TYPE_ERROR_ASSERTION,
                        "Shouldn't be able to not have a valid key record when OTA restoring with a key server");
            }
        }
    }

    private static boolean shouldGenerateFirstKey() {
        String keyServer = ServerUrls.getKeyServer();
        return keyServer == null || keyServer.equals("");
    }

    private ResultAndError<PullTaskResult> getRequestResultOrRetry(AndroidTransactionParserFactory factory) {
        while (asyncRestoreHelper.retryWaitPeriodInProgress()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
            }

            if (isCancelled()) {
                return new ResultAndError<>(PullTaskResult.CANCELLED);
            }
        }

        PullTaskResult responseError = PullTaskResult.UNKNOWN_FAILURE;
        asyncRestoreHelper.retryAtTime = -1;
        try {
            ResultAndError<PullTaskResult> result = makeRequestAndHandleResponse(factory);
            if (PullTaskResult.RETRY_NEEDED.equals(result.data)) {
                asyncRestoreHelper.startReportingServerProgress();
                return getRequestResultOrRetry(factory);
            } else {
                return result;
            }
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
            Logger.log(LogTypes.TYPE_WARNING_NETWORK, "Timed out listening to receive data during sync");
            responseError = PullTaskResult.CONNECTION_TIMEOUT;
        } catch (UnknownHostException e) {
            e.printStackTrace();
            Logger.log(LogTypes.TYPE_WARNING_NETWORK, "Couldn't sync due to bad network");
            responseError = PullTaskResult.UNREACHABLE_HOST;
        } catch (AuthenticationInterceptor.PlainTextPasswordException e) {
            e.printStackTrace();
            Logger.log(LogTypes.TYPE_ERROR_CONFIG_STRUCTURE, "Encountered PlainTextPasswordException during sync: Sending password over HTTP");
            responseError = PullTaskResult.AUTH_OVER_HTTP;
        } catch (CaptivePortalRedirectException e) {
            e.printStackTrace();
            Logger.log(LogTypes.TYPE_WARNING_NETWORK, "Couldn't sync due to presense of captive portal");
            responseError = PullTaskResult.CAPTIVE_PORTAL;
        } catch (IOException e) {
            e.printStackTrace();
            Logger.log(LogTypes.TYPE_WARNING_NETWORK, "Couldn't sync due to IO Error|" + e.getMessage());
        } catch (UnknownSyncError e) {
            e.printStackTrace();
            Logger.log(LogTypes.TYPE_WARNING_NETWORK, "Couldn't sync due to Unknown Error|" + e.getMessage());
        }

        wipeLoginIfItOccurred();
        this.publishProgress(PROGRESS_DONE);
        return new ResultAndError<>(responseError);
    }

    /**
     * @return the proper result, or null if we have not yet been able to determine the result to
     * return
     */
    private ResultAndError<PullTaskResult> makeRequestAndHandleResponse(AndroidTransactionParserFactory factory)
            throws IOException, UnknownSyncError {

        RemoteDataPullResponse pullResponse =
                dataPullRequester.makeDataPullRequest(this, requestor, server, !loginNeeded);

        int responseCode = pullResponse.responseCode;
        Logger.log(LogTypes.TYPE_USER,
                "Data pull request opened. Response code: " + responseCode);

        if (responseCode == 401) {
            return handleAuthFailed();
        } else if (responseCode >= 200 && responseCode < 300) {
            if (responseCode == 202) {
                return asyncRestoreHelper.handleRetryResponseCode(pullResponse);
            } else {
                return handleSuccessResponseCode(pullResponse, factory);
            }
        } else if (responseCode == 412) {
            return handleBadLocalState(factory);
        } else if (responseCode == 406) {
            return processErrorResponseWithMessage(pullResponse);
        } else if (responseCode == 500) {
            return handleServerError();
        } else if (responseCode == 503 || responseCode == 429) {
            return handleRateLimitedError();
        } else {
            throw new UnknownSyncError();
        }
    }

    private ResultAndError<PullTaskResult> processErrorResponseWithMessage(RemoteDataPullResponse pullResponse) {
        return new ResultAndError<>(PullTaskResult.ACTIONABLE_FAILURE, HttpUtils.parseUserVisibleError(pullResponse.getResponse()));
    }

    private ResultAndError<PullTaskResult> handleAuthFailed() {
        wipeLoginIfItOccurred();
        Logger.log(LogTypes.TYPE_USER, "Bad Auth Request for user!|" + username);
        return new ResultAndError<>(PullTaskResult.AUTH_FAILED);
    }

    /**
     * @return the proper result, or null if we have not yet been able to determine the result to
     * return
     */
    private ResultAndError<PullTaskResult> handleSuccessResponseCode(
            RemoteDataPullResponse pullResponse, AndroidTransactionParserFactory factory)
            throws IOException, UnknownSyncError {

        asyncRestoreHelper.completeServerProgressBarIfShowing();
        handleLoginNeededOnSuccess();
        this.publishProgress(PROGRESS_AUTHED, 0);

        if (isCancelled()) {
            // About to enter data commit phase; last chance to finish early if cancelled.
            return new ResultAndError<>(PullTaskResult.CANCELLED);
        }

        this.publishProgress(PROGRESS_DOWNLOADING_COMPLETE, 0);
        Logger.log(LogTypes.TYPE_USER, "Remote Auth Successful|" + username);

        try {
            BitCache cache = pullResponse.writeResponseToCache(context);
            String syncToken = readInput(cache.retrieveCache(), factory);
            updateUserSyncToken(syncToken);

            onSuccessfulSync();
            return new ResultAndError<>(PullTaskResult.DOWNLOAD_SUCCESS);
        } catch (XmlPullParserException e) {
            wipeLoginIfItOccurred();
            e.printStackTrace();
            Logger.log(LogTypes.TYPE_USER,
                    "User Sync failed due to bad payload|" + e.getMessage());
            return new ResultAndError<>(PullTaskResult.BAD_DATA, e.getMessage());
        } catch (ActionableInvalidStructureException e) {
            wipeLoginIfItOccurred();
            e.printStackTrace();
            Logger.log(LogTypes.TYPE_USER,
                    "User Sync failed due to bad payload|" + e.getMessage());
            return new ResultAndError<>(PullTaskResult.BAD_DATA_REQUIRES_INTERVENTION,
                    e.getLocalizedMessage());
        } catch (InvalidStructureException e) {
            wipeLoginIfItOccurred();
            e.printStackTrace();
            Logger.log(LogTypes.TYPE_USER,
                    "User Sync failed due to bad payload|" + e.getMessage());
            return new ResultAndError<>(PullTaskResult.BAD_DATA, e.getMessage());
        } catch (UnfullfilledRequirementsException e) {
            e.printStackTrace();
            Logger.log(LogTypes.TYPE_ERROR_ASSERTION,
                    "User sync failed oddly, unfulfilled reqs |" + e.getMessage());
            throw new UnknownSyncError();
        } catch (IllegalStateException e) {
            e.printStackTrace();
            Logger.log(LogTypes.TYPE_ERROR_ASSERTION,
                    "User sync failed oddly, IllegalStateException |" + e.getMessage());
            throw new UnknownSyncError();
        } catch (RecordTooLargeException e) {
            wipeLoginIfItOccurred();
            e.printStackTrace();
            Logger.log(LogTypes.TYPE_ERROR_ASSERTION,
                    "Storage Full during user sync |" + e.getMessage());
            return new ResultAndError<>(PullTaskResult.STORAGE_FULL);
        }
    }

    private void handleLoginNeededOnSuccess() {
        if (loginNeeded) {
            // This is currently necessary to make sure that data is encoded, but there is
            // probably a better way to do it
            CommCareApplication.instance().startUserSession(
                    ByteEncrypter.unwrapByteArrayWithString(ukrForLogin.getEncryptedKey(), password),
                    ukrForLogin, false);
            wasKeyLoggedIn = true;
        }
    }

    /**
     * @return the proper result, or null if we have not yet been able to determine the result to
     * return
     */
    private ResultAndError<PullTaskResult> handleBadLocalState(AndroidTransactionParserFactory factory)
            throws UnknownSyncError {
        this.publishProgress(PROGRESS_RECOVERY_NEEDED);
        Logger.log(LogTypes.TYPE_USER, "Sync Recovery Triggered");
        Pair<Integer, String> returnCodeAndMessageFromRecovery = recover(requestor, factory);
        int returnCode = returnCodeAndMessageFromRecovery.first;
        String failureReason = returnCodeAndMessageFromRecovery.second;

        if (returnCode == PROGRESS_DONE) {
            // Recovery was successful
            onSuccessfulSync();
            return new ResultAndError<>(PullTaskResult.DOWNLOAD_SUCCESS);
        } else if (returnCode == PROGRESS_RECOVERY_FAIL_SAFE || returnCode == PROGRESS_RECOVERY_FAIL_BAD) {
            wipeLoginIfItOccurred();
            this.publishProgress(PROGRESS_DONE);
            return new ResultAndError<>(PullTaskResult.RECOVERY_FAILURE, failureReason);
        } else {
            throw new UnknownSyncError();
        }
    }

    private void onSuccessfulSync() {
        recordSuccessfulSyncTime(username);

        ExternalDataUpdateHelper.broadcastDataUpdate(context, null);

        if (loginNeeded) {
            CommCareApplication.instance().getAppStorage(UserKeyRecord.class).write(ukrForLogin);
        }

        Logger.log(LogTypes.TYPE_USER, "User Sync Successful|" + username);
        updateCurrentUser(password);
        this.publishProgress(PROGRESS_DONE);
    }

    private ResultAndError<PullTaskResult> handleServerError() {
        wipeLoginIfItOccurred();
        Logger.log(LogTypes.TYPE_USER, "500 Server Error during data pull|" + username);
        return new ResultAndError<>(PullTaskResult.SERVER_ERROR);
    }

    private ResultAndError<PullTaskResult> handleRateLimitedError() {
        wipeLoginIfItOccurred();
        Logger.log(LogTypes.TYPE_USER, "503 Server Error during data pull|" + username);
        return new ResultAndError<>(PullTaskResult.RATE_LIMITED_SERVER_ERROR);
    }

    private void wipeLoginIfItOccurred() {
        if (wasKeyLoggedIn) {
            CommCareApplication.instance().releaseUserResourcesAndServices();
        }
    }

    @Override
    public void tryAbort() {
        if (requestor != null) {
            requestor.abortCurrentRequest();
        }
    }

    private static void recordSuccessfulSyncTime(String username) {
        CommCareApplication.instance().getCurrentApp().getAppPreferences().edit()
                .putLong(SyncDetailCalculations.getLastSyncKey(username), new Date().getTime()).apply();
    }

    //TODO: This and the normal sync share a ton of code. It's hard to really... figure out the right way to
    private Pair<Integer, String> recover(CommcareRequestEndpoints requestor, AndroidTransactionParserFactory factory) {
        while (asyncRestoreHelper.retryWaitPeriodInProgress()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
            }

            if (isCancelled()) {
                return new Pair<>(PROGRESS_RECOVERY_FAIL_SAFE,
                        "Task was cancelled during recovery sync");
            }
        }

        // This chunk is the safe field of operations which can all fail in IO in such a way that
        // we can just report back that things didn't work and don't need to attempt any recovery
        // or additional work
        BitCache cache;
        try {
            // Make a new request without all of the flags
            RemoteDataPullResponse pullResponse =
                    dataPullRequester.makeDataPullRequest(this, requestor, server, false);

            if (!(pullResponse.responseCode >= 200 && pullResponse.responseCode < 300)) {
                return new Pair<>(PROGRESS_RECOVERY_FAIL_SAFE,
                        "Received a non-success response during recovery sync");
            } else if (pullResponse.responseCode == 202) {
                ResultAndError<PullTaskResult> result =
                        asyncRestoreHelper.handleRetryResponseCode(pullResponse);
                if (PullTaskResult.RETRY_NEEDED.equals(result.data)) {
                    asyncRestoreHelper.startReportingServerProgress();
                    return recover(requestor, factory);
                } else {
                    return new Pair<>(PROGRESS_RECOVERY_FAIL_SAFE,
                            "Retry response during recovery sync was improperly formed");
                }
            }

            // Grab a cache. The plan is to download the incoming data, wipe (move) the existing
            // db, and then restore fresh from the downloaded file
            cache = pullResponse.writeResponseToCache(context);
        } catch (IOException e) {
            e.printStackTrace();
            //Ok, well, we're bailing here, but we didn't make any changes
            Logger.log(LogTypes.TYPE_USER, "Sync Recovery Failed due to IOException|" + e.getMessage());
            return new Pair<>(PROGRESS_RECOVERY_FAIL_SAFE, "");
        }

        this.publishProgress(PROGRESS_RECOVERY_STARTED);
        Logger.log(LogTypes.TYPE_USER, "Sync Recovery payload downloaded");

        //Ok. Here's where things get real. We now have a stable copy of the fresh data from the
        //server, so it's "safe" for us to wipe the casedb copy of it.

        //CTS: We're not doing this in a super good way right now, need to be way more fault tolerant.
        //this is the temporary implementation of everything past this point

        //Wipe storage
        SQLiteDatabase userDb = CommCareApplication.instance().getUserDbHandle();
        userDb.beginTransaction();
        wipeStorageForFourTwelveSync(userDb);

        try {
            String syncToken = readInputWithoutCommit(cache.retrieveCache(), factory);
            updateUserSyncToken(syncToken);
            Logger.log(LogTypes.TYPE_USER, "Sync Recovery Successful");
            userDb.setTransactionSuccessful();
            return new Pair<>(PROGRESS_DONE, "");
        } catch (InvalidStructureException | XmlPullParserException
                | UnfullfilledRequirementsException | SessionUnavailableException
                | IOException e) {
            Logger.exception("Sync recovery failed|" + e.getLocalizedMessage(), e);
            return new Pair<>(PROGRESS_RECOVERY_FAIL_BAD, e.getLocalizedMessage());
        } finally {
            userDb.endTransaction();
            //destroy temp file
            cache.release();
        }
    }

    private void wipeStorageForFourTwelveSync(SQLiteDatabase userDb) {
        SqlStorage.wipeTableWithoutCommit(userDb, ACase.STORAGE_KEY);
        SqlStorage.wipeTableWithoutCommit(userDb, Ledger.STORAGE_KEY);
        SqlStorage.wipeTableWithoutCommit(userDb, AndroidCaseIndexTable.TABLE_NAME);
        EntityStorageCache.wipeCacheForCurrentAppWithoutCommit(userDb);
    }

    private void updateCurrentUser(String password) {
        SqlStorage<User> storage = CommCareApplication.instance().getUserStorage("USER", User.class);
        User u = storage.getRecordForValue(User.META_USERNAME, username);
        CommCareApplication.instance().getSession().setCurrentUser(u, password);
    }

    private void updateUserSyncToken(String syncToken) {
        SqlStorage<User> storage = CommCareApplication.instance().getUserStorage("USER", User.class);
        try {
            User u = storage.getRecordForValue(User.META_USERNAME, username);
            u.setLastSyncToken(syncToken);
            storage.write(u);
        } catch (NoSuchElementException nsee) {
            //TODO: Something here? Maybe figure out if we downloaded a user from the server and attach the data to it?
        }
    }

    private void initParsers(AndroidTransactionParserFactory factory) {
        factory.initCaseParser();
        factory.initStockParser();
        Hashtable<String, String> formNamespaces = FormSaveUtil.getNamespaceToFilePathMap(CommCareApplication.instance().getAppStorage(FormDefRecord.class));
        factory.initFormInstanceParser(formNamespaces);
    }

    private void parseStream(InputStream stream,
                             AndroidTransactionParserFactory factory)
            throws InvalidStructureException, IOException, XmlPullParserException,
            UnfullfilledRequirementsException {
        DataModelPullParser parser = new DataModelPullParser(stream, factory, true, false, this);
        parser.parse();
    }

    private String readInputWithoutCommit(InputStream stream,
                                          AndroidTransactionParserFactory factory)
            throws InvalidStructureException, IOException, XmlPullParserException,
            UnfullfilledRequirementsException {
        initParsers(factory);
        parseStream(stream, factory);
        return factory.getSyncToken();
    }

    private String readInput(InputStream stream, AndroidTransactionParserFactory factory)
            throws InvalidStructureException, IOException, XmlPullParserException,
            UnfullfilledRequirementsException {
        initParsers(factory);
        //this is _really_ coupled, but we'll tolerate it for now because of the absurd performance gains
        SQLiteDatabase db = CommCareApplication.instance().getUserDbHandle();
        db.beginTransaction();
        try {
            parseStream(stream, factory);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }

        //Return the sync token ID
        return factory.getSyncToken();
    }

    //BEGIN - OTA Listener methods below - Note that most of the methods
    //below weren't really implemented

    @Override
    public void onUpdate(int numberCompleted) {
        mCurrentProgress = numberCompleted;
        int millisecondsElapsed = (int)(System.currentTimeMillis() - mSyncStartTime);

        this.publishProgress(PROGRESS_PROCESSING, mCurrentProgress, mTotalItems, millisecondsElapsed);
    }

    @Override
    public void setTotalForms(int totalItemCount) {
        mTotalItems = totalItemCount;
        mCurrentProgress = 0;
        mSyncStartTime = System.currentTimeMillis();
        this.publishProgress(PROGRESS_PROCESSING, mCurrentProgress, mTotalItems, 0);
    }

    protected void reportServerProgress(int completedSoFar, int total) {
        publishProgress(PROGRESS_SERVER_PROCESSING, completedSoFar, total);
    }

    public void reportDownloadProgress(int totalRead) {
        publishProgress(PROGRESS_DOWNLOADING, totalRead);
    }

    public AsyncRestoreHelper getAsyncRestoreHelper() {
        return this.asyncRestoreHelper;
    }

    public enum PullTaskResult {
        DOWNLOAD_SUCCESS(AnalyticsParamValue.SYNC_SUCCESS),
        RETRY_NEEDED(AnalyticsParamValue.SYNC_FAIL_RETRY_NEEDED),
        EMPTY_URL(AnalyticsParamValue.SYNC_FAIL_EMPTY_URL),
        AUTH_FAILED(AnalyticsParamValue.SYNC_FAIL_AUTH),
        BAD_DATA(AnalyticsParamValue.SYNC_FAIL_BAD_DATA),
        BAD_DATA_REQUIRES_INTERVENTION(AnalyticsParamValue.SYNC_FAIL_BAD_DATA),
        UNKNOWN_FAILURE(AnalyticsParamValue.SYNC_FAIL_UNKNOWN),
        CANCELLED(AnalyticsParamValue.SYNC_FAIL_CANCELLED),
        ENCRYPTION_FAILURE(AnalyticsParamValue.SYNC_FAIL_ENCRYPTION),
        SESSION_EXPIRE(AnalyticsParamValue.SYNC_FAIL_SESSION_EXPIRE),
        RECOVERY_FAILURE(AnalyticsParamValue.SYNC_FAIL_RECOVERY),
        ACTIONABLE_FAILURE(AnalyticsParamValue.SYNC_FAIL_ACTIONABLE),
        UNREACHABLE_HOST(AnalyticsParamValue.SYNC_FAIL_UNREACHABLE_HOST),
        CONNECTION_TIMEOUT(AnalyticsParamValue.SYNC_FAIL_CONNECTION_TIMEOUT),
        SERVER_ERROR(AnalyticsParamValue.SYNC_FAIL_SERVER_ERROR),
        RATE_LIMITED_SERVER_ERROR(AnalyticsParamValue.SYNC_FAIL_RATE_LIMITED_SERVER_ERROR),
        STORAGE_FULL(AnalyticsParamValue.SYNC_FAIL_STORAGE_FULL),
        CAPTIVE_PORTAL(AnalyticsParamValue.SYNC_FAIL_CAPTIVE_PORTAL),
        AUTH_OVER_HTTP(AnalyticsParamValue.SYNC_FAIL_AUTH_OVER_HTTP);

        public final String analyticsFailureReasonParam;

        PullTaskResult(String analyticsParam) {
            this.analyticsFailureReasonParam = analyticsParam;
        }
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jonathancolt.nicity.view.adaptor;

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

/**
 *
 * @author jonathan
 */
public interface IFontConstants {

    final public static String cDefaultFontName = "System";

    public static final String cDialog = "Dialog";
    public static final String cDialogInput = "DialogInput";
    public static final String cSansSerif = "SansSerif";
    public static final String cSerif = "Serif";
    public static final String cMonospaced = "Monospaced";

    final public static int cPlain = 0;
    final public static int cBold = 1;
    final public static int cItalic = 2;
}


text:
/**
* @file CLocalVarsExtra.h
* @brief Additional script variable types.
*/

#ifndef _INC_CLOCALVARSEXTRA_H
#define _INC_CLOCALVARSEXTRA_H

#include "flat_containers/flat_map.hpp"
#include "sphere_library/CSString.h"

class CLocalFloatVars
{
	struct LexNoCaseLess
	{
		bool operator()(const CSString& str, const char* pBeg2) const;
	};
	using MapType = fc::vector_map<CSString, realtype, LexNoCaseLess>;

	MapType m_VarMap;

public:
	CLocalFloatVars() = default;
	~CLocalFloatVars() = default;

private:
	CLocalFloatVars(const CLocalFloatVars& copy);
	CLocalFloatVars& operator=(const CLocalFloatVars& other);

private: //setting, getting
	bool Set( const char* VarName, const char* VarValue );
	realtype GetVal( const char* VarName );

public: //setting, getting
	bool Insert( const char* VarName, const char* VarValue, bool fForceSet = false);
	CSString Get( const char* VarName );
	void Clear();
};

class CObjBase;

class CLocalObjMap
{
	using ObjMap = fc::vector_map<ushort, CObjBase*>;
	ObjMap m_ObjMap;

public:
	CLocalObjMap() = default;
	~CLocalObjMap() = default;
private:
	CLocalObjMap(const CLocalObjMap& copy);
	CLocalObjMap& operator=(const CLocalObjMap& other);

public:
	CObjBase * Get( ushort Number );
	bool Insert( ushort Number, CObjBase * pObj, bool fForceSet = false );
	void Clear();
};

#endif // _INC_CLOCALVARSEXTRA_H


text:
/**
 * --------------------------------------------------------------------------
 * Licensed under MIT https://github.com/sitevision/envision/blob/master/LICENSE
 * --------------------------------------------------------------------------
 */

import $ from 'jquery';
import CssUtil from './util/css-util';
import Util from './util/util';
import {
   getNode,
   getNodes,
   uniqueId,
   setStyle,
   setAttributes,
} from './util/nodes';

const NAME = 'envImageslider';
const TOUCHEVENT_WAIT = 500;
const SLIDE_WIDTH_PX = 80;

const lang = {
   sv: {
      prev: 'Föregående',
      next: 'Nästa',
   },
   en: {
      prev: 'Previous',
      next: 'Next',
   },
};

const DEFAULTS = {
   buttons: true,
   imageSlider: false,
   interval: 5000,
   keyboard: true,
   pause: 'hover',
   slide: false,
   swipe: true,
   wrap: true,
};

const SELECTORS = {
   ACTIVE: '.env-image-slider__item--active',
   ACTIVE__CHILD: '.env-image-slider__item--active > *',
   ACTIVE_DOT: '.env-is-active',
   ACTIVE_ITEM: '.env-image-slider__item--active.env-image-slider__item',
   DATA_SLIDE: '[data-move], [data-move-to]',
   SLIDER_DATA_ATTRIBUTE: `[data-image-slider]`,
   INDICATORS: '.env-image-slider__indicators',
   INDICATOR_ITEMS: '.env-image-slider__indicators > *',
   INNER: '.env-image-slider__inner',
   NEXT_PREV: '.env-image-slider--next, .env-image-slider--prev',
   ITEM: '.env-image-slider__item',
   THUMBNAILS: '.env-image-slider__thumbnails',
   THUMBNAIL__ITEMS: '.env-image-slider__thumbnails > *',
};

const ClassName = {
   ACTIVE: 'env-image-slider__item--active',
   ACTIVE_DOT: 'env-is-active',
   LEFT: 'env-image-slider__item--left',
   NEXT: 'env-image-slider__item--next',
   PREV: 'env-image-slider__item--prev',
   RIGHT: 'env-image-slider__item--right',
   SLIDE: 'env-image-slider--slide',
};

const Direction = {
   LEFT: 'left',
   NEXT: 'next',
   PREV: 'prev',
   RIGHT: 'right',
};

const Events = {
   KEYDOWN: 'keydown',
   MOUSEENTER: 'mouseenter',
   MOUSELEAVE: 'mouseleave',
   SLID: 'slid',
   SLIDE: 'slide',
   JQSLID: `slid.env.image-slider`, // Deprecated
   JQSLIDE: `slide.env.image-slider`, // Deprecated
   TOUCHEND: 'touchend',
   TOUCHMOVE: 'touchmove',
   TOUCHSTART: 'touchstart',
};

class Imageslider {
   #images;
   #indicatorsElement;
   #thumbnailElement;
   #interval;
   #isSliding;
   #activeElement;
   #config;

   constructor(element, config) {
      this.el = element;
      this.isPaused = false;
      this.#images = getNodes(SELECTORS.ITEM, this.el);
      this.#indicatorsElement = getNode(SELECTORS.INDICATORS, this.el);
      this.#thumbnailElement = getNode(SELECTORS.THUMBNAILS, this.el);
      this.#isSliding = false;
      this.#interval = null;
      this.#activeElement = null;

      typeof this.el.dataset.imageSlider === 'undefined' &&
         this.el.setAttribute('data-image-slider', '');

      this.settings(config);

      if (this.#images.length > 1 && config.buttons) {
         this._addSlideButtons();
      }

      this.#images.forEach((image, i) => {
         image.setAttribute('data-env-imageslider-index', i);
      });

      this._bindEvents();
   }

   next() {
      if (!this.#isSliding) {
         this._slide(Direction.NEXT);
      }
   }

   prev() {
      if (!this.#isSliding) {
         this._slide(Direction.PREV);
      }
   }

   nextWhenVisible() {
      if (!document.hidden) {
         this.next();
      }
   }

   pause(e) {
      if (!e) {
         this.isPaused = true;
      }

      clearInterval(this.#interval);
      this.#interval = null;
   }

   cycle(e) {
      if (!e) {
         this.isPaused = false;
      }

      if (this.#interval) {
         clearInterval(this.#interval);
         this.#interval = null;
      }

      if (this.#config.interval && !this.isPaused) {
         this.#interval = setInterval(
            (document.visibilityState ? this.nextWhenVisible : this.next).bind(
               this
            ),
            this.#config.interval
         );
      }
   }

   goTo(index) {
      this.#activeElement = getNode(SELECTORS.ACTIVE_ITEM, this.el);

      const activeIndex = this._getItemIndex(this.#activeElement);

      if (index > this.#images.length - 1 || index < 0) {
         return;
      }

      if (this.#isSliding) {
         return;
      }

      if (activeIndex === index) {
         this.pause();
         this.cycle();
         return;
      }

      const direction = index > activeIndex ? Direction.NEXT : Direction.PREV;

      this._slide(direction, this.#images[index]);
   }

   startTouchSlide(e) {
      this.touchstartx = e.touches[0].pageX;
   }

   moveTouchSlide(e) {
      this.touchmovex = e.touches[0].pageX;
      this.movex = -(this.touchstartx - this.touchmovex);
      this.moved = false;

      const activeItem = getNode(SELECTORS.ACTIVE__CHILD, this.el);

      setStyle(activeItem, 'transform', `translate3d(${this.movex}px, 0, 0)`);

      if (this.movex > SLIDE_WIDTH_PX) {
         this.prev();
         this.moved = true;
         setTimeout(() => {
            setStyle(activeItem, 'transform', `translate3d(0, 0, 0)`);
         }, TOUCHEVENT_WAIT);
      } else if (this.movex < -SLIDE_WIDTH_PX) {
         this.next();
         this.moved = true;
         setTimeout(() => {
            setStyle(activeItem, 'transform', `translate3d(0, 0, 0)`);
         }, TOUCHEVENT_WAIT);
      }
   }

   endTouchSlide() {
      if (!this.moved) {
         setStyle(
            getNode(SELECTORS.ACTIVE__CHILD, this.el),
            'transform',
            'translate3d(0, 0, 0)'
         );
      }
   }

   dispose() {
      this.el = this.el.cloneNode(true);
      delete this.el[NAME];
      delete this.el.envImagesliderJQ;
      this.el = null;
      this.#images = null;
      this.#interval = null;
      this.isPaused = null;
      this.#isSliding = null;
      this.#activeElement = null;
      this.#indicatorsElement = null;
      this.#thumbnailElement = null;
   }

   settings(config) {
      this.#config = Util.extend(
         {},
         DEFAULTS,
         this.el.dataset,
         Util.isPlainObject(this.#config) ? this.#config : {},
         config
      );
   }

   _addSlideButtons() {
      const sliderId = this.el.id;
      const container = getNode(SELECTORS.INNER, this.el);
      const prevButton = document.createElement('button');
      setAttributes(prevButton, {
         type: 'button',
         class: 'env-image-slider--prev',
         'data-move': 'prev',
         'data-target': `#${sliderId}`,
      });
      prevButton.innerHTML = `<svg class="env-image-slider__previous-icon env-icon env-icon-small">
               <use xlink:href="/sitevision/envision-icons.svg#icon-arrow-left"></use></svg>
               ${
                  this.#config.i18n.prev
               }`;

      const nextButton = document.createElement('button');
      setAttributes(nextButton, {
         type: 'button',
         class: 'env-image-slider--next',
         'data-move': 'next',
         'data-target': `#${sliderId}`,
      });
      nextButton.innerHTML = `<svg class="env-image-slider__previous-icon env-icon env-icon-small">
               <use xlink:href="/sitevision/envision-icons.svg#icon-arrow-right"></use></svg>
               ${
                  this.#config.i18n.next
               }`;

      container.appendChild(prevButton);
      container.appendChild(nextButton);
   }

   _getItemByDirection(direction, activeElement) {
      const isNextDirection = direction === Direction.NEXT;
      const activeIndex = this._getItemIndex(activeElement);
      const lastImageIndex = this.#images.length - 1;
      const isGoingToWrap =
         (!isNextDirection && activeIndex === 0) ||
         (isNextDirection && activeIndex === lastImageIndex);

      if (isGoingToWrap && !this.#config.wrap) {
         return activeElement;
      }

      const delta = isNextDirection ? 1 : -1;
      const itemIndex = (activeIndex + delta) % this.#images.length;

      return itemIndex === -1
         ? this.#images[lastImageIndex]
         : this.#images[itemIndex];
   }

   _bindEvents() {
      this.el.addEventListener('click', (e) => this._click(e));

      if (this.#config.keyboard) {
         this.el.addEventListener(Events.KEYDOWN, (e) => this._keydown(e));
      }

      if (
         this.#config.pause === 'hover' &&
         this.#config.imageSlider === 'cycle'
      ) {
         this.el.addEventListener(Events.MOUSEENTER, (e) => this.pause(e));
         this.el.addEventListener(Events.MOUSELEAVE, (e) => this.cycle(e));

         if (CssUtil.isTouch()) {
            this.el.addEventListener(Events.TOUCHEND, () => {
               this.pause();
               if (this.touchTimeout) {
                  clearTimeout(this.touchTimeout);
               }
               this.touchTimeout = setTimeout(
                  (e) => this.cycle(e),
                  TOUCHEVENT_WAIT,
                  this.#config.interval
               );
            });
         }
      }
      if (this.#config.swipe) {
         this._bindTouchSlider();
      }
   }

   _bindTouchSlider() {
      const container = getNode(SELECTORS.INNER, this.el);

      container.addEventListener(Events.TOUCHSTART, (e) => {
         this.startTouchSlide(e);
      });

      container.addEventListener(Events.TOUCHMOVE, (e) => {
         this.moveTouchSlide(e);
      });

      container.addEventListener(Events.TOUCHEND, (e) => {
         this.endTouchSlide(e);
      });
   }

   _keydown(e) {
      if (/input|textarea/i.test(e.target.tagName)) {
         return;
      }

      switch (e.key) {
         case 'ArrowLeft':
            e.preventDefault();
            this.prev();
            break;
         case 'ArrowRight':
            e.preventDefault();
            this.next();
            break;
         default:
            return;
      }
   }

   _click(e) {
      const clickTarget = e.target.closest(SELECTORS.DATA_SLIDE);

      if (!clickTarget) {
         return;
      }

      let dataSet = clickTarget.dataset;

      if (!dataSet.target || !document.querySelector(dataSet.target)) {
         return;
      }

      const targetEl = document.querySelector(dataSet.target);

      if (!targetEl || typeof targetEl.dataset.imageSlider === 'undefined') {
         return;
      }

      if (dataSet.moveTo) {
         const slideIndex = parseInt(dataSet.moveTo, 10);
         this.settings({ interval: false });
         this.goTo(slideIndex);
      } else if (
         dataSet.move === Direction.PREV ||
         dataSet.move === Direction.NEXT
      ) {
         this[dataSet.move]();
      }

      e.preventDefault();
   }

   _getItemIndex(element) {
      return parseInt(element.dataset.envImagesliderIndex, 10);
   }

   _triggerSlideEvent(targetElement, eventDirectionName) {
      const targetIndex = this._getItemIndex(targetElement);
      const fromIndex = this._getItemIndex(
         getNode(SELECTORS.ACTIVE_ITEM, this.el)
      );
      let slideEvent;

      // TODO: Delete if/else when jQuery dependency is removed
      if (this.el.envImagesliderJQ) {
         // Deprecated
         slideEvent = $.Event(Events.JQSLIDE, {
            targetElement,
            direction: eventDirectionName,
            from: fromIndex,
            to: targetIndex,
         });
         $(this.el).trigger(slideEvent);
         slideEvent.defaultPrevented = slideEvent.isDefaultPrevented();
      } else {
         slideEvent = new CustomEvent(Events.SLIDE, {
            bubbles: true,
            cancelable: true,
            detail: {
               direction: eventDirectionName,
               from: fromIndex,
               to: targetIndex,
            },
         });
         targetElement.dispatchEvent(slideEvent);
      }
      return slideEvent;
   }

   _setActiveIndicatorElement(element) {
      if (this.#indicatorsElement) {
         const active = getNode(SELECTORS.ACTIVE_DOT, this.#indicatorsElement);
         const nextIndicator = getNodes(
            SELECTORS.INDICATOR_ITEMS,
            this.#indicatorsElement
         )[this._getItemIndex(element)];
         active && active.classList.remove(ClassName.ACTIVE_DOT);
         nextIndicator && nextIndicator.classList.add(ClassName.ACTIVE_DOT);
      } else if (this.#thumbnailElement) {
         const active = getNode(SELECTORS.ACTIVE, this.#thumbnailElement);
         const nextIndicator = getNodes(
            SELECTORS.ACTIVE,
            this.#thumbnailElement
         )[this._getItemIndex(element)];
         active && active.classList.remove(ClassName.ACTIVE);
         nextIndicator && nextIndicator.classList.add(ClassName.ACTIVE);
      }
   }

   _slide(direction, element) {
      const activeElement = getNode(SELECTORS.ACTIVE_ITEM, this.el);
      const activeElementIndex = this._getItemIndex(activeElement);
      const nextElement = getNode(
         element ||
            (activeElement &&
               this._getItemByDirection(direction, activeElement))
      );
      const nextElementIndex = this._getItemIndex(nextElement);

      let directionalClassName;
      let orderClassName;
      let eventDirectionName;

      if (direction === Direction.NEXT) {
         directionalClassName = ClassName.LEFT;
         orderClassName = ClassName.NEXT;
         eventDirectionName = Direction.LEFT;
      } else {
         directionalClassName = ClassName.RIGHT;
         orderClassName = ClassName.PREV;
         eventDirectionName = Direction.RIGHT;
      }

      if (nextElement && nextElement.classList.contains(ClassName.ACTIVE)) {
         this.#isSliding = false;
         return;
      }

      const slideEvent = this._triggerSlideEvent(
         nextElement,
         eventDirectionName
      );

      if (slideEvent.defaultPrevented) {
         return;
      }

      if (!activeElement || !nextElement) {
         return;
      }

      this.#isSliding = true;

      this._setActiveIndicatorElement(nextElement);

      let slidEvent;

      // TODO: Delete if/else when jQuery dependency is removed
      if (this.el.envImagesliderJQ) {
         // Deprecated
         slidEvent = $.Event(Events.JQSLID, {
            relatedTarget: nextElement,
            direction: eventDirectionName,
            from: activeElementIndex,
            to: nextElementIndex,
         });
         slidEvent.defaultPrevented = slideEvent.isDefaultPrevented();
      } else {
         slidEvent = new CustomEvent(Events.SLID, {
            bubbles: true,
            cancelable: true,
            detail: {
               relatedTarget: nextElement,
               direction: eventDirectionName,
               from: activeElementIndex,
               to: nextElementIndex,
            },
         });
      }

      if (this.el.classList.contains(ClassName.SLIDE)) {
         nextElement.classList.add(orderClassName);

         CssUtil.reflow(nextElement);

         activeElement.classList.add(directionalClassName);
         nextElement.classList.add(directionalClassName);

         activeElement.addEventListener(
            'transitionend',
            () => {
               nextElement.classList.remove(
                  directionalClassName,
                  orderClassName
               );
               nextElement.classList.add(ClassName.ACTIVE);

               activeElement.classList.remove(
                  ClassName.ACTIVE,
                  orderClassName,
                  directionalClassName
               );

               this.#isSliding = false;

               if (this.el.envImagesliderJQ) {
                  $(this.el).trigger(slidEvent);
               } else {
                  this.el.dispatchEvent(slidEvent);
               }
            },
            { once: true }
         );
      } else {
         activeElement.classList.remove(ClassName.ACTIVE);
         nextElement.classList.add(ClassName.ACTIVE);

         this.#isSliding = false;

         // TODO: Delete if/else when jQuery dependency is removed
         if (this.el.envImagesliderJQ) {
            $(this.el).trigger(slideEvent);
         } else {
            this.el.dispatchEvent(slideEvent);
         }
      }
   }

   static _init(elements, settings, isJQuery) {
      const nodes = getNodes(elements);

      if (nodes.length > 0) {
         const sliders = nodes.map((node) => {
            uniqueId(node);
            let config;

            if (typeof settings === 'object') {
               config = {
                  ...DEFAULTS,
                  ...node.dataset,
                  ...settings,
                  i18n: Util.getLanguageOptions(settings?.i18n, lang, node),
               };
            } else {
               config = {
                  ...DEFAULTS,
                  ...node.dataset,
                  i18n: Util.getLanguageOptions({}, lang, node),
               };
            }

            if (!node[NAME]) {
               node.envImagesliderJQ = isJQuery;
               node[NAME] = new Imageslider(node, config);
            } else {
               node[NAME].settings(
                  Util.extend({}, { ...node.dataset, ...settings })
               );
            }

            const action =
               typeof settings === 'string' ? settings : config.move;

            if (typeof settings === 'number') {
               node[NAME].goTo(settings);
            } else if (typeof action === 'string') {
               if (node[NAME][action] === undefined) {
                  throw new Error(`No method named "${action}"`);
               }
               node[NAME][action]();
            }

            if (config.interval && config.imageSlider === 'cycle') {
               node[NAME].pause();
               node[NAME].cycle();
            }
            return node[NAME];
         });
         return sliders;
      }
   }

   static _jQueryInterface(config) {
      Util.consoleWarning('jQuery', NAME);
      return this.each(() => {
         const nodes = getNodes(this);
         nodes.forEach((node) => {
            Imageslider._init(node, config, true);
         });
      });
   }
}

if (typeof document !== 'undefined') {
   window.addEventListener('load', () => {
      const imageSliders = getNodes(SELECTORS.SLIDER_DATA_ATTRIBUTE);
      if (imageSliders.length > 0) {
         Imageslider._init(imageSliders);
      }
   });

   // Deprecated
   const NO_CONFLICT = $.fn[NAME];
   $.fn[NAME] = Imageslider._jQueryInterface;
   $.fn[NAME].Constructor = Imageslider;
   $.fn[NAME].noConflict = () => {
      $.fn[NAME] = NO_CONFLICT;
      return Imageslider._jQueryInterface;
   };
}

export default async (elements, settings) => {
   return Imageslider._init(elements, settings);
};


text:
redirect_to:
- http://tech.hbc.com/2015-01-20-i-cant-get-no-satisfaction-ramblings-on-the.html
layout:: post
title: 'I Can''t Get No Satisfaction: Ramblings on the First Agile Principle'
date: '2015-01-20T22:18:00-05:00'
tags:
- agile
- agile methodology
- agile manifesto
- personal development
- heather fleming
- Gilt
- Gilt Groupe
- Gilt Tech
- gilttech
- software development
- technology
tumblr_url: http://tech.gilt.com/post/108701264319/i-cant-get-no-satisfaction-ramblings-on-the
---

This is part of a series of ramblings on the Principles behind the Agile Manifesto, reposted with permission from Incremental Me.

“Our highest priority is to satisfy the customer through early and continuous delivery of valuable software.”

In software development…

In order to satisfy the customer you have to truly understand what the customer needs.

Sometimes what a customer wants is very different than what a customer needs.

Keep asking "Why? Why? Why?"

This requires the customer to be very much engaged in what is happening.  They need to be able to express whether or not they are satisfied in real-time.

Early and continuous delivery of valuable software is pretty difficult to do.

What is "early"?  Perhaps "incremental" is more appropriate.  I'm assuming this wasn't intended to be "early" in the traditional, calendar-time based meaning.

Continuous delivery == constantly changing, hopefully for the better.

There is no such thing as "scope creep" in Agile!

It is of value if it satisfies the customer, therefore the customer must determine what "valuable" means.

But… If delivery is continuous, when are we "done"?  Perhaps never.  Satisfaction is a tricky beast.

In life…

In order to be satisfied, you must actually understand what you really need to be happy.

What you want is not necessarily what you need.

Perhaps in order to get at the core of what you really need, you have to ask myself "Why do you want X?"

You can't "check-out".  In order for this to work you need to be present and engaged in your life and incrementally improving it.

You also need to start NOW and continuously deliver on those needs in the form of changes for the better.

“Working software” in life is a means by which the need is satisfied.  This could be anything from eating well, getting enough rest, to treating yourself with the same kindness and respect you give your friends.

The key is to first really understand what your needs are — what will it take to be satisfied?

And finally, admitting that you am a work-in-progress.  There is no “done”.


text:
class Foo {}
class Foo extends Bar {}


text:
"""Tests for forward and backwards compatibility utilities."""

import datetime
import os
from tensorflow.python.compat import compat
from tensorflow.python.platform import test

class CompatTest(test.TestCase):

  def _compatibility_date(self):
    date = compat._FORWARD_COMPATIBILITY_HORIZON  # pylint: disable=protected-access
    return (date.year, date.month, date.day)

  def _n_days_after(self, n):
    date = compat._FORWARD_COMPATIBILITY_HORIZON + datetime.timedelta(days=n)  # pylint: disable=protected-access
    return (date.year, date.month, date.day)

  def test_basic(self):
    compatibility_date = self._compatibility_date()
    one_day_before = self._n_days_after(-1)
    self.assertTrue(compat.forward_compatible(*one_day_before))
    self.assertFalse(compat.forward_compatible(*compatibility_date))

  def test_past(self):
    with compat.forward_compatibility_horizon(2018, 9, 18):
      self.assertTrue(compat.forward_compatible(2020, 4, 4))

  def test_decorator(self):
    compatibility_date = self._compatibility_date()
    one_day_after = self._n_days_after(1)
    with compat.forward_compatibility_horizon(*one_day_after):
      self.assertTrue(compat.forward_compatible(*compatibility_date))
      self.assertFalse(compat.forward_compatible(*one_day_after))

    # After exiting context manager, value should be reset.
    self.assertFalse(compat.forward_compatible(*compatibility_date))

  def test_decorator_with_failure(self):
    compatibility_date = self._compatibility_date()
    one_day_after = self._n_days_after(1)

    class DummyError(Exception):
      pass

    try:
      with compat.forward_compatibility_horizon(*one_day_after):
        raise DummyError()
    except DummyError:
      pass  # silence DummyError

    # After exiting context manager, value should be reset.
    self.assertFalse(compat.forward_compatible(*compatibility_date))

  def test_environment_override(self):
    var_name = 'TF_FORWARD_COMPATIBILITY_DELTA_DAYS'

    def remove_os_environment_var():
      try:
        del os.environ[var_name]
      except KeyError:
        pass

    self.addCleanup(remove_os_environment_var)

    compatibility_date = self._compatibility_date()
    one_day_before = self._n_days_after(-1)
    one_day_after = self._n_days_after(1)
    ten_days_after = self._n_days_after(10)
    nine_days_after = self._n_days_after(9)

    self.assertTrue(compat.forward_compatible(*one_day_before))
    self.assertFalse(compat.forward_compatible(*compatibility_date))
    self.assertFalse(compat.forward_compatible(*one_day_after))
    self.assertFalse(compat.forward_compatible(*nine_days_after))
    self.assertFalse(compat.forward_compatible(*ten_days_after))

    os.environ[var_name] = '10'
    compat._update_forward_compatibility_date_number()
    self.assertTrue(compat.forward_compatible(*one_day_before))
    self.assertTrue(compat.forward_compatible(*compatibility_date))
    self.assertTrue(compat.forward_compatible(*one_day_after))
    self.assertTrue(compat.forward_compatible(*nine_days_after))
    self.assertFalse(compat.forward_compatible(*ten_days_after))

    del os.environ[var_name]
    compat._update_forward_compatibility_date_number()
    self.assertTrue(compat.forward_compatible(*one_day_before))
    self.assertFalse(compat.forward_compatible(*compatibility_date))
    self.assertFalse(compat.forward_compatible(*one_day_after))
    self.assertFalse(compat.forward_compatible(*nine_days_after))
    self.assertFalse(compat.forward_compatible(*ten_days_after))

    # Now test interaction between environment variable and context func.
    os.environ[var_name] = '10'
    compat._update_forward_compatibility_date_number()
    self.assertTrue(compat.forward_compatible(*one_day_after))
    with compat.forward_compatibility_horizon(*one_day_after):
      self.assertTrue(compat.forward_compatible(*one_day_before))
      self.assertTrue(compat.forward_compatible(*compatibility_date))
      self.assertFalse(compat.forward_compatible(*one_day_after))
      self.assertFalse(compat.forward_compatible(*nine_days_after))
      self.assertFalse(compat.forward_compatible(*ten_days_after))
    self.assertTrue(compat.forward_compatible(*one_day_after))

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