text:
package org.camunda.bpm.engine.impl.cmd;

import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotEmpty;
import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotNull;
import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNumberOfElements;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.camunda.bpm.engine.impl.cfg.CommandChecker;
import org.camunda.bpm.engine.impl.event.EventType;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.persistence.entity.EventSubscriptionEntity;
import org.camunda.bpm.engine.impl.persistence.entity.EventSubscriptionManager;

/**
 * @author Daniel Meyer
 * @author Joram Barrez
 */
public class MessageEventReceivedCmd implements Command<Void>, Serializable {

  private static final long serialVersionUID = 1L;

  protected final String executionId;
  protected final Map<String, Object> processVariables;
  protected final Map<String, Object> processVariablesLocal;
  protected final String messageName;
  protected boolean exclusive = false;

  public MessageEventReceivedCmd(String messageName, String executionId, Map<String, Object> processVariables) {
    this(messageName, executionId, processVariables, null);
  }

  public MessageEventReceivedCmd(String messageName, String executionId, Map<String, Object> processVariables, Map<String, Object> processVariablesLocal) {
    this.executionId = executionId;
    this.messageName = messageName;
    this.processVariables = processVariables;
    this.processVariablesLocal = processVariablesLocal;
  }

  public MessageEventReceivedCmd(String messageName, String executionId, Map<String, Object> processVariables, Map<String, Object> processVariablesLocal, boolean exclusive) {
    this(messageName, executionId, processVariables, processVariablesLocal);
    this.exclusive = exclusive;
  }

  @Override
  public Void execute(CommandContext commandContext) {
    ensureNotNull("executionId", executionId);

    EventSubscriptionManager eventSubscriptionManager = commandContext.getEventSubscriptionManager();
    List<EventSubscriptionEntity> eventSubscriptions = null;
    if (messageName != null) {
      eventSubscriptions = eventSubscriptionManager.findEventSubscriptionsByNameAndExecution(
              EventType.MESSAGE.name(), messageName, executionId, exclusive);
    } else {
      eventSubscriptions = eventSubscriptionManager.findEventSubscriptionsByExecutionAndType(
          executionId, EventType.MESSAGE.name(), exclusive);
    }

    ensureNotEmpty("Execution with id '" + executionId + "' does not have a subscription to a message event with name '" + messageName + "'", "eventSubscriptions", eventSubscriptions);
    ensureNumberOfElements("More than one matching message subscription found for execution " + executionId, "eventSubscriptions", eventSubscriptions, 1);

    // there can be only one:
    EventSubscriptionEntity eventSubscriptionEntity = eventSubscriptions.get(0);

    // check authorization
    String processInstanceId = eventSubscriptionEntity.getProcessInstanceId();
    for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
      checker.checkUpdateProcessInstanceById(processInstanceId);
    }

    eventSubscriptionEntity.eventReceived(processVariables, processVariablesLocal, null, false);

    return null;
  }

}


text:
declare var jStat: any;
declare var THREE: any;
declare var turf: any;
declare var scene: any;
declare var QActions: any;

import {Resource} from './resource';

export const SUCCESS: number = 1;
export const FAILED: number = 2;
export const RUNNING: number = 3;

export function createCSVURI(data: any[]) {
  var dataString;
  var URI;
  var csvContent = "data:text/csv;charset=utf-8,";
  var csvContentArray = [];
  data.forEach(function(infoArray) {
    dataString = infoArray.join(",");
    csvContentArray.push(dataString);
  });
  csvContent += csvContentArray.join("\n");
  URI = encodeURI(csvContent);
  return URI;
}

export function arrayFromRange(start, end, step) {
  var range = [];
  var i = start;
  while (i < end) {
    range.push(i);
    i += step;
  }
  return range;
}

/**
* shuffle - fisher-yates shuffle
*/
export function shuffle(array: any[], rng: any) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(rng.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

export function generateUUID(): string {
  // http://www.broofa.com/Tools/Math.uuid.htm
  var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  var uuid = new Array(36);
  var rnd = 0, r;

  for (var i = 0; i < 36; i++) {
    if (i == 8 || i == 13 || i == 18 || i == 23) {
      uuid[i] = '-';
    } else if (i == 14) {
      uuid[i] = '4';
    } else {
      if (rnd <= 0x02) rnd = 0x2000000 + (Math.random() * 0x1000000) | 0;
      r = rnd & 0xf;
      rnd = rnd >> 4;
      uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
    }
  }
  return uuid.join('');
}

export function always(a) {
  if (a === SUCCESS) {
    return SUCCESS;
  } else {
    return FAILED;
  }
}

export function eventually(a) {
  if (a === SUCCESS) {
    return SUCCESS;
  } else {
    return RUNNING;
  }
}

export function equalTo(a, b) {
  if (a === b) {
    return SUCCESS;
  } else {
    return FAILED;
  }
}

export function not(result) {
  var newResult;
  if (result === SUCCESS) {
    newResult = FAILED;
  } else if (result === FAILED) {
    newResult = SUCCESS;
  }
  return newResult;
}

export function notEqualTo(a, b) {
  if (a !== b) {
    return SUCCESS;
  } else {
    return FAILED;
  }
}

export function gt(a, b) {
  if (a > b) {
    return SUCCESS;
  } else {
    return FAILED;
  }
}

export function gtEq(a, b) {
  if (a >= b) {
    return SUCCESS;
  } else {
    return FAILED;
  }
}

export function lt(a, b) {
  if (a < b) {
    return SUCCESS;
  } else {
    return FAILED;
  }
}

export function ltEq(a, b) {
  if (a <= b) {
    return SUCCESS;
  } else {
    return FAILED;
  }
}

export function hasProp(a, b) {
  a = a || false;
  if (a === b) {
    return SUCCESS;
  } else {
    return FAILED;
  }
}

export function inRange(a, b) {
  if (b >= a[0] && b <= a[1]) {
    return SUCCESS;
  } else {
    return FAILED;
  }
}

export function notInRange(a, b) {
  if (b >= a[0] && b <= a[1]) {
    return FAILED;
  } else {
    return SUCCESS;
  }
}

export function getMatcherString(check) {
  var string = null;
  switch (check) {
    case equalTo:
      string = "equal to";
      break;
    case notEqualTo:
      string = "not equal to";
      break;
    case gt:
      string = "greater than";
      break;
    case gtEq:
      string = "greater than or equal to";
      break;
    case lt:
      string = "less than";
      break;
    case ltEq:
      string = "less than or equal to";
      break;
    case hasProp:
      string = "has the property";
      break;
    default:
      try {
        string = "not a defined matcher";
      } catch (e) {
        console.log(e);
      }
      break;
  }
  return string;
}

export function setMin(params, keys?) {
  for (var param in params) {
    if (typeof (keys) !== 'undefined' && keys.indexOf(param) !== -1) {
      params[param].current = params[param].value - params[param].error;
    } else if (typeof (keys) === 'undefined') {
      params[param].current = params[param].value - params[param].error;
    }
  }
}

export function setMax(params, keys?) {
  for (var param in params) {
    if (typeof (keys) !== 'undefined' && keys.indexOf(param) !== -1) {
      params[param].current = params[param].value + params[param].error;
    } else if (typeof (keys) === 'undefined') {
      params[param].current = params[param].value + params[param].error;
    }
  }
}

export function setStandard(params, keys?) {
  for (var param in params) {
    if (typeof (keys) !== 'undefined' && keys.indexOf(param) !== -1) {
      params[param].current = params[param].value;
    } else if (typeof (keys) === 'undefined') {
      params[param].current = params[param].value;
    }
  }
}

export function dataToMatrix(items: any[], stdized = false) {
  let data = [];
  for (let i = 0; i < items.length; i++) {
    let item = items[i];
    if (stdized) {
      item = scale(item);
    }
    item.forEach((x, ii) => {
      if (typeof data[ii] === 'undefined') {
        data[ii] = [1, x];
      } else {
        data[ii].push(x);
      }
    });
  }
  return data;
}

export function categoriesToVector(data:any[]){
  let values = [];
  let keys = {};
  let matrix;
  let idx = 0;
  data.forEach((x) => {
    let key = x + '';
    if(!(key in keys)){
        values.push(key);
        keys[key] = values.length - 1;
    }
  });
  matrix = data.map((y) => {
    let z = values.map((v) => {return 0});
    let idx = keys[y + ''];
    z[idx] = 1;
    return z;
  })
  return {labels:keys, data: matrix};
}

export function scale(vals: any, center?: number, scale?: number) {
  if (typeof vals === 'number') {
    return (vals - center) / scale;
  } else {
    center = center || jStat.mean(vals);
    scale = scale || jStat.stdev(vals);
    return vals.map((d: number) => {
      return (d - center) / scale;
    })
  }
}

export function scaleInv(vals: any, center: number, scale: number) {
  if (typeof vals === 'number') {
    return vals * scale + center;
  } else {
    return vals.map((d: number) => {
      return d * scale + center;
    });
  }
}

/*
* relative to the mean, how many sds
*/
export function standardized(arr: number[]) {
  let std = jStat.stdev(arr);
  let mean = jStat.mean(arr);
  let standardized = arr.map((d) => {
    return (d - mean) / std;
  })
  return standardized;
}

/*
* between 0 and 1 when min and max are known
*/
export function normalize(x: number, min: number, max: number) {
  let val = x - min;
  return val / (max - min);
}

/*
* give the real unit value
*/
export function invNorm(x: number, min: number, max: number) {
  return (x * max - x * min) + min;
}

/*
*
*/
export function randRange(min: number, max: number) {
  return (max - min) * Math.random() + min;
}

export function getRange(data: any[], prop: string) {
  let range = {
    min: 1e15,
    max: -1e15
  };
  for (let i = 0; i < data.length; i++) {
    if (range.min > data[i][prop]) {
      range.min = data[i][prop];
    }
    if (range.max < data[i][prop]) {
      range.max = data[i][prop];
    }
  }
  return range;
}

export class Match {
  static gt(a: number, b: number) {
    if (a > b) {
      return SUCCESS;
    }
    return FAILED;
  }
  static ge(a: number, b: number) {
    if (a >= b) {
      return SUCCESS;
    }
    return FAILED;
  }
  static lt(a: number, b: number) {
    if (a < b) {
      return SUCCESS;
    }
    return FAILED;
  }
  static le(a: number, b: number) {
    if (a <= b) {
      return SUCCESS;
    }
    return FAILED;
  }
  static always(a) {
    if (a === SUCCESS) {
      return SUCCESS;
    } else {
      return FAILED;
    }
  }

  static eventually(a) {
    if (a === SUCCESS) {
      return SUCCESS;
    } else {
      return RUNNING;
    }
  }

  static equalTo(a, b) {
    if (a === b) {
      return SUCCESS;
    } else {
      return FAILED;
    }
  }

  static not(result) {
    var newResult;
    if (result === SUCCESS) {
      newResult = FAILED;
    } else if (result === FAILED) {
      newResult = SUCCESS;
    }
    return newResult;
  }

  static notEqualTo(a, b) {
    if (a !== b) {
      return SUCCESS;
    } else {
      return FAILED;
    }
  }

  static gtEq(a, b) {
    if (a >= b) {
      return SUCCESS;
    } else {
      return FAILED;
    }
  }

  static ltEq(a, b) {
    if (a <= b) {
      return SUCCESS;
    } else {
      return FAILED;
    }
  }

  static hasProp(a, b) {
    a = a || false;
    if (a === b) {
      return SUCCESS;
    } else {
      return FAILED;
    }
  }

  static inRange(a, b) {
    if (b >= a[0] && b <= a[1]) {
      return SUCCESS;
    } else {
      return FAILED;
    }
  }

  static notInRange(a, b) {
    if (b >= a[0] && b <= a[1]) {
      return FAILED;
    } else {
      return SUCCESS;
    }
  }
}

export function addResources(arr, template, number) {
  for (var i = 0; i < number; i++) {
    arr.push(new Resource(template));
  }
  return arr;
}

export function generatePop(numAgents: number, options: any, type: any, boundaries: any, currentAgentId: number, rng: any) {
  var pop = [];
  var locs = {
    type: 'FeatureCollection',
    features: []
  };
  options = options || [];
  type = type || 'continuous';
  for (var a = 0; a < numAgents; a++) {
    pop[a] = {
      id: currentAgentId,
      type: type,
      states: {}
    };
    //movement params
    pop[a].movePerDay = rng.normal(2500 * 24, 1000); // m/day
    pop[a].prevX = 0;
    pop[a].prevY = 0;
    pop[a].movedTotal = 0;

    if (pop[a].type === 'continuous') {

      pop[a].mesh = new THREE.Mesh(new THREE.TetrahedronGeometry(1, 1), new THREE.MeshBasicMaterial({
        color: 0x000000
      }));
      pop[a].mesh.qId = pop[a].id;
      pop[a].mesh.type = 'agent';

      pop[a].position = { x: 0, y: 0, z: 0 };

      pop[a].boundaryGroup = options.groupName
      pop[a].position.x = rng.randRange(boundaries.left, boundaries.right);
      pop[a].position.y = rng.randRange(boundaries.bottom, boundaries.top);

      pop[a].mesh.position.x = pop[a].position.x;
      pop[a].mesh.position.y = pop[a].position.y;

      if (typeof scene !== 'undefined') {
        scene.add(pop[a].mesh);
      }
    }

    if (pop[a].type === 'geospatial') {
      locs.features[a] = turf.point([rng.randRange(-75.1467, -75.1867), rng.randRange(39.9200, 39.9900)]);
      pop[a].location = locs.features[a];
      pop[a].location.properties.agentRefID = pop[a].id;
    }

    pop[a] = assignParams(pop[a], options, rng);
    currentAgentId++;
  }

  for (let a = 0; a < pop.length; a++) {
    for (let key in pop[a].states) {
      pop[a][pop[a].states[key]] = true;
    }
  }
  return [pop, locs];
}

export function assignParams(targetObj: any, params:any[], rng:any){
  for (let key in params) {
    targetObj[key] = assignParam(targetObj, params[key], key, rng);
  }
  return targetObj;
}

export function assignParam(targetObj:any, param:any, key:string, rng:any){
  if (typeof param.states !== 'undefined') {
    targetObj.states[key] = rng.pick(param.states.params[0], param.states.params[1]);
    return targetObj.states[key];
  }
  if (typeof param.distribution !== 'undefined') {
    targetObj[key] = rng[param.distribution.name](param.distribution.params[0], param.distribution.params[1]);
  }
  if (typeof param.action !== 'undefined') {
    targetObj[key] = QActions[param.action];
  }
  if (typeof param.assign !== 'undefined') {
    targetObj[key] = param.assign;
  }
  return targetObj[key];
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals
from django.test import LiveServerTestCase, TestCase
from django.core.urlresolvers import reverse
from django.core.management import call_command
from django.test.utils import override_settings
from django.contrib.auth.models import User
from django.core.cache import caches
from django.db import IntegrityError
from django.template import defaultfilters

from dynamic_preferences.serializers import *
from dynamic_preferences import user_preferences_registry, global_preferences_registry
from dynamic_preferences.models import UserPreferenceModel, GlobalPreferenceModel
from dynamic_preferences.registries import autodiscover, clear
from dynamic_preferences.managers import PreferencesManager
from dynamic_preferences.forms import global_preference_form_builder, user_preference_form_builder

from .types import *
from .test_app.dynamic_preferences_registry import *

class BaseTest(object):

    def tearDown(self):
        caches['default'].clear()

class TestTutorial(BaseTest, TestCase):

    """
    Test everything from the tutorial
    """

    def setUp(self):
        self.henri = User(
            username="henri", password="test", email="henri@henri.com")
        self.henri.save()

    def test_quickstart(self):
        global_preferences = global_preferences_registry.manager()

        self.assertEqual(global_preferences['user__registration_allowed'], False)

        global_preferences['user__registration_allowed'] = True

        self.assertEqual(global_preferences['user__registration_allowed'], True)
        self.assertEqual(GlobalPreferenceModel.objects.get(
            section="user", name="registration_allowed").value, True)

        self.assertEqual(self.henri.preferences['misc__favourite_colour'], 'Green')

        self.henri.preferences['misc__favourite_colour'] = 'Blue'

        self.assertEqual(self.henri.preferences['misc__favourite_colour'], 'Blue')

        self.assertEqual(UserPreferenceModel.objects.get(
            section="misc", name="favourite_colour", instance=self.henri).value, 'Blue')

class TestModels(BaseTest, TestCase):

    def test_adding_user_create_default_preferences(self):

        u = User(username="post_create")
        u.save()

        self.assertEqual(
            len(u.preferences), len(user_preferences_registry.preferences()))

    def test_global_preferences_manager_get(self):
        global_preferences = global_preferences_registry.manager()
        self.assertEqual(global_preferences['no_section'], False)

    def test_global_preferences_manager_set(self):
        global_preferences = global_preferences_registry.manager()
        global_preferences['no_section'] = True
        self.assertEqual(global_preferences['no_section'], True)

    def test_can_cache_single_preference(self):

        manager = global_preferences_registry.manager()
        v = manager['no_section']
        with self.assertNumQueries(0):
            v = manager['no_section']
            v = manager['no_section']
            v = manager['no_section']

    def test_can_cache_all_preferences(self):

        manager = global_preferences_registry.manager()
        manager.all()
        with self.assertNumQueries(0):
            manager.all()
            manager.all()
            manager.all()

    def test_cache_invalidate_on_save(self):

        manager = global_preferences_registry.manager()
        model_instance = manager.create_db_pref(section=None, name='no_section', value=False)

        with self.assertNumQueries(0):
            assert not manager['no_section']
            manager['no_section']

        model_instance.value = True
        model_instance.save()

        with self.assertNumQueries(0):
            assert manager['no_section']
            manager['no_section']

class TestDynamicPreferences(BaseTest, TestCase):

    def setUp(self):

        self.test_user = User(
            username="test", password="test", email="test@test.com")
        self.test_user.save()

    def test_manager_is_attached_to_each_referenced_instance(self):
        self.assertTrue(isinstance(self.test_user.preferences, PreferencesManager))

    def test_preference_is_saved_to_database(self):

        self.test_user.preferences['test__TestUserPref1'] = 'new test value'

        test_user_pref1 = UserPreferenceModel.objects.get(
            section="test", name="TestUserPref1", instance=self.test_user)

        self.assertEqual(self.test_user.preferences['test__TestUserPref1'], "new test value")

    def test_per_instance_preference_stay_unique_in_db(self):

        self.test_user.preferences['test__TestUserPref1'] = 'new value'

        duplicate = UserPreferenceModel(
            section="test", name="TestUserPref1", instance=self.test_user)

        with self.assertRaises(IntegrityError):
            duplicate.save()

    def test_preference_value_set_to_default(self):

        pref = user_preferences_registry.get("TestUserPref1", "test")

        value = self.test_user.preferences['test__TestUserPref1']
        self.assertEqual(pref.default, value)
        instance = UserPreferenceModel.objects.get(
            section="test", name="TestUserPref1", instance=self.test_user)

    def test_preference_model_manager_to_dict(self):
        manager = global_preferences_registry.manager()
        call_command('checkpreferences', verbosity=1, interactive=False)
        expected = {u'test__TestGlobal1': u'default value', u'test__TestGlobal2': False, u'test__TestGlobal3': False,
            u'no_section': False, u'user__max_users': 100, u'user__items_per_page': 25, u'user__registration_allowed': False}
        self.assertDictEqual(manager.all(), expected)

    def test_user_preference_model_manager_to_dict(self):
        user = self.test_user
        expected = {u'misc__favourite_colour': u'Green', u'misc__is_zombie': True, u'user__favorite_vegetable': 'C',
            u'test__SUserStringPref': u'Hello world!', u'test__SiteBooleanPref': False, u'test__TestUserPref1': u'default value', u'test__TestUserPref2': u''}
        self.assertEqual(
            user.preferences.all(), expected)

class TestPreferenceObjects(BaseTest, TestCase):

    def test_can_get_to_string_notation(self):
        pref = global_preferences_registry.get('user__registration_allowed')

        self.assertEqual(pref.identifier(), 'user__registration_allowed')

    def test_boolean_field_class_instantiation(self):

        preference = TestBooleanPreference()

        self.assertEqual(preference.field.initial, False)

    def test_char_field_class_instantiation(self):

        preference = TestStringPreference()

        self.assertEqual(preference.field.initial, "hello world!")

    def test_choice_field(self):
        #preference = TestChoicePreference()
        pass
        #self.assertEqual(preference.field.initial, "FR")

class TestRegistry(BaseTest, TestCase):

    def test_can_retrieve_preference_using_dotted_notation(self):
        registration_allowed = global_preferences_registry.get(
            name="registration_allowed", section="user")
        dotted_result = global_preferences_registry.get(
            "user__registration_allowed")
        self.assertEqual(registration_allowed, dotted_result)

    def test_can_register_and_retrieve_preference_with_section_none(self):
        no_section_pref = global_preferences_registry.get(name="no_section")
        self.assertEqual(no_section_pref.section, None)

    def test_can_autodiscover_multiple_times(self):
        autodiscover()
        self.assertEqual(len(global_preferences_registry.preferences()), 7)
        self.assertEqual(len(user_preferences_registry.preferences()), 7)
        autodiscover()
        self.assertEqual(len(global_preferences_registry.preferences()), 7)
        self.assertEqual(len(user_preferences_registry.preferences()), 7)

    def test_can_autodiscover_user_preferences(self):

        clear()
        with self.assertRaises(KeyError):
            user_preferences_registry.preferences(section='test')

        autodiscover(force_reload=True)

        self.assertEqual(
            len(user_preferences_registry.preferences(section='test')), 4)

class TestSerializers(BaseTest, TestCase):

    def test_boolean_serialization(self):
        s = BooleanSerializer

        self.assertEqual(s.serialize(True), "1")
        self.assertEqual(s.serialize("True"), "1")
        self.assertEqual(s.serialize("Something"), "1")

        self.assertEqual(s.serialize(False), "0")
        self.assertEqual(s.serialize(""), "0")

    def test_boolean_deserialization(self):

        s = BooleanSerializer

        for v in s.true:
            self.assertEqual(s.deserialize(v), True)

        for v in s.false:
            self.assertEqual(s.deserialize(v), False)

        with self.assertRaises(s.exception):
            s.deserialize("I'm a true value")

    def test_int_serialization(self):

        s = IntSerializer

        self.assertEqual(s.serialize(1), "1")
        self.assertEqual(s.serialize(666), "666")
        self.assertEqual(s.serialize(-144), "-144")
        self.assertEqual(s.serialize(0), "0")
        self.assertEqual(s.serialize(123456), "123456")

        with self.assertRaises(s.exception):
            s.serialize("I'm an integer")

    def test_int_deserialization(self):

        s = IntSerializer

        self.assertEqual(s.deserialize("1"), 1)
        self.assertEqual(s.deserialize("125"), 125)
        self.assertEqual(s.deserialize("-144000"), -144000)
        self.assertEqual(s.deserialize("0"), 0)

        with self.assertRaises(s.exception):
            s.deserialize("Trust me, i'm an integer")

    def test_string_serialization(self):

        s = StringSerializer

        self.assertEqual(s.serialize("Bonjour"), "Bonjour")
        self.assertEqual(s.serialize("12"), "12")
        self.assertEqual(s.serialize(
            "I'm a long sentence, but I rock"), "I'm a long sentence, but I rock")

        # check for HTML escaping
        kwargs = {"escape_html": True, }
        self.assertEqual(
            s.serialize(
                "Please, I don't wanna disappear", **kwargs),
            defaultfilters.force_escape(
                "Please, I don't wanna disappear")
        )

        with self.assertRaises(s.exception):
            s.serialize(('I', 'Want', 'To', 'Be', 'A', 'String'))

    def test_string_deserialization(self):

        s = StringSerializer
        self.assertEqual(s.deserialize("Bonjour"), "Bonjour")
        self.assertEqual(s.deserialize("12"), "12")
        self.assertEqual(s.deserialize(
            "I'm a long sentence, but I rock"), "I'm a long sentence, but I rock")

        kwargs = {"escape_html": True, }
        self.assertEqual(
            s.deserialize(
                s.serialize("Please, I don't wanna disappear", **kwargs)),
            defaultfilters.force_escape(
                "Please, I don't wanna disappear")
        )

class TestViews(BaseTest, LiveServerTestCase):

    def setUp(self):
        self.henri = User(
            username="henri", password="test", email="henri@henri.com")
        self.henri.set_password('test')
        self.henri.save()

        self.admin = User(
            username="admin", email="admin@admin.com", is_superuser=True, is_staff=True)
        self.admin.set_password('test')
        self.admin.save()

    def test_can_build_global_preference_form(self):
        # We want to display a form with two global preferences
        # RegistrationAllowed and MaxUsers
        form = global_preference_form_builder(
            preferences=['user__registration_allowed', "user__max_users"])()

        self.assertEqual(len(form.fields), 2)
        self.assertEqual(
            form.fields['user__registration_allowed'].initial, False)

    def test_can_build_preference_form_from_sections(self):
        form = global_preference_form_builder(section='test')()

        self.assertEqual(len(form.fields), 3)

    def test_can_build_global_preference_form_from_sections(self):
        form = global_preference_form_builder(section='test')()

        self.assertEqual(len(form.fields), 3)

    def test_can_build_user_preference_form_from_sections(self):
        form = user_preference_form_builder(
            instance=self.admin, section='test')()

        self.assertEqual(len(form.fields), 4)

    def test_global_preference_view_requires_staff_member(self):
        url = reverse("dynamic_preferences.global")
        response = self.client.get(url, follow=True)

        self.assertRedirects(response, "/admin/login/?next=/global/")

        self.client.login(username='henri', password="test")
        response = self.client.get(url)
        self.assertRedirects(response, "/admin/login/?next=/global/")

        self.client.login(username='admin', password="test")
        response = self.client.get(url)

        self.assertEqual(self.admin.is_authenticated(), True)
        self.assertEqual(response.status_code, 200)

    def test_global_preference_view_display_form(self):

        url = reverse("dynamic_preferences.global")
        self.client.login(username='admin', password="test")
        response = self.client.get(url)
        self.assertEqual(len(response.context['form'].fields), 7)
        self.assertEqual(
            response.context['registry'], global_preferences_registry)

    def test_global_preference_filters_by_section(self):
        self.client.login(username='admin', password="test")
        url = reverse(
            "dynamic_preferences.global.section", kwargs={"section": 'user'})
        response = self.client.get(url)
        self.assertEqual(len(response.context['form'].fields), 3)

    def test_preference_are_updated_on_form_submission(self):
        self.client.login(username='admin', password="test")
        url = reverse(
            "dynamic_preferences.global.section", kwargs={"section": 'user'})
        response = self.client.post(url, {'user__max_users': 95, 'user__registration_allowed': True,
                                          "user__items_per_page": 12})
        self.assertEqual(GlobalPreferenceModel.objects.get(
            section="user", name="max_users").value, 95)
        self.assertEqual(GlobalPreferenceModel.objects.get(
            section="user", name="registration_allowed").value, True)
        self.assertEqual(GlobalPreferenceModel.objects.get(
            section="user", name="items_per_page").value, 12)

    def test_user_preference_form_is_bound_with_current_user(self):
        self.client.login(username='henri', password="test")
        self.assertEqual(UserPreferenceModel.objects.get_or_create(
            instance=self.henri, section="misc", name='favourite_colour')[0].value, 'Green')
        self.assertEqual(UserPreferenceModel.objects.get_or_create(
            instance=self.henri, section="misc", name='is_zombie')[0].value, True)

        url = reverse(
            "dynamic_preferences.user.section", kwargs={'section': 'misc'})
        response = self.client.post(
            url, {'misc__favourite_colour': 'Purple', 'misc__is_zombie': False})

        self.assertEqual(self.henri.preferences['misc__favourite_colour'], 'Purple')
        self.assertEqual(self.henri.preferences['misc__is_zombie'], False)

    def test_template_gets_global_preferences_via_template_processor(self):
        global_preferences = global_preferences_registry.manager()
        url = reverse("dynamic_preferences.test.templateview")
        response = self.client.get(url)
        self.assertEqual(
            response.context['global_preferences'], global_preferences.all())


text:
var assert, e, jy, pluginDir, request, root, toType;

pluginDir = __dirname + '/../';

toType = function(obj) {
  return {}.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
};

assert = require('chai').assert;

request = require('request');

try {
  jy = require('jellyjs');
} catch (_error) {
  e = _error;
  root = __dirname + '/../../../../';
  jy = require("" + root + "/index.js");
}

describe('#Plugin::compilejs', function() {
  it('Should compile js File entities', function(cb) {
    var jelly;

    jelly = new jy.Jelly();
    return jelly.boot({
      directory: "" + __dirname + "/demo",
      folderPlugins: [
        {
          name: 'compilejs',
          directory: pluginDir
        }
      ]
    }, function(err) {
      var content, file;

      if (err != null) {
        cb(err);
        cb = function() {};
        return;
      }
      file = jelly.getChildByIdRec('module1-file1.js');
      content = file.getCurrentContent();
      assert.equal(toType(content), 'object');
      assert.equal(content.extension, '__exec');
      assert.equal(toType(content.content), 'object');
      assert.equal(content.content.TEST, 1);
      return cb();
    });
  });
  it('Should raise an error if the file is invalid', function(cb) {
    var jelly;

    jelly = new jy.Jelly();
    return jelly.boot({
      directory: "" + __dirname + "/demoInvalidFile",
      folderPlugins: [
        {
          name: 'compilejs',
          directory: pluginDir
        }
      ]
    }, function(err) {
      if (err != null) {
        cb();
        cb = function() {};
        return;
      }
      return cb('No errors returned');
    });
  });
  it('Should raise an error if the plugin is not used on Files', function(cb) {
    var jelly;

    jelly = new jy.Jelly();
    return jelly.boot({
      directory: "" + __dirname + "/demoInvalidPluginUsage",
      folderPlugins: [
        {
          name: 'compilejs',
          directory: pluginDir
        }
      ]
    }, function(err) {
      if (err != null) {
        cb();
        cb = function() {};
        return;
      }
      return cb('No errors returned');
    });
  });
  return it('Should ignore non JS/JSON files', function(cb) {
    var jelly;

    jelly = new jy.Jelly();
    return jelly.boot({
      directory: "" + __dirname + "/demoCompileJSOnly",
      folderPlugins: [
        {
          name: 'compilejs',
          directory: pluginDir
        }
      ]
    }, function(err) {
      return cb(err);
    });
  });
});


text:
//Problem 12.* Randomize the Numbers 1…N

//Write a program that enters in integer n
//and prints the numbers 1, 2, …, n in random order.

using System;

class RandomizeOneToN
{
    static void Main(string[] args)
    {
        int n = int.Parse(Console.ReadLine());

        //create an array of random numbers
        int[] numbers = new int[n];
        Random random = new Random();

        for (int i = 0; i < numbers.Length; i++)
        {
            numbers[i] = random.Next(1, n + 1);
        }

        Console.WriteLine(string.Join(" ", numbers));
    }
}


text:
from rdkit import Chem

from mordred import Chi, ABCIndex

benzene = Chem.MolFromSmiles('c1ccccc1')

# create descriptor instance
abci = ABCIndex.ABCIndex()
chi_p2 = Chi.Chi(type='path', order=2)

# create product term using descriptor arithmetic
abci_x_chi_p2 = abci * chi_p2

# calculate descriptor value
result = abci_x_chi_p2(benzene)

print(abci_x_chi_p2, result)


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <meta name="description" content="Hi. I'm Javier Rizzo and this is my website." />
    <meta name="author" content="Javier Rizzo" />
    <meta name="keywords" content="javier, rizzo, mexicali, programmer, programming, mexico, cybernetics, electronics, writer" />
    <meta property="og:title" content="Javier Rizzo" />
    <meta property="og:type" content="article" />
    <meta property="og:url" content="http://javierrizzo.com/" />
    <meta property="og:image" content="http://javierrizzo.com/img/me.jpg" />
    <meta property="og:description" content="Hi. I'm Javier Rizzo and this is my website." />
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:site" content="@javierrizzoa" />
    <meta name="twitter:title" content="Javier Rizzo" />
    <meta name="twitter:description" content="Hi. I'm Javier Rizzo and this is my website." />
    <meta name="twitter:creator" content="@javierrizzoa" />
    <meta name="twitter:image" content="http://javierrizzo.com/img/me.jpg" />

    <meta name="theme-color" content="#fc7e0d">
    <meta name="msapplication-navbutton-color" content="#fc7e0d">
    <meta name="apple-mobile-web-app-status-bar-style" content="#fc7e0d">

    <title>Juegos de El Garage | Javier Rizzo</title>
    <link rel="stylesheet" type="text/css" href="../../css/style.css" />
    <link rel="stylesheet" type="text/css" href="../../node_modules/font-awesome/css/font-awesome.min.css" />

    <link rel="shortcut icon" href="../../icons/favicon.ico?v=edef8a8b10" type="image/x-icon">
    <link rel="apple-touch-icon" href="../../icons/apple-touch-icon.png?v=edef8a8b10" />
    <link rel="apple-touch-icon" sizes="57x57" href="../../icons/apple-touch-icon-57x57.png?v=edef8a8b10" />
    <link rel="apple-touch-icon" sizes="72x72" href="../../icons/apple-touch-icon-72x72.png?v=edef8a8b10" />
    <link rel="apple-touch-icon" sizes="76x76" href="../../icons/apple-touch-icon-76x76.png?v=edef8a8b10" />
    <link rel="apple-touch-icon" sizes="114x114" href="../../icons/apple-touch-icon-114x114.png?v=edef8a8b10" />
    <link rel="apple-touch-icon" sizes="120x120" href="../../icons/apple-touch-icon-120x120.png?v=edef8a8b10" />
    <link rel="apple-touch-icon" sizes="144x144" href="../../icons/apple-touch-icon-144x144.png?v=edef8a8b10" />
    <link rel="apple-touch-icon" sizes="152x152" href="../../icons/apple-touch-icon-152x152.png?v=edef8a8b10" />

Javier Rizzo / 2017 / Juegos de El Garage

Juegos de El Garage

Aquí pueden encontrar algunos juegos hechos por mis alumnos en El Garage Project Hub.

Apocalipsis - Isaac, Carlos, Jussef y Aldo

Marvel Wars - Juviem

Mosquito Spit - Guillermo

Mega Launcher - Charlie

El Barrio del Ocho - Ezequiel y José Manuel


text:
namespace base {

const SyncSocket::Handle SyncSocket::kInvalidHandle = -1;

SyncSocket::SyncSocket() : handle_(kInvalidHandle) {
}

SyncSocket::~SyncSocket() {
  Close();
}

// static
bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
  return false;
}

// static
SyncSocket::Handle SyncSocket::UnwrapHandle(
    const SyncSocket::TransitDescriptor& descriptor) {
  // TODO(xians): Still unclear how NaCl uses SyncSocket.
  // See http://crbug.com/409656
  NOTIMPLEMENTED();
  return SyncSocket::kInvalidHandle;
}

bool SyncSocket::PrepareTransitDescriptor(
    ProcessHandle peer_process_handle,
    SyncSocket::TransitDescriptor* descriptor) {
  // TODO(xians): Still unclear how NaCl uses SyncSocket.
  // See http://crbug.com/409656
  NOTIMPLEMENTED();
  return false;
}

bool SyncSocket::Close() {
  if (handle_ != kInvalidHandle) {
    if (close(handle_) < 0)
      DPLOG(ERROR) << "close";
    handle_ = kInvalidHandle;
  }
  return true;
}

size_t SyncSocket::Send(const void* buffer, size_t length) {
  const ssize_t bytes_written = write(handle_, buffer, length);
  return bytes_written > 0 ? bytes_written : 0;
}

size_t SyncSocket::Receive(void* buffer, size_t length) {
  const ssize_t bytes_read = read(handle_, buffer, length);
  return bytes_read > 0 ? bytes_read : 0;
}

size_t SyncSocket::ReceiveWithTimeout(void* buffer, size_t length, TimeDelta) {
  NOTIMPLEMENTED();
  return 0;
}

size_t SyncSocket::Peek() {
  NOTIMPLEMENTED();
  return 0;
}

CancelableSyncSocket::CancelableSyncSocket() {
}

CancelableSyncSocket::CancelableSyncSocket(Handle handle)
    : SyncSocket(handle) {
}

size_t CancelableSyncSocket::Send(const void* buffer, size_t length) {
  return SyncSocket::Send(buffer, length);
}

bool CancelableSyncSocket::Shutdown() {
  return SyncSocket::Close();
}

// static
bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
                                      CancelableSyncSocket* socket_b) {
  return SyncSocket::CreatePair(socket_a, socket_b);
}

}  // namespace base


text:
#include "rhodes/JNIRhodes.h"

#include "rhodes/jni/com_rhomobile_rhodes_datetime_DateTimePicker.h"

#include <common/RhodesApp.h>

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "DateTimePicker"

RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_datetime_DateTimePicker_callback
  (JNIEnv *env, jclass, jstring callback, jlong result, jbyteArray opaqueObj, jboolean cancelled)
{
    jbyte *opaqueStr = env->GetByteArrayElements(opaqueObj, JNI_FALSE);
    rho_rhodesapp_callDateTimeCallback(rho_cast<std::string>(callback).c_str(), result, (const char *)opaqueStr, cancelled);
    env->ReleaseByteArrayElements(opaqueObj, opaqueStr, 0);
}

RHO_GLOBAL void choose_datetime_with_range(char* callback, char* title, long initial_time, int format, char* data, long min_time, long max_time)
{
    JNIEnv *env = jnienv();
    jclass cls = getJNIClass(RHODES_JAVA_CLASS_DATE_TIME_PICKER);
    if (!cls) return;
    jmethodID mid = getJNIClassStaticMethod(env, cls, "choose", "(Ljava/lang/String;Ljava/lang/String;JI[BJJ)V");
    if (!mid) return;

    jsize data_size = strlen(data);
    jholder<jbyteArray> opaqueObj = jholder<jbyteArray>(env->NewByteArray(data_size));
    if (!opaqueObj) return;
    env->SetByteArrayRegion(opaqueObj.get(), 0, data_size, (const jbyte *)data);
    jhstring objCallback = rho_cast<jstring>(callback);
    jhstring objTitle = rho_cast<jstring>(title);
    env->CallStaticVoidMethod(cls, mid, objCallback.get(), objTitle.get(),
        (jlong)initial_time, format, opaqueObj.get(), (jlong)min_time, (jlong)max_time);
}

RHO_GLOBAL void choose_datetime(char* callback, char* title, long initial_time, int format, char* data)
{
    choose_datetime_with_range(callback, title, initial_time, format, data, 0, 0);
}

RHO_GLOBAL void set_change_value_callback_datetime(char* callback) {
}


text:
extern crate serde_derive;

use std::fs;
use std::fs::File;
use std::io::prelude::*;

extern crate byteorder;

use byteorder::{BigEndian, WriteBytesExt};

mod dictionary;

const DIRECTIONS: &[&str] = &["io-en", "en-io", "io-ru-io"];

fn main() {
    for &dir in DIRECTIONS.iter() {
        let data =
            dictionary::load_dictionary("service_data/dictionaries_by_letter/".to_owned() + dir);

        let target_path = "misc_data/stardict/".to_owned() + dir;
        fs::remove_dir_all(&target_path).unwrap();
        fs::create_dir_all(&target_path).unwrap();

        let mut dict_file_stream =
            File::create(target_path.to_owned() + "/" + dir + ".dict").unwrap();

        let mut idx_data = vec![];
        let mut offset = 0;
        for article in data.entries {
            let bytes = article.as_bytes();
            dict_file_stream.write_all(bytes).unwrap();
            idx_data.push((offset, bytes.len()));
            offset += bytes.len();
        }

        let mut idx_file_stream =
            File::create(target_path.to_owned() + "/" + dir + ".idx").unwrap();
        let mut all_words: Vec<String> = data.compact_index.keys().map(|x| x.clone()).collect();
        // Emulate g_ascii_strcasecmp
        all_words.sort_by_key(|x| {
            x.bytes()
                .map(|x| if x >= 128 { 0 } else { x })
                .collect::<Vec<u8>>()
        });
        let mut idx_size = 0;
        for word in &all_words {
            let article_ids = &data.compact_index[word];
            for article_id in article_ids {
                let word_bytes = word.as_bytes();
                idx_file_stream.write_all(word_bytes).unwrap();
                idx_file_stream.write_all(&vec![0u8]).unwrap();
                idx_file_stream
                    .write_i32::<BigEndian>(idx_data[*article_id].0 as i32)
                    .unwrap();
                idx_file_stream
                    .write_i32::<BigEndian>(idx_data[*article_id].1 as i32)
                    .unwrap();
                idx_size += word_bytes.len() + 9;
            }
        }
        let mut ifo_file_writer =
            File::create(target_path.to_owned() + "/" + dir + ".ifo").unwrap();
        ifo_file_writer
            .write_all(
                format!(
                    "StarDict's dict ifo file
version=3.0.0
[options]
bookname={}
wordcount={}
idxfilesize={}
sametypesequence=h
",
                    dir,
                    all_words.len(),
                    idx_size
                )
                .as_bytes(),
            )
            .unwrap();
    }
}


text:
package mesosphere.marathon.storage

import java.util
import java.util.Collections
import java.util.concurrent.TimeUnit

import akka.actor.{ ActorRefFactory, Scheduler }
import akka.stream.Materializer
import com.typesafe.config.{ Config, ConfigMemorySize }
import mesosphere.marathon.core.storage.store.PersistenceStore
import mesosphere.marathon.core.storage.store.impl.BasePersistenceStore
import mesosphere.marathon.core.storage.store.impl.cache.{ LazyCachingPersistenceStore, LoadTimeCachingPersistenceStore }
import mesosphere.marathon.core.storage.store.impl.memory.{ Identity, InMemoryPersistenceStore, RamId }
import mesosphere.marathon.core.storage.store.impl.zk.{ NoRetryPolicy, RichCuratorFramework, ZkId, ZkPersistenceStore, ZkSerialized }
import mesosphere.marathon.metrics.Metrics
import mesosphere.marathon.state.MarathonState
import mesosphere.marathon.storage.repository.legacy.store._
import mesosphere.marathon.util.{ RetryConfig, toRichConfig }
import org.apache.curator.framework.api.ACLProvider
import org.apache.curator.framework.imps.GzipCompressionProvider
import org.apache.curator.framework.{ AuthInfo, CuratorFrameworkFactory }
import org.apache.mesos.state.ZooKeeperState
import org.apache.zookeeper.ZooDefs
import org.apache.zookeeper.data.ACL

import scala.collection.JavaConverters._
import scala.collection.immutable.Seq
import scala.concurrent.ExecutionContext
import scala.concurrent.duration.{ Duration, _ }
import scala.reflect.ClassTag

sealed trait StorageConfig extends Product with Serializable
sealed trait LegacyStorageConfig extends StorageConfig {
  protected[storage] def store: PersistentStore
  val maxVersions: Int
  val enableCache: Boolean

  def entityStore[T <: MarathonState[_, T]](prefix: String, newState: () => T)(
    implicit
    metrics: Metrics, ct: ClassTag[T]): EntityStore[T] = {
    val marathonStore = new MarathonStore[T](store, metrics, newState, prefix)
    if (enableCache) new EntityStoreCache[T](marathonStore) else marathonStore
  }
}

// only for testing
private[storage] case class LegacyInMemConfig(maxVersions: Int) extends LegacyStorageConfig {
  override protected[storage] val store: PersistentStore = new InMemoryStore()
  override val enableCache: Boolean = false
}

case class TwitterZk(
    maxVersions: Int,
    enableCache: Boolean,
    sessionTimeout: Duration,
    zkHosts: String,
    zkPath: String,
    zkAcl: util.List[ACL],
    username: Option[String],
    password: Option[String],
    retries: Int,
    enableCompression: Boolean,
    compressionThreshold: ConfigMemorySize,
    maxConcurrent: Int,
    maxOutstanding: Int)(implicit metrics: Metrics, actorRefFactory: ActorRefFactory) extends LegacyStorageConfig {

  private val sessionTimeoutTw = {
    com.twitter.util.Duration(sessionTimeout.toMillis, TimeUnit.MILLISECONDS)
  }

  protected[storage] lazy val store: PersistentStore = {
    import com.twitter.util.JavaTimer
    import com.twitter.zk.{ AuthInfo, NativeConnector, ZkClient }

    val authInfo = (username, password) match {
      case (Some(user), Some(pass)) => Some(AuthInfo.digest(user, pass))
      case _ => None
    }

    val connector = NativeConnector(zkHosts, None, sessionTimeoutTw, new JavaTimer(isDaemon = true), authInfo)

    val client = ZkClient(connector)
      .withAcl(zkAcl.asScala)
      .withRetries(retries)
    val compressionConf = CompressionConf(enableCompression, compressionThreshold.toBytes)
    new ZKStore(client, client(zkPath), compressionConf, maxConcurrent = maxConcurrent, maxOutstanding = maxOutstanding)
  }
}

object TwitterZk {
  val StoreName = "legacy_zk"

  def apply(
    config: StorageConf)(implicit metrics: Metrics, actorRefFactory: ActorRefFactory): TwitterZk =
    TwitterZk(
      maxVersions = config.maxVersions(),
      enableCache = config.storeCache(),
      sessionTimeout = config.zkSessionTimeoutDuration,
      zkHosts = config.zkHosts,
      zkPath = config.zooKeeperStatePath,
      zkAcl = config.zkDefaultCreationACL,
      username = config.zkUsername,
      password = config.zkPassword,
      retries = 3,
      enableCompression = config.zooKeeperCompressionEnabled(),
      compressionThreshold = ConfigMemorySize.ofBytes(config.zooKeeperCompressionThreshold()),
      maxConcurrent = config.zkMaxConcurrency(),
      maxOutstanding = 1024)

  def apply(config: Config)(implicit metrics: Metrics, actorRefFactory: ActorRefFactory): TwitterZk = {
    val username = config.optionalString("username")
    val password = config.optionalString("password")
    val acls = (username, password) match {
      case (Some(_), Some(_)) => ZooDefs.Ids.CREATOR_ALL_ACL
      case _ => ZooDefs.Ids.OPEN_ACL_UNSAFE
    }
    TwitterZk(
      maxVersions = config.int("max-versions", StorageConfig.DefaultLegacyMaxVersions),
      enableCache = config.bool("enable-cache", true),
      sessionTimeout = config.duration("session-timeout", 10.seconds),
      zkHosts = config.stringList("hosts", Seq("localhost:2181")).mkString(","),
      zkPath = s"${config.string("path", "marathon")}/state",
      zkAcl = acls,
      username = username,
      password = password,
      retries = config.int("retries", 3),
      enableCompression = config.bool("enable-compression", true),
      compressionThreshold = config.memorySize("compression-threshold", ConfigMemorySize.ofBytes(64 * 1024)),
      maxConcurrent = config.int("max-concurrent", 32),
      maxOutstanding = config.int("max-outstanding", 1024)
    )
  }
}

case class MesosZk(
    maxVersions: Int,
    enableCache: Boolean,
    zkHosts: String,
    zkPath: String,
    timeout: Duration) extends LegacyStorageConfig {
  def store: PersistentStore = {
    val state = new ZooKeeperState(
      zkHosts,
      timeout.toMillis,
      TimeUnit.MILLISECONDS,
      zkPath
    )
    new MesosStateStore(state, timeout)
  }
}

object MesosZk {
  val StoreName = "mesos_zk"

  def apply(config: StorageConf): MesosZk =
    MesosZk(
      maxVersions = config.maxVersions(),
      enableCache = config.storeCache(),
      zkHosts = config.zkHosts,
      zkPath = config.zooKeeperStatePath,
      timeout = config.zkTimeoutDuration)

  def apply(config: Config): MesosZk =
    MesosZk(
      maxVersions = config.int("max-versions", StorageConfig.DefaultLegacyMaxVersions),
      enableCache = config.bool("enable-cache", true),
      zkHosts = config.stringList("hosts", Seq("localhost:2181")).mkString(","),
      zkPath = s"${config.string("path", "marathon")}/state",
      timeout = config.duration("timeout", 10.seconds)
    )
}

sealed trait CacheType
case object NoCaching extends CacheType
case object EagerCaching extends CacheType
case object LazyCaching extends CacheType

object CacheType {
  def apply(str: String): CacheType = str.toLowerCase match {
    case str: String if str.startsWith("eager") => EagerCaching
    case str: String if str.startsWith("lazy") => LazyCaching
    case _ => NoCaching
  }
}

sealed trait PersistenceStorageConfig[K, C, S] extends StorageConfig {
  val maxVersions: Int
  val cacheType: CacheType
  protected def leafStore(implicit metrics: Metrics, mat: Materializer, ctx: ExecutionContext,
    scheduler: Scheduler, actorRefFactory: ActorRefFactory): BasePersistenceStore[K, C, S]

  def store(implicit metrics: Metrics, mat: Materializer,
    ctx: ExecutionContext, scheduler: Scheduler, actorRefFactory: ActorRefFactory): PersistenceStore[K, C, S] = {
    cacheType match {
      case NoCaching => leafStore
      case LazyCaching => new LazyCachingPersistenceStore[K, C, S](leafStore)
      case EagerCaching => new LoadTimeCachingPersistenceStore[K, C, S](leafStore)
    }
  }
}

case class CuratorZk(
    cacheType: CacheType,
    sessionTimeout: Option[Duration],
    connectionTimeout: Option[Duration],
    timeout: Duration,
    zkHosts: String,
    zkPath: String,
    zkAcls: util.List[ACL],
    username: Option[String],
    password: Option[String],
    enableCompression: Boolean,
    retryConfig: RetryConfig,
    maxConcurrent: Int,
    maxOutstanding: Int,
    maxVersions: Int) extends PersistenceStorageConfig[ZkId, String, ZkSerialized] {

  lazy val client: RichCuratorFramework = {
    val builder = CuratorFrameworkFactory.builder()
    builder.connectString(zkHosts)
    sessionTimeout.foreach(t => builder.sessionTimeoutMs(t.toMillis.toInt))
    connectionTimeout.foreach(t => builder.connectionTimeoutMs(t.toMillis.toInt))
    if (enableCompression) builder.compressionProvider(new GzipCompressionProvider)
    (username, password) match {
      case (Some(user), Some(pass)) =>
        builder.authorization(Collections.singletonList(new AuthInfo("digest", s"$user:$pass".getBytes("UTF-8"))))
      case _ =>
    }
    builder.aclProvider(new ACLProvider {
      override def getDefaultAcl: util.List[ACL] = zkAcls

      override def getAclForPath(path: String): util.List[ACL] = zkAcls
    })
    builder.retryPolicy(NoRetryPolicy) // We use our own Retry.
    builder.namespace(zkPath.stripPrefix("/"))
    val client = builder.build()
    client.start()
    client.blockUntilConnected()
    RichCuratorFramework(client)
  }

  protected def leafStore(implicit metrics: Metrics, mat: Materializer, ctx: ExecutionContext,
    scheduler: Scheduler, actorRefFactory: ActorRefFactory): BasePersistenceStore[ZkId, String, ZkSerialized] =
    new ZkPersistenceStore(client, timeout, maxConcurrent, maxOutstanding)

}

object CuratorZk {
  val StoreName = "zk"
  def apply(conf: StorageConf): CuratorZk =
    CuratorZk(
      cacheType = if (conf.storeCache()) LazyCaching else NoCaching,
      sessionTimeout = Some(conf.zkSessionTimeoutDuration),
      connectionTimeout = None,
      timeout = conf.zkTimeoutDuration,
      zkHosts = conf.zkHosts,
      zkPath = conf.zooKeeperStatePath,
      zkAcls = conf.zkDefaultCreationACL,
      username = conf.zkUsername,
      password = conf.zkPassword,
      enableCompression = conf.zooKeeperCompressionEnabled(),
      retryConfig = RetryConfig(),
      maxConcurrent = conf.zkMaxConcurrency(),
      maxOutstanding = 1024,
      maxVersions = conf.maxVersions()
    )

  def apply(config: Config): CuratorZk = {
    val username = config.optionalString("username")
    val password = config.optionalString("password")
    val acls = (username, password) match {
      case (Some(_), Some(_)) => ZooDefs.Ids.CREATOR_ALL_ACL
      case _ => ZooDefs.Ids.OPEN_ACL_UNSAFE
    }
    CuratorZk(
      cacheType = CacheType(config.string("cache-type", "lazy")),
      sessionTimeout = config.optionalDuration("session-timeout"),
      connectionTimeout = config.optionalDuration("connect-timeout"),
      timeout = config.duration("timeout", 10.seconds),
      zkHosts = config.stringList("hosts", Seq("localhost:2181")).mkString(","),
      zkPath = s"${config.string("path", "marathon")}/state",
      zkAcls = acls,
      username = username,
      password = password,
      enableCompression = config.bool("enable-compression", true),
      retryConfig = RetryConfig(config),
      maxConcurrent = config.int("max-concurrent-requests", 32),
      maxOutstanding = config.int("max-concurrent-outstanding", 1024),
      maxVersions = config.int("max-versions", StorageConfig.DefaultMaxVersions)
    )
  }
}

case class InMem(maxVersions: Int) extends PersistenceStorageConfig[RamId, String, Identity] {
  override val cacheType: CacheType = NoCaching

  protected def leafStore(implicit metrics: Metrics, mat: Materializer, ctx: ExecutionContext,
    scheduler: Scheduler, actorRefFactory: ActorRefFactory): BasePersistenceStore[RamId, String, Identity] =
    new InMemoryPersistenceStore()
}

object InMem {
  val StoreName = "mem"

  def apply(conf: StorageConf): InMem =
    InMem(conf.maxVersions())

  def apply(conf: Config): InMem =
    InMem(conf.int("max-versions", StorageConfig.DefaultMaxVersions))
}

object StorageConfig {
  val DefaultLegacyMaxVersions = 25
  val DefaultMaxVersions = 5000
  def apply(conf: StorageConf)(implicit metrics: Metrics, actorRefFactory: ActorRefFactory): StorageConfig = {
    conf.internalStoreBackend() match {
      case TwitterZk.StoreName => TwitterZk(conf)
      case MesosZk.StoreName => MesosZk(conf)
      case InMem.StoreName => InMem(conf)
      case CuratorZk.StoreName => CuratorZk(conf)
    }
  }

  def apply(conf: Config)(implicit metrics: Metrics, actorRefFactory: ActorRefFactory): StorageConfig = {
    conf.string("storage-type", "zk") match {
      case TwitterZk.StoreName => TwitterZk(conf)
      case MesosZk.StoreName => MesosZk(conf)
      case InMem.StoreName => InMem(conf)
      case CuratorZk.StoreName => CuratorZk(conf)
    }
  }
}


text:
/*

    Name:       Base16 Default Light
    Author:     Chris Kempson (http://chriskempson.com)

    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-chrome-devtools)
    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)

*/

.cm-s-base16-light.CodeMirror {background: #f5f5f5; color: #202020;}
.cm-s-base16-light div.CodeMirror-selected {background: #e0e0e0 !important;}
.cm-s-base16-light .CodeMirror-gutters {background: #f5f5f5; border-right: 0px;}
.cm-s-base16-light .CodeMirror-linenumber {color: #b0b0b0;}
.cm-s-base16-light .CodeMirror-cursor {border-left: 1px solid #505050 !important;}

.cm-s-base16-light span.cm-comment {color: #8f5536;}
.cm-s-base16-light span.cm-atom {color: #aa759f;}
.cm-s-base16-light span.cm-number {color: #aa759f;}

.cm-s-base16-light span.cm-property, .cm-s-base16-light span.cm-attribute {color: #90a959;}
.cm-s-base16-light span.cm-keyword {color: #ac4142;}
.cm-s-base16-light span.cm-string {color: #f4bf75;}
.cm-s-base16-light span.cm-header {color: #ac4142;}

.cm-s-base16-light span.cm-variable {color: #90a959;}
.cm-s-base16-light span.cm-variable-2 {color: #6a9fb5;}
.cm-s-base16-light span.cm-def {color: #d28445;}
.cm-s-base16-light span.cm-bracket {color: #202020;}
.cm-s-base16-light span.cm-tag {color: #ac4142;}
.cm-s-base16-light span.cm-link {color: #aa759f;}
.cm-s-base16-light span.cm-error {background: #ac4142; color: #505050;}

.cm-s-base16-light .CodeMirror-activeline-background {background: #DDDCDC !important;}
.cm-s-base16-light .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;}
.cm-s-base16-light { line-height: 150%; }


text:
from __future__ import print_function
import xml.sax.saxutils

def clean(txt):
    txt=txt.replace(' ','_')
    txt=txt.replace('Ä','Ae')
    txt=txt.replace('Ö','Oe')
    txt=txt.replace('Ü','Ue')
    txt=txt.replace('ä','ae')
    txt=txt.replace('ö','oe')
    txt=txt.replace('ü','ue')
    txt=txt.replace('&','_und_')
    txt=txt.replace("'","_")
    txt=txt.replace("__","_")
    return txt

def escape(s):
    return xml.sax.saxutils.escape(s).strip()

def escape_path(p):
    return p.replace(' ','\ ').replace('&','\&').replace("'","\'")

def list2options(tag,list):
    #print ("DEBUG list2options",tag,list)
    option=''
    for element in list:
        option+=tag+' '
        option+=element+' '
    return option
def ctx2options(ctx,image):
    #print ("DEBUG ctx2options",ctx.images[image])
    options=''
    ctx_image=ctx.images[image]

    if ctx_image:
        if 'links' in ctx_image:
            options+=list2options('--link',ctx_image.links)
        if 'ports' in ctx_image:
            options+=list2options('-p',ctx_image.ports)
        if 'env' in ctx_image:
            options+=list2options('-e',ctx_image.env)
        if 'volumes' in ctx_image:
            for volume in ctx_image.volumes:
                #print ('DEBUG volume',ctx_image.volumes[volume])
                options+=' -v '+ctx.data_dir+'/'+ctx.network+'/'+image+'/'+volume+':'+ctx_image.volumes[volume]
        if 'hostname' in ctx_image:
            hostname=ctx_image.hostname
        else:
            hostname=image
        options+=" --network={network} --hostname {hostname} --network-alias={hostname}".format(network=ctx.network,hostname=hostname)
    return options

#def name2options(ctx,image):
#    network = ctx.network
#    #print ("DEBUG name2options",ctx.images[image])
#    try:
#        version = ctx.images[image].version
#    except AttributeError:
#        version = ctx.version
    #try:
#    options = ctx2options(ctx,image)
    #except AttributeError:
    #    options=''
#    return (network,version,options)

def ctx2version(ctx,image):

    if ctx.images[image] and ('version' in ctx.images[image]):
        version = ctx.images[image].version
    else:
        version = ctx.version

    return version


text:
  Sutrieu est
       un village
       géographiquement positionné dans le département de l'Ain en Rhône-Alpes. On dénombrait 217 habitants en 2008.

Le nombre d'habitations, à Sutrieu, se décomposait en 2011 en douze appartements et 164 maisons soit
 un marché plutôt équilibré.

À coté de Sutrieu sont positionnées géographiquement les villes de
Ruffieu à 4 km, 172 habitants,
Champagne-en-Valromey à 5 km, 691 habitants,
Brénaz à 5 km, 93 habitants,
Lochieu à 5 km, 86 habitants,
Hauteville-Lompnes à 5 km, 4 125 habitants,
Lompnieu située à 1 km, 96 habitants,
 entre autres. De plus, Sutrieu est située à seulement 23 km de Rumilly.

Si vous envisagez de venir habiter à Sutrieu, vous pourrez aisément trouver une maison à acheter.


text:
//// [declFileObjectLiteralWithOnlyGetter.ts]
function /*1*/makePoint(x: number) {
    return {
        get x() { return x; },
    };
};
var /*4*/point = makePoint(2);
var /*2*/x = point./*3*/x;

//// [declFileObjectLiteralWithOnlyGetter.js]
function makePoint(x) {
    return {
        get x() { return x; },
    };
}
;
var /*4*/ point = makePoint(2);
var /*2*/ x = point. /*3*/x;

//// [declFileObjectLiteralWithOnlyGetter.d.ts]
declare function makePoint(x: number): {
    readonly x: number;
};
declare var /*4*/ point: {
    readonly x: number;
};
declare var /*2*/ x: number;


text:
package kr.debop4j.data.hibernate.forTesting;

import com.google.common.base.Objects;
import kr.debop4j.core.tools.HashTool;
import kr.debop4j.data.model.LongAnnotatedEntityBase;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;

import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Version;

/**
 * kr.debop4j.data.hibernate.forTesting.LongEntityForTesting
 *
 * @author 배성혁 ( sunghyouk.bae@gmail.com )
 * @since 13. 2. 21.
 */
@Entity
@Table(name = "LongEntity_ForTesting")
@DynamicInsert
@DynamicUpdate
@Getter
@Setter
public class LongEntityForTesting extends LongAnnotatedEntityBase {

    public String code;
    public String name;
    public Integer age;

    @Version
    public int version;

    @Override
    public int hashCode() {
        if (isPersisted())
            return super.hashCode();

        return HashTool.compute(code, name);
    }

    @Override
    protected Objects.ToStringHelper buildStringHelper() {
        return super.buildStringHelper()
                .add("code", code)
                .add("name", name)
                .add("age", age);
    }
}


text:
from __future__ import unicode_literals

import shutil
import tempfile
import unittest

from mopidy.local import translator
from mopidy.models import Track
from mopidy_local_sqlite import library

class LocalLibraryProviderTest(unittest.TestCase):

    config = {
        'local-sqlite': {
            'directories': [],
            'encodings': ['utf-8', 'latin-1'],
            'timeout': 1.0,
            'use_album_mbid_uri': False,
            'use_artist_mbid_uri': False,
            'extract_images': False
        }
    }

    def setUp(self):
        self.tempdir = tempfile.mkdtemp()
        self.library = library.SQLiteLibrary(dict(self.config, local={
            'media_dir': self.tempdir,
            'data_dir': self.tempdir
        }))
        self.library.load()

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

    def test_add_noname_ascii(self):
        name = b'Test.mp3'
        uri = translator.path_to_local_track_uri(name)
        self.library.begin()
        self.library.add(Track(uri=uri))
        self.library.close()
        self.assertEqual(self.library.lookup(uri).name, name)

    def test_add_noname_utf8(self):
        name = u'Mi\xf0vikudags.mp3'
        uri = translator.path_to_local_track_uri(name)
        self.library.begin()
        self.library.add(Track(uri=uri))
        self.library.close()
        self.assertEqual(self.library.lookup(uri).name, name)

    def test_clear(self):
        self.library.begin()
        self.library.add(Track(uri='local:track:track.mp3'))
        self.library.close()
        self.library.clear()
        self.assertEqual(self.library.load(), 0)


text:
@interface UISplitViewController (MemoryLeak)

@end

#endif


text:
module DAGMan

	class GridWay
		attr_accessor :job_id, :template, :state, :info

		# Wait for jobs specified in the array
		def self.wait(job_ids)
			ids=job_ids.collect{|id| id.to_s.strip }.join(' ')
			`gwwait -k -a #{ids}`
		end

		def initialize(template)
			@template=template
			@state=nil
		end

		# Submit the job to gridway and keep the job_id. (It is also
		# returned)
		def submit
			submit_out=`gwsubmit -v #{@template}`
			exit_code=$?
			if !submit_out or exit_code!=0
				return false
			end

			@job_id=submit_out.split(':')[1].strip
		end

		# Actualizes information for the job. Also sets state value
		def get_info
			ps_out=`gwps -f #{@job_id}`
			exit_code=$?
			if !ps_out or exit_code!=0
				return false
			end

			@info=Hash.new
			ps_out.each{|line|
				(name, val)=line.split('=')
				name.strip! if name
				val.strip! if val
				@info[name]=val if name
			}
			@state=@info['JOB_STATE']
		end

		# Kills the job
		def kill
			`gwkill #{@job_id}`
		end

		# Returns true if the job is done
		def done?
			if @state
				@state=='done'
			else
				false
			end
		end

	end # class

end # module


text:
package com.mossle.car.web;

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

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mossle.api.tenant.TenantHolder;
import com.mossle.api.user.UserConnector;

import com.mossle.car.persistence.domain.CarInfo;
import com.mossle.car.persistence.manager.CarInfoManager;

import com.mossle.core.export.Exportor;
import com.mossle.core.export.TableModel;
import com.mossle.core.hibernate.PropertyFilter;
import com.mossle.core.mapper.BeanMapper;
import com.mossle.core.page.Page;
import com.mossle.core.spring.MessageHelper;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("car")
public class CarInfoController {
    private CarInfoManager carInfoManager;
    private Exportor exportor;
    private BeanMapper beanMapper = new BeanMapper();
    private UserConnector userConnector;
    private MessageHelper messageHelper;
    private TenantHolder tenantHolder;

    @RequestMapping("car-info-list")
    public String list(@ModelAttribute Page page,
            @RequestParam Map<String, Object> parameterMap, Model model) {
        String tenantId = tenantHolder.getTenantId();
        List<PropertyFilter> propertyFilters = PropertyFilter
                .buildFromMap(parameterMap);
        propertyFilters.add(new PropertyFilter("EQS_tenantId", tenantId));
        page = carInfoManager.pagedQuery(page, propertyFilters);

        model.addAttribute("page", page);

        return "car/car-info-list";
    }

    @RequestMapping("car-info-input")
    public String input(@RequestParam(value = "id", required = false) Long id,
            Model model) {
        if (id != null) {
            CarInfo carInfo = carInfoManager.get(id);
            model.addAttribute("model", carInfo);
        }

        return "car/car-info-input";
    }

    @RequestMapping("car-info-save")
    public String save(@ModelAttribute CarInfo carInfo,
            @RequestParam Map<String, Object> parameterMap,
            RedirectAttributes redirectAttributes) {
        String tenantId = tenantHolder.getTenantId();
        CarInfo dest = null;

        Long id = carInfo.getId();

        if (id != null) {
            dest = carInfoManager.get(id);
            beanMapper.copy(carInfo, dest);
        } else {
            dest = carInfo;
            dest.setTenantId(tenantId);
        }

        carInfoManager.save(dest);

        messageHelper.addFlashMessage(redirectAttributes, "core.success.save",
                "保存成功");

        return "redirect:/car/car-info-list.do";
    }

    @RequestMapping("car-info-remove")
    public String remove(@RequestParam("selectedItem") List<Long> selectedItem,
            RedirectAttributes redirectAttributes) {
        List<CarInfo> carInfos = carInfoManager.findByIds(selectedItem);

        carInfoManager.removeAll(carInfos);

        messageHelper.addFlashMessage(redirectAttributes,
                "core.success.delete", "删除成功");

        return "redirect:/car/car-info-list.do";
    }

    @RequestMapping("car-info-export")
    public void export(@ModelAttribute Page page,
            @RequestParam Map<String, Object> parameterMap,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String tenantId = tenantHolder.getTenantId();
        List<PropertyFilter> propertyFilters = PropertyFilter
                .buildFromMap(parameterMap);
        propertyFilters.add(new PropertyFilter("EQS_tenantId", tenantId));
        page = carInfoManager.pagedQuery(page, propertyFilters);

        List<CarInfo> carInfos = (List<CarInfo>) page.getResult();

        TableModel tableModel = new TableModel();
        tableModel.setName("car info");
        tableModel.addHeaders("id", "name");
        tableModel.setData(carInfos);
        exportor.export(request, response, tableModel);
    }

    // ~ ======================================================================
    @Resource
    public void setCarInfoManager(CarInfoManager carInfoManager) {
        this.carInfoManager = carInfoManager;
    }

    @Resource
    public void setExportor(Exportor exportor) {
        this.exportor = exportor;
    }

    @Resource
    public void setUserConnector(UserConnector userConnector) {
        this.userConnector = userConnector;
    }

    @Resource
    public void setMessageHelper(MessageHelper messageHelper) {
        this.messageHelper = messageHelper;
    }

    @Resource
    public void setTenantHolder(TenantHolder tenantHolder) {
        this.tenantHolder = tenantHolder;
    }
}


text:
package org.thesemproject.opensem.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JWindow;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;

/**
 * Implementa un suggeritore alla digitazione. E' utilizzato per suggerire nome
 * tabella o termine di dizionario una volta digitato un # che nella notazione
 * di SEM identifica un oggetto complesso
 */
public class AutoSuggestor {

    private final JTextComponent textComp;
    private final Window container;
    private JPanel suggestionsPanel;
    private JWindow autoSuggestionPopUpWindow;
    private String typedWord;
    private final List<String> dictionary = new ArrayList<>();
    private int currentIndexOfSpace, tW, tH;
    private DocumentListener documentListener = new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent de) {
            checkForAndShowSuggestions();
        }

        @Override
        public void removeUpdate(DocumentEvent de) {
            checkForAndShowSuggestions();
        }

        @Override
        public void changedUpdate(DocumentEvent de) {
            checkForAndShowSuggestions();
        }
    };
    private final Color suggestionsTextColor;
    private final Color suggestionFocusedColor;

    /**
     * Istanzia il suggeritore su un componente testo
     *
     * @param textComp finestra di testo su cui istanziare il suggeritore
     * @param mainWindow finestra principale
     * @param words lista di parole
     * @param popUpBackground colore dello sfondo
     * @param textColor colore del testo
     * @param suggestionFocusedColor colore del suggeritore
     * @param opacity indice di opacità
     */
    public AutoSuggestor(JTextComponent textComp, Window mainWindow, List<String> words, Color popUpBackground, Color textColor, Color suggestionFocusedColor, float opacity) {
        this.textComp = textComp;
        this.suggestionsTextColor = textColor;
        this.container = mainWindow;
        this.suggestionFocusedColor = suggestionFocusedColor;
        this.textComp.getDocument().addDocumentListener(documentListener);

        setDictionary(words);

        typedWord = "";
        currentIndexOfSpace = 0;
        tW = 0;
        tH = 0;

        autoSuggestionPopUpWindow = new JWindow(mainWindow);
        autoSuggestionPopUpWindow.setOpacity(opacity);

        suggestionsPanel = new JPanel();
        suggestionsPanel.setLayout(new GridLayout(0, 1));
        suggestionsPanel.setBackground(popUpBackground);
        suggestionsPanel.setBorder(new LineBorder(Color.black));

        addKeyBindingToRequestFocusInPopUpWindow();
    }

    private int lastFocusableIndex = 0;

    private void addKeyBindingToRequestFocusInPopUpWindow() {
        textComp.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "Down released");
        textComp.getActionMap().put("Down released", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {//focuses the first label on popwindow
                for (int i = 0; i < suggestionsPanel.getComponentCount(); i++) {
                    if (suggestionsPanel.getComponent(i) instanceof SuggestionLabel) {
                        ((SuggestionLabel) suggestionsPanel.getComponent(i)).setFocused(true);
                        autoSuggestionPopUpWindow.toFront();
                        autoSuggestionPopUpWindow.requestFocusInWindow();
                        suggestionsPanel.requestFocusInWindow();
                        suggestionsPanel.getComponent(i).requestFocusInWindow();
                        break;
                    }
                }
            }
        });

        suggestionsPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "Down released");
        suggestionsPanel.getActionMap().put("Down released", new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent ae) {//allows scrolling of labels in pop window (I know very hacky for now :))

                ArrayList<SuggestionLabel> sls = getAddedSuggestionLabels();
                int max = sls.size();

                if (max > 1) {//more than 1 suggestion
                    for (int i = 0; i < max; i++) {
                        SuggestionLabel sl = sls.get(i);
                        if (sl.isFocused()) {
                            if (lastFocusableIndex == max - 1) {
                                lastFocusableIndex = 0;
                                sl.setFocused(false);
                                autoSuggestionPopUpWindow.setVisible(false);
                                setFocusToTextField();
                                checkForAndShowSuggestions();//fire method as if document listener change occured and fired it

                            } else {
                                sl.setFocused(false);
                                lastFocusableIndex = i;
                            }
                        } else if (lastFocusableIndex <= i) {
                            if (i < max) {
                                sl.setFocused(true);
                                autoSuggestionPopUpWindow.toFront();
                                autoSuggestionPopUpWindow.requestFocusInWindow();
                                suggestionsPanel.requestFocusInWindow();
                                suggestionsPanel.getComponent(i).requestFocusInWindow();
                                lastFocusableIndex = i;
                                break;
                            }
                        }
                    }
                } else {//only a single suggestion was given
                    autoSuggestionPopUpWindow.setVisible(false);
                    setFocusToTextField();
                    checkForAndShowSuggestions();//fire method as if document listener change occured and fired it
                }
            }
        });
        suggestionsPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true), "Up released");
        suggestionsPanel.getActionMap().put("Up released", new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent ae) {//allows scrolling of labels in pop window (I know very hacky for now :))

                ArrayList<SuggestionLabel> sls = getAddedSuggestionLabels();
                int max = sls.size();

                if (max > 1) {//more than 1 suggestion
                    for (int i = max - 1; i >= 0; i--) {
                        SuggestionLabel sl = sls.get(i);
                        if (sl.isFocused()) {
                            if (lastFocusableIndex == 0) {
                                lastFocusableIndex = max - 1;
                                sl.setFocused(false);
                                autoSuggestionPopUpWindow.setVisible(false);
                                setFocusToTextField();
                                checkForAndShowSuggestions();//fire method as if document listener change occured and fired it

                            } else {
                                sl.setFocused(false);
                                lastFocusableIndex = i;
                            }
                        } else if (lastFocusableIndex >= i) {
                            if (i >= 0) {
                                sl.setFocused(true);
                                autoSuggestionPopUpWindow.toFront();
                                autoSuggestionPopUpWindow.requestFocusInWindow();
                                suggestionsPanel.requestFocusInWindow();
                                suggestionsPanel.getComponent(i).requestFocusInWindow();
                                lastFocusableIndex = i;
                                break;
                            }
                        }
                    }
                } else {//only a single suggestion was given
                    autoSuggestionPopUpWindow.setVisible(false);
                    setFocusToTextField();
                    checkForAndShowSuggestions();//fire method as if document listener change occured and fired it
                }
            }
        });
    }

    private void setFocusToTextField() {
        container.toFront();
        container.requestFocusInWindow();
        textComp.requestFocusInWindow();
    }

    /**
     * Ritorna la lista di label suggerite
     *
     * @return lista
     */
    public ArrayList<SuggestionLabel> getAddedSuggestionLabels() {
        ArrayList<SuggestionLabel> sls = new ArrayList<>();
        for (int i = 0; i < suggestionsPanel.getComponentCount(); i++) {
            if (suggestionsPanel.getComponent(i) instanceof SuggestionLabel) {
                SuggestionLabel sl = (SuggestionLabel) suggestionsPanel.getComponent(i);
                sls.add(sl);
            }
        }
        return sls;
    }

    private void checkForAndShowSuggestions() {
        typedWord = getCurrentlyTypedWord();

        suggestionsPanel.removeAll();//remove previos words/jlabels that were added

        //used to calcualte size of JWindow as new Jlabels are added
        tW = 0;
        tH = 0;

        boolean added = wordTyped(typedWord);

        if (!added) {
            if (autoSuggestionPopUpWindow.isVisible()) {
                autoSuggestionPopUpWindow.setVisible(false);
            }
        } else {
            showPopUpWindow();
            setFocusToTextField();
        }
    }

    /**
     * Aggiunge una parola al suggeritore
     *
     * @param word parola de aggiungere
     */
    protected void addWordToSuggestions(String word) {
        SuggestionLabel suggestionLabel = new SuggestionLabel(word, suggestionFocusedColor, suggestionsTextColor, this);

        calculatePopUpWindowSize(suggestionLabel);

        suggestionsPanel.add(suggestionLabel);
    }

    /**
     * Ritorna la nuova parola dopo l'ultimo spazio bianco oppure se si tratta
     * della prima parola se non ci sono spazi
     *
     * @return parola
     */
    public String getCurrentlyTypedWord() {//
        String text = textComp.getText();
        String wordBeingTyped = "";
        text = text.replaceAll("(\\r|\\n)", " ");
        if (text.contains(" ")) {
            int tmp = text.lastIndexOf(" ");
            if (tmp >= currentIndexOfSpace) {
                currentIndexOfSpace = tmp;
                wordBeingTyped = text.substring(text.lastIndexOf(" "));
            }
        } else {
            wordBeingTyped = text;
        }
        return wordBeingTyped.trim();
    }

    private void calculatePopUpWindowSize(JLabel label) {
        //so we can size the JWindow correctly
        if (tW < label.getPreferredSize().width) {
            tW = label.getPreferredSize().width;
        }
        tH += label.getPreferredSize().height;
    }

    private void showPopUpWindow() {
        autoSuggestionPopUpWindow.getContentPane().add(suggestionsPanel);
        autoSuggestionPopUpWindow.setMinimumSize(new Dimension(200, 30));
        autoSuggestionPopUpWindow.setSize(Math.min(200, tW), tH);
        autoSuggestionPopUpWindow.setVisible(true);

        int windowX = 0;
        int windowY = 0;

        if (textComp instanceof JTextField) {//calculate x and y for JWindow at bottom of JTextField
            windowX = container.getX() + textComp.getX() + 5;
            if (suggestionsPanel.getHeight() > autoSuggestionPopUpWindow.getMinimumSize().height) {
                windowY = container.getY() + textComp.getY() + textComp.getHeight() + autoSuggestionPopUpWindow.getMinimumSize().height;
            } else {
                windowY = container.getY() + textComp.getY() + textComp.getHeight() + autoSuggestionPopUpWindow.getHeight();
            }
        } else {//calculate x and y for JWindow on any JTextComponent using the carets position

            Point pt = new Point(textComp.getLocation());
            SwingUtilities.convertPointToScreen(pt, textComp);
            Rectangle rect = null;
            try {
                rect = textComp.getUI().modelToView(textComp, textComp.getCaret().getDot());//get carets position
            } catch (BadLocationException ex) {
                ex.printStackTrace();
            }

            windowX = pt.x + (int) (rect.getX());
            windowY = textComp.getBaseline(0, 0) + pt.y;

        }

        //show the pop up
        autoSuggestionPopUpWindow.setLocation(windowX, windowY);
        autoSuggestionPopUpWindow.setMinimumSize(new Dimension(200, 30));
        autoSuggestionPopUpWindow.setMaximumSize(new Dimension(200, 30));
        autoSuggestionPopUpWindow.setPreferredSize(new Dimension(200, 30));
        autoSuggestionPopUpWindow.revalidate();
        autoSuggestionPopUpWindow.repaint();

    }

    /**
     * Imposta il dizionario delle parole da suggerire
     * @param words lista delle parole da suggerire
     */
    public void setDictionary(List<String> words) {
        dictionary.clear();
        if (words == null) {
            return;//so we can call constructor with null value for dictionary without exception thrown
        }
        for (String word : words) {
            dictionary.add(word);
        }
    }

    /**
     * Ritorna la finestra del suggeritore
     * @return finestra del suggeritore
     */
    public JWindow getAutoSuggestionPopUpWindow() {
        return autoSuggestionPopUpWindow;
    }

    /**
     * Ritorna il windows container
     * @return container
     */
    public Window getContainer() {
        return container;
    }

    /**
     * Ritorna il text field
     * @return Text component
     */
    public JTextComponent getTextField() {
        return textComp;
    }

    /**
     * Aggiunge una parola al dizionario
     * @param word parola da aggiungere
     */
    public void addToDictionary(String word) {
        dictionary.add(word);
    }

    boolean wordTyped(String tw) {
        if (tw.isEmpty()) {
            return false;
        }
        String typedWord = tw;
        int posDash = typedWord.indexOf("#");
        if (posDash != 0 && posDash != -1) {
            typedWord = typedWord.substring(posDash);
        }
        boolean suggestionAdded = false;
        int count = 0;
        for (String word : dictionary) {//get words in the dictionary which we added
            boolean fullymatches = true;
            for (int i = 0; i < typedWord.length(); i++) {//each string in the word
                if (!typedWord.toLowerCase().startsWith(String.valueOf(word.toLowerCase().charAt(i)), i)) {//check for match
                    fullymatches = false;
                    break;
                }
            }
            if (fullymatches) {
                addWordToSuggestions(word);
                suggestionAdded = true;
                count++;
            }
            if (count >= 5) {
                break;
            }
        }
        return suggestionAdded;
    }
}

class SuggestionLabel extends JLabel {

    private boolean focused = false;
    private final JWindow autoSuggestionsPopUpWindow;
    private final JTextComponent textComponent;
    private final AutoSuggestor autoSuggestor;
    private Color suggestionsTextColor, suggestionBorderColor;

    public SuggestionLabel(String string, final Color borderColor, Color suggestionsTextColor, AutoSuggestor autoSuggestor) {
        super(string);

        this.suggestionsTextColor = suggestionsTextColor;
        this.autoSuggestor = autoSuggestor;
        this.textComponent = autoSuggestor.getTextField();
        this.suggestionBorderColor = borderColor;
        this.autoSuggestionsPopUpWindow = autoSuggestor.getAutoSuggestionPopUpWindow();

        initComponent();
    }

    private void initComponent() {
        setFocusable(true);
        setForeground(suggestionsTextColor);
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent me) {
                super.mouseClicked(me);

                replaceWithSuggestedText();

                autoSuggestionsPopUpWindow.setVisible(false);
            }
        });

        getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), "Enter released");
        getActionMap().put("Enter released", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                replaceWithSuggestedText();
                autoSuggestionsPopUpWindow.setVisible(false);
            }
        });
    }

    public void setFocused(boolean focused) {
        if (focused) {
            setBorder(new LineBorder(suggestionBorderColor));
            setBackground(suggestionBorderColor);
            setForeground(Color.WHITE);
            setOpaque(true);
        } else {
            setBorder(null);
            setForeground(suggestionsTextColor);
            setOpaque(false);

        }
        repaint();
        this.focused = focused;
    }

    public boolean isFocused() {
        return focused;
    }

    private void replaceWithSuggestedText() {
        String suggestedWord = getText();

        int pos = suggestedWord.indexOf(" ");
        if (pos != -1) {
            suggestedWord = suggestedWord.substring(0, pos + 1);
        }

        String text = textComponent.getText();
        String typedWord = autoSuggestor.getCurrentlyTypedWord();
        if (!typedWord.startsWith("#")) {
            suggestedWord = typedWord.substring(0, typedWord.indexOf("#")) + suggestedWord;
        }
        String t = text.substring(0, text.lastIndexOf(typedWord));
        String tmp = t + text.substring(text.lastIndexOf(typedWord)).replace(typedWord, suggestedWord);
        textComponent.setText(tmp);
    }
}


text:
<?php

namespace Funct\Tests\Collection;

use Funct\Collection;

/**
 * Class CollectionToJsonTest
 *
 * @package Funct\Tests\Collection
 * @author Rod Elias <rod@wgo.com.br>
*/
class CollectionToJsonTest extends \PHPUnit_Framework_TestCase
{
    public function testCollectionToJson()
    {
        $input = ['a' => 1, 'b' => 2, 'c' => 3];

        $expected = json_encode($input);

        $this->assertEquals($expected, Collection\toJson($input));
    }
}


text:
package org.neo4j.driver.types;

import org.neo4j.driver.util.Immutable;

/**
 * A uniquely identifiable property container that can form part of a Neo4j graph.
 * @since 1.0
 */
@Immutable
public interface Entity extends MapAccessor {
    /**
     * A unique id for this Entity. Ids are guaranteed to remain stable for the duration of the session they were found in, but may be re-used for other
     * entities after that. As such, if you want a public identity to use for your entities, attaching an explicit 'id' property or similar persistent and
     * unique identifier is a better choice.
     *

     * Please note that depending on server configuration numeric id might not be available and accessing it will result in {@link IllegalStateException}.
     *
     * @return the id of this entity
     * @deprecated superseded by {@link #elementId()}
     */
    @Deprecated
    long id();

    /**
     * A unique id for this Entity.
     *

     * It is recommended to attach an explicit 'id' property or similar persistent and unique identifier if you want a public identity to use for your
     * entities.
     *
     * @return the id of this entity
     */
    String elementId();
}


text:
package io.quarkus.smallrye.reactivemessaging.devmode;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;

import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import io.smallrye.reactive.messaging.annotations.Channel;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.Router;

@ApplicationScoped
public class HttpFrontend {
    @Inject
    @Channel("processed")
    Instance<Publisher<String>> channel;

    @SuppressWarnings("SubscriberImplementation")
    public void init(@Observes Router router) {
        router.get().handler(rc -> {
            HttpServerResponse response = rc.response();
            channel.get().subscribe(new Subscriber<String>() {
                @Override
                public void onSubscribe(Subscription subscription) {
                    response.putHeader("Transfer-encoding", "chunked");
                    subscription.request(2);
                }

                @Override
                public void onNext(String s) {
                    response.write(s);
                }

                @Override
                public void onError(Throwable throwable) {
                    // ignore it.
                }

                @Override
                public void onComplete() {
                    response.end();
                }
            });
        });
    }
}


text:
/*
 *  Two objects in a reference loop on finalize_list, both having finalizers.
 *  Each finalizer will break the reference to the other object.
 *
 *  Assume X's finalizer executes first.  It deletes X.ref, so that Y's refcount
 *  drops to zero and Y gets refzero processed while still on finalize_list.
 *  This causes heap list corruption because refzero should only happen for
 *  objects on heap_allocated.
 *
 *  This is avoided by preincrementing refcounts when an object is inserted to
 *  finalize_list (cf. how mark-and-sweep considers finalize_list objects
 *  reachability roots).  This ensures that the refcount remains >= 1 at all
 *  times, and can only drop to zero once the finalizer for the object is
 *  complete.
 */

/*===
gc 1
lose refs
gc 2
fin x
fin y
still here
===*/

var x = {};
var y = {};
x.ref = y;
y.ref = x;

Duktape.fin(x, function (v) { print('fin x'); v.ref = null; });
Duktape.fin(y, function (v) { print('fin y'); v.ref = null; });

print('gc 1');
Duktape.gc();
print('lose refs');
x = y = null;
print('gc 2');
Duktape.gc();

print('still here');


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const baseResource_1 = require("./baseResource");
/**
 * Websudo
 *
 * @constructor Websudo
 * @property {IConnector} connector the jira connector instance
 */
class Websudo extends baseResource_1.baseResource {
    constructor(connector, Model, settings) {
        super(connector, Model, settings);
        /**
         * This method invalidates the any current WebSudo session.
         *
         * @method release
         * @memberOf Websudo#
         * @param {Object} options An object containing options to pass to the Jira API.
         * @param {string} options.token token The token to use for authentication. This token is supplied on a sucessful login. If not supplied, the default token (if set) is used
         * @param [callback] if supplied, called with result of api call
         * @return {Promise.<any>} result of api call
         */
        this.release = (...args) => {
            if (args.length === 0) {
                throw new Error("options must be passed");
            }
            let callback = ((typeof args[args.length - 1]) === 'function') ? args.pop() : null;
            let options = ((typeof args[0]) === 'object') ? args[0] : {};
            return this.makeRequest('release', 'DELETE', 'rest/auth/1/websudo', options, callback);
        };
        this.methods = [];
        this.register();
    }
}
exports.Websudo = Websudo;


text:
{% import "forms.html" as forms %}

		<form id="alert_filter_form" class="form form-inline" method="post" role="form">
			{{ forms.global_errors() }}
			{{ forms.inline_input('period_from', 'From', prefix = 'alert_filter_', placeholder = 'DD-MM-YYYY') }}
			{{ forms.inline_input('period_to', 'To', prefix = 'alert_filter_', placeholder = 'DD-MM-YYYY') }}
			{{ forms.inline_select('alert_level', 'Level', 'allAlertLevels', optionsText="'label'", optionsValue="'code'", prefix = 'alert_filter_') }}
			{{ forms.inline_select('alert_type', 'Type', 'allAlertTypes', optionsText="'label'", optionsValue="'code'", prefix = 'alert_filter_') }}
			<button	type="button" role="button" class="btn btn-primary" id="alert_filter_submit"
					data-bind="click: filterAlerts">Filter</button>
			<button	type="button" role="button" class="btn btn-default"
					data-bind="click: resetAlerts">Reset</button>
		</form>

				Time
				Type
				Module
				Message