text:
package pl.com.itsense.maven;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;

import pl.com.itsense.csssprites.CssSpriteImageProcessor;
import pl.com.itsense.csssprites.WebAppUtils;
import pl.com.itsense.maven.api.CssSprite;
import pl.com.itsense.maven.api.CssSpriteData;
import pl.com.itsense.maven.api.GSonConverter;
import pl.com.itsense.maven.api.Image;
import pl.com.itsense.maven.api.ImageData;
import pl.com.itsense.maven.api.StylesheetData;

@Mojo(name = "resourcehash", defaultPhase = LifecyclePhase.PROCESS_CLASSES)
public class ResourceHash extends AbstractMojo
{
    @Parameter(required = true)
    private List images;

    @Parameter(defaultValue = "${basedir}/src/main/webapp", required = false)
    private File warSourceDirectory;

    @Parameter(defaultValue = "${project.build.directory}/webapp-maven-temp", required = false)
    private File targetDirectory;

    @Parameter(defaultValue = "${project.build.directory}/webapp-maven-temp/resources", required = false)
    private File resourcesDirectory;

    @Component
    private MavenProject project;

    /**
     *
     * @param scripts
     * @param links
     * @return
     */
    private boolean createDirectory(final File directory)
    {
        boolean result = false;
        if (!directory.exists())
        {
            try
            {
                Files.createDirectory(directory.toPath());
                result = true;
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     *
     * @return
     * @throws MojoExecutionException
     */
    private ClassLoader getCompileClassLoader() throws MojoExecutionException
    {
        createDirectory(targetDirectory);
        createDirectory(resourcesDirectory);
        final List<String> classpathElements = new ArrayList<String>();
        try
        {
            classpathElements.addAll(project.getCompileClasspathElements());
            List<URL> projectClasspathList = new ArrayList<URL>();
            for (final String element : classpathElements)
            {
                try
                {
                    getLog().info("element: " + element);
                    projectClasspathList.add(new File(element).toURI().toURL());
                }
                catch (MalformedURLException e)
                {
                    throw new MojoExecutionException(element + " is an invalid classpath element", e);
                }
            }
            return new URLClassLoader(projectClasspathList.toArray(new URL[0]), getClass().getClassLoader());
        }
        catch (final DependencyResolutionRequiredException e)
        {
            throw new MojoExecutionException("Dependency resolution failed");
        }
    }

    private List<ImageData> imagesProcessing(final ClassLoader loader)
    {
        final ArrayList<ImageData> imageDataList = new ArrayList<ImageData>();
        if (images != null)
        {
            if (images.size() > 0)
            {
                final ArrayList<StylesheetData> stylesheets = new ArrayList<StylesheetData>();
                final ArrayList<CssSpriteData> sprites = new ArrayList<CssSpriteData>();
                for (final Object obj : images)
                {
                    final StringBuilder cssClasses = new StringBuilder();
                    if (obj instanceof String)
                    {
                        final String className = (String) obj;
                        try
                        {
                            final Class clazz = Class.forName(className, true, loader);
                            final Annotation annotation = clazz.getAnnotation(CssSprite.class);
                            final ArrayList<ImageData> spriteImages;
                            final CssSprite sprite;
                            if (annotation instanceof CssSprite)
                            {
                                sprite = (CssSprite) annotation;
                                spriteImages = new ArrayList<ImageData>();
                            }
                            else
                            {
                                sprite = null;
                                spriteImages = null;
                            }
                            final HashMap<String,String> absolutePaths = new HashMap<String,String>();
                            final HashMap<String,String> invertedAbsolutePaths = new HashMap<String,String>();
                            for (final Field field : clazz.getDeclaredFields())
                            {
                                final Image image = field.getAnnotation(Image.class);
                                if (image !=  null)
                                {
                                    final File imageFile = new File(warSourceDirectory, image.path());
                                    getLog().info("imageFile " + imageFile.getPath());
                                    try
                                    {
                                        final String ext = FilenameUtils.getExtension(imageFile.getName());
                                        final String hash = DigestUtils.md5Hex(new FileInputStream(imageFile));
                                        final ImageData imageData = WebAppUtils.getImageData(imageFile);
                                        imageData.setName(field.getName());
                                        imageData.setPath(image.path());
                                        imageData.setClassName(clazz.getName());
                                        if (StringUtils.isNotBlank(ext))
                                        {
                                            imageData.setHashFile(hash + "." + ext);
                                        }
                                        else
                                        {
                                            imageData.setHashFile( hash);
                                        }
                                        imageDataList.add(imageData);
                                        Files.copy(imageFile.toPath(), new File(resourcesDirectory, imageData.getHashFile()).toPath(), StandardCopyOption.REPLACE_EXISTING);
                                        // CSS PROCESSING
                                        if (image.css())
                                        {
                                            imageData.setCssClass(appendStylesheetClass(cssClasses, clazz, imageData));
                                        }
                                        else
                                        {
                                            imageData.setCssClass(StringUtils.EMPTY);
                                        }

                                        if (image.sprite() && spriteImages != null)
                                        {
                                            final ImageData spriteImageData = new ImageData(imageData);
                                            spriteImages.add(spriteImageData);
                                            absolutePaths.put(image.path(), imageFile.getPath());
                                            invertedAbsolutePaths.put(imageFile.getPath(), image.path());
                                        }
                                        getLog().info(imageFile.getPath() + " <=> " + imageData);
                                    }
                                    catch (IOException e)
                                    {
                                        e.printStackTrace();
                                    }
                                }
                            }
                            if (spriteImages != null &&  spriteImages.size() > 0)
                            {
                            	for (final ImageData spriteImage : spriteImages) spriteImage.setPath(absolutePaths.get(spriteImage.getPath()));
                                final CssSpriteData spriteData = WebAppUtils.getSpriteData(spriteImages.toArray(new ImageData[0]), null);
                                spriteData.setName(clazz.getName().replaceAll("\\.", "-"));
                                spriteData.setClassName(className);
                                sprites.add(spriteData);
                                CssSpriteImageProcessor.createImage(spriteData, resourcesDirectory, BufferedImage.TYPE_INT_RGB, Color.WHITE, "png");
                                for (final ImageData spriteImage : spriteData.getImages()) spriteImage.setPath(invertedAbsolutePaths.get(spriteImage.getPath()));
                                final String spriteStylesheet = WebAppUtils.getStylesheetClass(spriteData, StringUtils.EMPTY);
                                if (StringUtils.isNoneBlank(spriteStylesheet))
                                {

                                	final String hash = DigestUtils.md5Hex(spriteStylesheet.toString());
                                	spriteData.setHashFile(hash + ".css");
                                    try
                                    {
                                    	final Path path = new File(resourcesDirectory, hash + ".css").toPath();
                                    	Files.write(path, spriteStylesheet.toString().getBytes());
                                    }
                                    catch (IOException e)
                                    {
                                        e.printStackTrace();
                                    }
                                }
                                getLog().info("Sprite Added: " + spriteData);
                            }
                            if (cssClasses.length() > 0)
                            {
                                final String hash = DigestUtils.md5Hex(cssClasses.toString());
                                try
                                {
                                    final Path path = new File(resourcesDirectory, hash + ".css").toPath();
                                    Files.write(path, cssClasses.toString().getBytes());
                                    final StylesheetData stylesheetData = new StylesheetData();
                                    stylesheetData.setClassName(className);
                                    stylesheetData.setHashFile(hash);
                                    stylesheets.add(stylesheetData);
                                }
                                catch (IOException e)
                                {
                                    e.printStackTrace();
                                }
                            }
                        }
                        catch (ClassNotFoundException e)
                        {
                            e.printStackTrace();
                        }
                    }
                }

                final String jsonImages = imageDataList.size() > 0 ? GSonConverter.getGson().toJson(imageDataList) : StringUtils.EMPTY;
                final String jsonStylesheet = stylesheets.size() > 0 ? GSonConverter.getGson().toJson(stylesheets): StringUtils.EMPTY;
                final String jsonSprites = sprites.size() > 0 ? GSonConverter.getGson().toJson(sprites): StringUtils.EMPTY;
                try
                {
                    if (StringUtils.isNotBlank(jsonImages)) Files.write(new File(targetDirectory, "images.json").toPath(), jsonImages.getBytes());
                    if (StringUtils.isNotBlank(jsonStylesheet)) Files.write(new File(targetDirectory, "stylesheets.json").toPath(), jsonStylesheet.getBytes());
                    if (StringUtils.isNotBlank(jsonSprites)) Files.write(new File(targetDirectory, "sprites.json").toPath(), jsonSprites.getBytes());
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            else
            {
                getLog().error("Images have not been specified");
            }
        }
        else
        {
            getLog().error("images have not been specified");
        }
        return imageDataList;
    }
    /**
     *
     */
    public void execute() throws MojoExecutionException
    {
        final ClassLoader loader = getCompileClassLoader();
        getLog().info("ResourceHash: start executing ...");
        imagesProcessing(loader);
        getLog().info("ResourceHash: stop executing");
    }
    /**
     *
     * @return
     */
    private static String appendStylesheetClass(final StringBuilder buffer, final Class clazz, final ImageData imageData)
    {
        final String name = clazz.getName().replaceAll("\\.", "-") + "-" + imageData.getName();
        buffer.append(".").append(name).append("{\n");
        buffer.append("background-image: url(\"").append(imageData.getHashFile()).append("\");\n");
        buffer.append("background-repeat: no-repeat;\n");
        buffer.append("width:").append(imageData.getWidth()).append("px;\n");
        buffer.append("height:").append(imageData.getHeight()).append("px;\n");
        buffer.append("}\n");
        return name;
    }
}


text:
"""Test environment for client library tests.

This module has functions for creating keyspaces, tablets for the client
library test.
"""
#!/usr/bin/env python
# coding: utf-8

import hashlib
import random
import struct
import threading
import time
import traceback
import unittest

import environment
import tablet
import utils
from clientlib_tests import topo_schema
from clientlib_tests import db_class_unsharded
from clientlib_tests import db_class_sharded
from clientlib_tests import db_class_lookup

from vtdb import database_context
from vtdb import db_object
from vtdb import keyrange
from vtdb import keyrange_constants
from vtdb import keyspace
from vtdb import dbexceptions
from vtdb import shard_constants
from vtdb import vtdb_logger
from vtdb import vtgatev2
from vtdb import vtgate_cursor
from zk import zkocc

conn_class = vtgatev2
__tablets = None

shard_names = ['-80', '80-']
shard_kid_map = {'-80': [527875958493693904, 626750931627689502,
                         345387386794260318, 332484755310826578,
                         1842642426274125671, 1326307661227634652,
                         1761124146422844620, 1661669973250483744,
                         3361397649937244239, 2444880764308344533],
                 '80-': [9767889778372766922, 9742070682920810358,
                         10296850775085416642, 9537430901666854108,
                         10440455099304929791, 11454183276974683945,
                         11185910247776122031, 10460396697869122981,
                         13379616110062597001, 12826553979133932576],
                 }

pack_kid = struct.Struct('!Q').pack

def setUpModule():
  try:
    environment.topo_server().setup()
    setup_topology()

    # start mysql instance external to the test
    global __tablets
    setup_procs = []
    for tablet in __tablets:
      setup_procs.append(tablet.init_mysql())
    utils.wait_procs(setup_procs)
    create_db()
    start_tablets()
    utils.VtGate().start()
  except:
    tearDownModule()
    raise

def tearDownModule():
  global __tablets
  if utils.options.skip_teardown:
    return
  if __tablets is not None:
    tablet.kill_tablets(__tablets)
    teardown_procs = []
    for t in __tablets:
      teardown_procs.append(t.teardown_mysql())
    utils.wait_procs(teardown_procs, raise_on_error=False)

  environment.topo_server().teardown()

  utils.kill_sub_processes()
  utils.remove_tmp_files()

  if __tablets is not None:
    for t in __tablets:
      t.remove_tree()

def setup_topology():
  global __tablets
  if __tablets is None:
    __tablets = []

  keyspaces = topo_schema.keyspaces
  for ks in keyspaces:
    ks_name = ks[0]
    ks_type = ks[1]
    utils.run_vtctl(['CreateKeyspace', ks_name])
    if ks_type == shard_constants.UNSHARDED:
      shard_master = tablet.Tablet()
      shard_replica = tablet.Tablet()
      shard_master.init_tablet('master', keyspace=ks_name, shard='0')
      __tablets.append(shard_master)
      shard_replica.init_tablet('replica', keyspace=ks_name, shard='0')
      __tablets.append(shard_replica)
    elif ks_type == shard_constants.RANGE_SHARDED:
      utils.run_vtctl(['SetKeyspaceShardingInfo', '-force', ks_name,
                       'keyspace_id', 'uint64'])
      for shard_name in shard_names:
        shard_master = tablet.Tablet()
        shard_replica = tablet.Tablet()
        shard_master.init_tablet('master', keyspace=ks_name, shard=shard_name)
        __tablets.append(shard_master)
        shard_replica.init_tablet('replica', keyspace=ks_name, shard=shard_name)
        __tablets.append(shard_replica)
    utils.run_vtctl(['RebuildKeyspaceGraph', ks_name], auto_log=True)

def create_db():
  global __tablets
  for t in __tablets:
    t.create_db(t.dbname)
    ks_name = t.keyspace
    for table_tuple in topo_schema.keyspace_table_map[ks_name]:
      t.mquery(t.dbname, table_tuple[1])

def start_tablets():
  global __tablets
  # start tablets
  for t in __tablets:
    t.start_vttablet(wait_for_state=None)

  # wait for them to come in serving state
  for t in __tablets:
    t.wait_for_vttablet_state('SERVING')

  # InitShardMaster for master tablets
  for t in __tablets:
    if t.tablet_type == 'master':
      utils.run_vtctl(['InitShardMaster', t.keyspace+'/'+t.shard,
                       t.tablet_alias], auto_log=True)

  for ks in topo_schema.keyspaces:
    ks_name = ks[0]
    ks_type = ks[1]
    utils.run_vtctl(['RebuildKeyspaceGraph', ks_name],
                     auto_log=True)
    if ks_type == shard_constants.RANGE_SHARDED:
      utils.check_srv_keyspace('test_nj', ks_name,
                               'Partitions(master): -80 80-\n' +
                               'Partitions(rdonly): -80 80-\n' +
                               'Partitions(replica): -80 80-\n')

def get_connection(user=None, password=None):
  timeout = 10.0
  conn = None
  vtgate_addrs = {"vt": [utils.vtgate.addr(),]}
  conn = conn_class.connect(vtgate_addrs, timeout,
                            user=user, password=password)
  return conn

def get_keyrange(shard_name):
  kr = None
  if shard_name == keyrange_constants.SHARD_ZERO:
    kr = keyrange.KeyRange(keyrange_constants.NON_PARTIAL_KEYRANGE)
  else:
    kr = keyrange.KeyRange(shard_name)
  return kr

def _delete_all(keyspace, shard_name, table_name):
  vtgate_conn = get_connection()
  # This write is to set up the test with fresh insert
  # and hence performing it directly on the connection.
  vtgate_conn.begin()
  vtgate_conn._execute("delete from %s" % table_name, {},
                       keyspace, 'master',
                       keyranges=[get_keyrange(shard_name)])
  vtgate_conn.commit()

def restart_vtgate(extra_args={}):
  port = utils.vtgate.port
  utils.vtgate.kill()
  utils.VtGate(port=port).start(extra_args=extra_args)

def populate_table():
  keyspace = "KS_UNSHARDED"
  _delete_all(keyspace, keyrange_constants.SHARD_ZERO, 'vt_unsharded')
  vtgate_conn = get_connection()
  cursor = vtgate_conn.cursor(keyspace, 'master', keyranges=[get_keyrange(keyrange_constants.SHARD_ZERO),],writable=True)
  cursor.begin()
  for x in xrange(10):
    cursor.execute('insert into vt_unsharded (id, msg) values (%s, %s)' % (str(x), 'msg'), {})
  cursor.commit()

class TestUnshardedTable(unittest.TestCase):

  def setUp(self):
    self.vtgate_addrs = {"vt": [utils.vtgate.addr(),]}
    self.dc = database_context.DatabaseContext(self.vtgate_addrs)
    self.all_ids = []
    with database_context.WriteTransaction(self.dc) as context:
      for x in xrange(20):
        ret_id = db_class_unsharded.VtUnsharded.insert(context.get_cursor(),
                                                       msg="test message")
        self.all_ids.append(ret_id)

  def tearDown(self):
    _delete_all("KS_UNSHARDED", "0", 'vt_unsharded')

  def test_read(self):
    id_val = self.all_ids[0]
    with database_context.ReadFromMaster(self.dc) as context:
      rows = db_class_unsharded.VtUnsharded.select_by_id(
          context.get_cursor(), id_val)
      expected = 1
      self.assertEqual(len(rows), expected, "wrong number of rows fetched %d, expected %d" % (len(rows), expected))
      self.assertEqual(rows[0].id, id_val, "wrong row fetched")

  def test_update_and_read(self):
    id_val = self.all_ids[0]
    where_column_value_pairs = [('id', id_val)]
    with database_context.WriteTransaction(self.dc) as context:
      update_cols = [('msg', "test update"),]
      db_class_unsharded.VtUnsharded.update_columns(context.get_cursor(),
                                                    where_column_value_pairs,
                                                    update_column_value_pairs=update_cols)

    with database_context.ReadFromMaster(self.dc) as context:
      rows = db_class_unsharded.VtUnsharded.select_by_id(context.get_cursor(), id_val)
      self.assertEqual(len(rows), 1, "wrong number of rows fetched")
      self.assertEqual(rows[0].msg, "test update", "wrong row fetched")

  def test_delete_and_read(self):
    id_val = self.all_ids[-1]
    where_column_value_pairs = [('id', id_val)]
    with database_context.WriteTransaction(self.dc) as context:
      db_class_unsharded.VtUnsharded.delete_by_columns(context.get_cursor(),
                                                    where_column_value_pairs)

    with database_context.ReadFromMaster(self.dc) as context:
      rows = db_class_unsharded.VtUnsharded.select_by_id(context.get_cursor(), id_val)
      self.assertEqual(len(rows), 0, "wrong number of rows fetched")
    self.all_ids = self.all_ids[:-1]

  def test_count(self):
    with database_context.ReadFromMaster(self.dc) as context:
      count = db_class_unsharded.VtUnsharded.get_count(
          context.get_cursor(), msg="test message")
      expected = len(self.all_ids)
      self.assertEqual(count, expected, "wrong count fetched; expected %d got %d" % (expected, count))

  def test_min_id(self):
    with database_context.ReadFromMaster(self.dc) as context:
      min_id = db_class_unsharded.VtUnsharded.get_min(
          context.get_cursor())
      expected = min(self.all_ids)
      self.assertEqual(min_id, expected, "wrong min value fetched; expected %d got %d" % (expected, min_id))

  def test_max_id(self):
    with database_context.ReadFromMaster(self.dc) as context:
      max_id = db_class_unsharded.VtUnsharded.get_max(
          context.get_cursor())
      self.all_ids.sort()
      expected = max(self.all_ids)
      self.assertEqual(max_id, expected, "wrong max value fetched; expected %d got %d" % (expected, max_id))

class TestRangeSharded(unittest.TestCase):
  def populate_tables(self):
    self.user_id_list = []
    self.song_id_list = []
    self.user_song_map = {}
    r = random.Random()
    # This should create the lookup entries and sharding key.
    with database_context.WriteTransaction(self.dc) as context:
      for x in xrange(20):
        # vt_user - EntityRangeSharded; creates username:user_id lookup
        user_id = db_class_sharded.VtUser.insert(context.get_cursor(),
                                       username="user%s" % x, msg="test message")
        self.user_id_list.append(user_id)

        # vt_user_email - RangeSharded; references user_id:keyspace_id hash
        email = 'user%s@google.com' % x
        m = hashlib.md5()
        m.update(email)
        email_hash = m.digest()
        entity_id_map={'user_id':user_id}
        db_class_sharded.VtUserEmail.insert(
            context.get_cursor(entity_id_map=entity_id_map),
            user_id=user_id, email=email,
            email_hash=email_hash)

        # vt_song - EntityRangeSharded; creates song_id:user_id lookup
        num_songs_for_user = r.randint(1, 5)
        for i in xrange(num_songs_for_user):
          song_id = db_class_sharded.VtSong.insert(context.get_cursor(),
                                                   user_id=user_id, title="Test Song")
          self.song_id_list.append(song_id)
          self.user_song_map.setdefault(user_id, []).append(song_id)

          # vt_song_detail - RangeSharded; references song_id:user_id lookup
          entity_id_map = {'song_id':song_id}
          db_class_sharded.VtSongDetail.insert(context.get_cursor(entity_id_map=entity_id_map),
                                               song_id=song_id, album_name="Test album",
                                               artist="Test artist")

  def setUp(self):
    self.vtgate_addrs = {"vt": [utils.vtgate.addr(),]}
    self.dc = database_context.DatabaseContext(self.vtgate_addrs)
    self.populate_tables()

  def tearDown(self):
    with database_context.WriteTransaction(self.dc) as context:
      for uid in self.user_id_list:
        try:
          db_class_sharded.VtUser.delete_by_columns(context.get_cursor(entity_id_map={'id':uid}),
                                                    [('id', uid),])
          db_class_sharded.VtUserEmail.delete_by_columns(context.get_cursor(entity_id_map={'user_id':uid}),
                                                         [('user_id', uid),])
          db_class_sharded.VtSong.delete_by_columns(context.get_cursor(entity_id_map={'user_id':uid}),
                                                         [('user_id', uid),])
          song_id_list = self.user_song_map[uid]
          for sid in song_id_list:
            db_class_sharded.VtSongDetail.delete_by_columns(context.get_cursor(entity_id_map={'song_id':sid}),
                                                            [('song_id', sid),])
        except dbexceptions.DatabaseError as e:
          if str(e) == "DB Row not found":
            pass

  def test_sharding_key_read(self):
    user_id = self.user_id_list[0]
    with database_context.ReadFromMaster(self.dc) as context:
      where_column_value_pairs = [('id', user_id),]
      entity_id_map = dict(where_column_value_pairs)
      rows = db_class_sharded.VtUser.select_by_columns(
          context.get_cursor(entity_id_map=entity_id_map),
          where_column_value_pairs)
      self.assertEqual(len(rows), 1, "wrong number of rows fetched")

      where_column_value_pairs = [('user_id', user_id),]
      entity_id_map = dict(where_column_value_pairs)
      rows = db_class_sharded.VtUserEmail.select_by_columns(
          context.get_cursor(entity_id_map=entity_id_map),
          where_column_value_pairs)
      self.assertEqual(len(rows), 1, "wrong number of rows fetched")

      where_column_value_pairs = [('user_id', user_id),]
      entity_id_map = dict(where_column_value_pairs)
      rows = db_class_sharded.VtSong.select_by_columns(
          context.get_cursor(entity_id_map=entity_id_map),
          where_column_value_pairs)
      self.assertEqual(len(rows), len(self.user_song_map[user_id]), "wrong number of rows fetched")

  def test_entity_id_read(self):
    user_id = self.user_id_list[0]
    with database_context.ReadFromMaster(self.dc) as context:
      entity_id_map = {'username': 'user0'}
      rows = db_class_sharded.VtUser.select_by_columns(
          context.get_cursor(entity_id_map=entity_id_map),
          [('id', user_id),])
      self.assertEqual(len(rows), 1, "wrong number of rows fetched")

      where_column_value_pairs = [('id', self.user_song_map[user_id][0]),]
      entity_id_map = dict(where_column_value_pairs)
      rows = db_class_sharded.VtSong.select_by_columns(
          context.get_cursor(entity_id_map=entity_id_map),
          where_column_value_pairs)
      self.assertEqual(len(rows), 1, "wrong number of rows fetched")

      where_column_value_pairs = [('song_id', self.user_song_map[user_id][0]),]
      entity_id_map = dict(where_column_value_pairs)
      rows = db_class_sharded.VtSongDetail.select_by_columns(
          context.get_cursor(entity_id_map=entity_id_map),
          where_column_value_pairs)
      self.assertEqual(len(rows), 1, "wrong number of rows fetched")

  def test_in_clause_read(self):
    with database_context.ReadFromMaster(self.dc) as context:
      user_id_list = [self.user_id_list[0], self.user_id_list[1]]

      where_column_value_pairs = (('id', user_id_list),)
      entity_id_map = dict(where_column_value_pairs)
      rows = db_class_sharded.VtUser.select_by_ids(
          context.get_cursor(entity_id_map=entity_id_map),
          where_column_value_pairs)
      self.assertEqual(len(rows), 2, "wrong number of rows fetched")
      got = [row.id for row in rows]
      got.sort()
      self.assertEqual(user_id_list, got, "wrong rows fetched; expected %s got %s" % (user_id_list, got))

      username_list = [row.username for row in rows]
      username_list.sort()
      where_column_value_pairs = (('username', username_list),)
      entity_id_map = dict(where_column_value_pairs)
      rows = db_class_sharded.VtUser.select_by_ids(
          context.get_cursor(entity_id_map=entity_id_map),
          where_column_value_pairs)
      self.assertEqual(len(rows), 2, "wrong number of rows fetched")
      got = [row.username for row in rows]
      got.sort()
      self.assertEqual(username_list, got, "wrong rows fetched; expected %s got %s" % (username_list, got))

      where_column_value_pairs = (('user_id', user_id_list),)
      entity_id_map = dict(where_column_value_pairs)
      rows = db_class_sharded.VtUserEmail.select_by_ids(
          context.get_cursor(entity_id_map=entity_id_map),
          where_column_value_pairs)
      self.assertEqual(len(rows), 2, "wrong number of rows fetched")
      got = [row.user_id for row in rows]
      got.sort()
      self.assertEqual(user_id_list, got, "wrong rows fetched; expected %s got %s" % (user_id_list, got))

      song_id_list = []
      for user_id in user_id_list:
        song_id_list.extend(self.user_song_map[user_id])
      song_id_list.sort()
      where_column_value_pairs = [('id', song_id_list),]
      entity_id_map = dict(where_column_value_pairs)
      rows = db_class_sharded.VtSong.select_by_columns(
          context.get_cursor(entity_id_map=entity_id_map),
          where_column_value_pairs)
      got = [row.id for row in rows]
      got.sort()
      self.assertEqual(song_id_list, got, "wrong rows fetched %s got %s" % (song_id_list, got))

      where_column_value_pairs = [('song_id', song_id_list),]
      entity_id_map = dict(where_column_value_pairs)
      rows = db_class_sharded.VtSongDetail.select_by_columns(
          context.get_cursor(entity_id_map=entity_id_map),
          where_column_value_pairs)
      got = [row.song_id for row in rows]
      got.sort()
      self.assertEqual(song_id_list, got, "wrong rows fetched %s got %s" % (song_id_list, got))

  def test_keyrange_read(self):
    where_column_value_pairs = []
    with database_context.ReadFromMaster(self.dc) as context:
      rows1 = db_class_sharded.VtUser.select_by_columns(
          context.get_cursor(keyrange='-80'), where_column_value_pairs)
      rows2 = db_class_sharded.VtUser.select_by_columns(
          context.get_cursor(keyrange='80-'), where_column_value_pairs)
      fetched_rows = len(rows1) + len(rows2)
      expected = len(self.user_id_list)
      self.assertEqual(fetched_rows, expected, "wrong number of rows fetched expected:%d got:%d" % (expected, fetched_rows))

  def test_scatter_read(self):
    where_column_value_pairs = []
    with database_context.ReadFromMaster(self.dc) as context:
      rows = db_class_sharded.VtUser.select_by_columns(
          context.get_cursor(keyrange=keyrange_constants.NON_PARTIAL_KEYRANGE),
          where_column_value_pairs)
      self.assertEqual(len(rows), len(self.user_id_list), "wrong number of rows fetched, expecting %d got %d" % (len(self.user_id_list), len(rows)))

  def test_streaming_read(self):
    where_column_value_pairs = []
    with database_context.ReadFromMaster(self.dc) as context:
      rows = db_class_sharded.VtUser.select_by_columns_streaming(
          context.get_cursor(keyrange=keyrange_constants.NON_PARTIAL_KEYRANGE),
          where_column_value_pairs)
      got_user_id_list = []
      for r in rows:
        got_user_id_list.append(r.id)
      self.assertEqual(len(got_user_id_list), len(self.user_id_list), "wrong number of rows fetched")

  def update_columns(self):
    with database_context.WriteTransaction(self.dc) as context:
      user_id = self.user_id_list[1]
      where_column_value_pairs = [('id', user_id),]
      entity_id_map = {'id': user_id}
      new_username = 'new_user%s' % user_id
      update_cols = [('username', new_username),]
      db_class_sharded.VtUser.update_columns(context.get_cursor(entity_id_map=entity_id_map),
                                             where_column_value_pairs,
                                             update_column_value_pairs=update_cols)
      # verify the updated value.
      where_column_value_pairs = [('id', user_id),]
      rows = db_class_sharded.VtUser.select_by_columns(
          context.get_cursor(entity_id_map={'id': user_id}),
          where_column_value_pairs)
      self.assertEqual(len(rows), 1, "wrong number of rows fetched")
      self.assertEqual(new_username, rows[0].username)

      where_column_value_pairs = [('user_id', user_id),]
      entity_id_map = {'user_id': user_id}
      new_email = 'new_user%s@google.com' % user_id
      m = hashlib.md5()
      m.update(new_email)
      email_hash = m.digest()
      update_cols = [('email', new_email), ('email_hash', email_hash)]
      db_class_sharded.VtUserEmail.update_columns(context.get_cursor(entity_id_map={'user_id':user_id}),
                                                  where_column_value_pairs,
                                                  update_column_value_pairs=update_cols)

    # verify the updated value.
    with database_context.ReadFromMaster(self.dc) as context:
      where_column_value_pairs = [('user_id', user_id),]
      entity_id_map = dict(where_column_value_pairs)
      rows = db_class_sharded.VtUserEmail.select_by_ids(
          context.get_cursor(entity_id_map=entity_id_map),
          where_column_value_pairs)
      self.assertEqual(len(rows), 1, "wrong number of rows fetched")
      self.assertEqual(new_email, rows[0].email)
    self.user_id_list.sort()

  def delete_columns(self):
    user_id = self.user_id_list[-1]
    with database_context.WriteTransaction(self.dc) as context:
      where_column_value_pairs = [('id', user_id),]
      entity_id_map = {'id': user_id}
      db_class_sharded.VtUser.delete_by_columns(context.get_cursor(entity_id_map=entity_id_map),
                                             where_column_value_pairs)

      where_column_value_pairs = [('user_id', user_id),]
      entity_id_map = {'user_id': user_id}
      db_class_sharded.VtUserEmail.delete_by_columns(context.get_cursor(entity_id_map=entity_id_map),
                                                  where_column_value_pairs)

    with database_context.ReadFromMaster(self.dc) as context:
      rows = db_class_sharded.VtUser.select_by_columns(
          context.get_cursor(entity_id_map=entity_id_map),
          where_column_value_pairs)
      self.assertEqual(len(rows), 0, "wrong number of rows fetched")

      rows = db_class_sharded.VtUserEmail.select_by_ids(
          context.get_cursor(entity_id_map=entity_id_map),
          where_column_value_pairs)
      self.assertEqual(len(rows), 0, "wrong number of rows fetched")
    self.user_id_list = self.user_id_list[:-1]
    self.user_id_list.sort()

  def test_count(self):
    with database_context.ReadFromMaster(self.dc) as context:
      count = db_class_sharded.VtUser.get_count(
          context.get_cursor(keyrange=keyrange_constants.NON_PARTIAL_KEYRANGE),
          msg="test message")
      expected = len(self.user_id_list)
      self.assertEqual(count, expected, "wrong count fetched; expected %d got %d" % (expected, count))

  def test_min_id(self):
    with database_context.ReadFromMaster(self.dc) as context:
      min_id = db_class_sharded.VtUser.get_min(
          context.get_cursor(keyrange=keyrange_constants.NON_PARTIAL_KEYRANGE))
      self.user_id_list.sort()
      expected = min(self.user_id_list)
      rows1 = db_class_sharded.VtUser.select_by_columns(
          context.get_cursor(keyrange=keyrange_constants.NON_PARTIAL_KEYRANGE), [])
      id_list = [row.id for row in rows1]
      self.assertEqual(min_id, expected, "wrong min value fetched; expected %d got %d" % (expected, min_id))

  def test_max_id(self):
    with database_context.ReadFromMaster(self.dc) as context:
      max_id = db_class_sharded.VtUser.get_max(
          context.get_cursor(keyrange=keyrange_constants.NON_PARTIAL_KEYRANGE))
      expected = max(self.user_id_list)
      self.assertEqual(max_id, expected, "wrong max value fetched; expected %d got %d" % (expected, max_id))

  def test_batch_read(self):
    # TODO(sougou): fix
    return
    # 1. Create select queries using DB classes.
    query_list = []
    bv_list = []
    user_id_list = [self.user_id_list[0], self.user_id_list[1]]
    where_column_value_pairs = (('id', user_id_list),)
    entity_id_map = dict(where_column_value_pairs)
    q, bv = db_class_sharded.VtUser.create_select_query(where_column_value_pairs)
    query_list.append(q)
    bv_list.append(bv)
    where_column_value_pairs = (('user_id', user_id_list),)
    q, bv = db_class_sharded.VtUserEmail.create_select_query(where_column_value_pairs)
    query_list.append(q)
    bv_list.append(bv)
    with database_context.ReadFromMaster(self.dc) as context:
      # 2. Cursor Creation using one of the DB classes.
      cursor = context.get_cursor(entity_id_map=entity_id_map)(db_class_sharded.VtUser)
      # 3. Batch execution of reads.
      results = db_object.execute_batch_read(
          cursor, query_list, bv_list)
      self.assertEqual(len(results), len(query_list))
      res_ids = [row.id for row in results[0]]
      res_user_ids = [row.user_id for row in results[1]]
      self.assertEqual(res_ids, user_id_list)
      self.assertEqual(res_user_ids, user_id_list)

  def test_batch_write(self):
    # TODO(sougou): fix
    return
    # 1. Create DMLs using DB Classes.
    query_list = []
    bv_list = []
    # Update VtUser table.
    user_id = self.user_id_list[1]
    where_column_value_pairs = (('id', user_id),)
    entity_id_map = dict(where_column_value_pairs)
    new_username = 'new_user%s' % user_id
    update_cols = [('username', new_username),]
    q, bv = db_class_sharded.VtUser.create_update_query(
        where_column_value_pairs, update_column_value_pairs=update_cols)
    query_list.append(q)
    bv_list.append(bv)
    # Update VtUserEmail table.
    where_column_value_pairs = [('user_id', user_id),]
    new_email = 'new_user%s@google.com' % user_id
    m = hashlib.md5()
    m.update(new_email)
    email_hash = m.digest()
    update_cols = [('email', new_email), ('email_hash', email_hash)]
    q, bv = db_class_sharded.VtUserEmail.create_update_query(
        where_column_value_pairs, update_column_value_pairs=update_cols)
    query_list.append(q)
    bv_list.append(bv)
    # Delete a VtSong row
    where_column_value_pairs = [('user_id', user_id),]
    q, bv = db_class_sharded.VtSong.create_delete_query(where_column_value_pairs)
    query_list.append(q)
    bv_list.append(bv)
    with database_context.WriteTransaction(self.dc) as context:
      # 2. Routing for query_list is done by associating
      # the common entity_id to the cursor.
      # NOTE: cursor creation needs binding to a particular db class,
      # so we create a writable cursor using the common entity (user_id).
      # This entity_id is used to derive the keyspace_id for routing the dmls.
      entity_id_map = {'id': user_id}
      cursor = context.get_cursor(entity_id_map=entity_id_map)(db_class_sharded.VtUser)
      # 3. Execute the writable batch query.
      results = db_object.execute_batch_write(
          cursor, query_list, bv_list)

      # 4. Verify results
      self.assertEqual(len(results), len(query_list))
      self.assertEqual(results[0]['rowcount'], 1, "VtUser update didn't update 1 row")
      self.assertEqual(results[1]['rowcount'], 1, "VtUserEmail update didn't update 1 row")
      self.assertEqual(results[2]['rowcount'], len(self.user_song_map[user_id]),
                       "VtSong deleted '%d' rows, expected '%d'" % (results[2]['rowcount'], len(self.user_song_map[user_id])))

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

redpajama_set_name: RedPajamaGithub


text:
import sys

# import statepoint
sys.path.insert(0, '../../src/utils')
import statepoint

# read in statepoint file
if len(sys.argv) > 1:
    sp = statepoint.StatePoint(sys.argv[1])
else:
    sp = statepoint.StatePoint('statepoint.08.binary')
sp.read_results()
sp.read_source()

# set up output string
outstr = ''

# write out k-combined
outstr += 'k-combined:\n'
outstr += "{0:12.6E} {1:12.6E}\n".format(sp.k_combined[0], sp.k_combined[1])

# write out xyz
xyz = sp.source[0].xyz
for i in xyz:
    outstr += "{0:12.6E} ".format(i)
outstr += "\n"

# write results to file
with open('results_test.dat','w') as fh:
    fh.write(outstr)


text:
@interface PodsDummy_Pods_JKLogDispatcherDemo_JKLogDispatcher : NSObject
@end
@implementation PodsDummy_Pods_JKLogDispatcherDemo_JKLogDispatcher
@end


text:
var LayerController, Log, Module, Promise, pasteHTML, superagent, _,
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  __slice = [].slice;

_ = require('lodash');

Promise = require('bluebird');

superagent = require('superagent');

Module = require('./module');

pasteHTML = require('./pasteHTML');

Log = require('./log');

LayerController = (function(_super) {
  __extends(LayerController, _super);

  LayerController.prototype.emitAll = function() {
    var args, event;
    event = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
    return new Promise((function(_this) {
      return function(resolve, reject) {
        var counter, stop;
        counter = _this.listeners(event).length;
        if (!counter) {
          return resolve(true);
        }
        stop = false;
        args.unshift(event, function(abort) {
          if (stop) {
            return;
          }
          if (abort != null) {
            if (abort instanceof Error) {
              stop = true;
              return reject(abort);
            }
            if (!abort) {
              stop = true;
              return resolve(null);
            }
          }
          if (--counter === 0) {
            return resolve(true);
          }
        });
        return _this.emit.apply(_this, args);
      };
    })(this));
  };

  LayerController.prototype._conflictTask = {
    'stateAll': ['state', 'hideAll', 'hide', 'show', 'insert'],
    'state': ['hideAll', 'hide', 'show', 'insert', 'reset'],
    'hideAll': ['hide', 'show', 'insert'],
    'hide': ['show', 'insert', 'reset'],
    'show': ['hideAll', 'hide', 'insert', 'reset'],
    'insert': ['hideAll', 'hide', 'reset'],
    'load': ['reset'],
    'parse': ['reset'],
    'reset': ['hide', 'show', 'insert', 'load', 'parse']
  };

  LayerController.prototype._afterConflictTask = function(name, type) {
    var conflictTasks, task, _name, _ref, _task;
    task = this.task[name];
    if (task.run) {
      return task;
    }
    if (!((_ref = this._conflictTask[name]) != null ? _ref.length : void 0)) {
      return task;
    }
    conflictTasks = (function() {
      var _ref1, _results;
      _ref1 = this.task;
      _results = [];
      for (_name in _ref1) {
        if (!__hasProp.call(_ref1, _name)) continue;
        _task = _ref1[_name];
        if ((this._conflictTask[name].indexOf(_name) !== -1) && _task.run) {
          _results.push(_task.run);
        }
      }
      return _results;
    }).call(this);
    if (!conflictTasks.length) {
      return task;
    }
    task.run = Promise.all(conflictTasks)["catch"]().then((function(_this) {
      return function() {
        _this._deleteTask(task);
        return _this[name](type);
      };
    })(this));
    return task;
  };

  LayerController.prototype._task = function(name, type) {
    var task;
    if (!this.task[name]) {
      this.task[name] = {};
    }
    task = this.task[name];
    if (task.run) {
      if (task.type === type) {
        return task;
      }
      task.run.then((function(_this) {
        return function() {
          return _this[name](type);
        };
      })(this));
    }
    task.type = type;
    return this._afterConflictTask(name, type);
  };

  LayerController.prototype._deleteTask = function(task, fn, arg) {
    delete task.type;
    delete task.run;
    delete task.err;
    if (fn != null) {
      return fn(arg);
    }
  };

  LayerController.prototype.test = function(testValue) {
    var task;
    task = this._task('load', testValue);
    if (task.run) {
      return task.run;
    }
    return task.run = new Promise((function(_this) {
      return function(resolve, reject) {
        var emits;
        emits = [];
        emits.push(_this.emitAll('test', testValue));
        if (testValue === 24) {
          emits.push(_this.emitAll('test.prop', testValue, 42));
        }
        return resolve(Promise.all(emits).then(function(emits) {
          var success, _i, _len;
          for (_i = 0, _len = emits.length; _i < _len; _i++) {
            success = emits[_i];
            if (!success) {
              return _this._deleteTask(task, Promise.resolve, null);
            }
          }
          if (_this.testCount == null) {
            _this.testCount = 0;
          }
          _this.testCount++;
          _this.log.debug('test action');
          emits = [];
          emits.push(_this.emitAll('tested', testValue));
          if (testValue === 24) {
            emits.push(_this.emitAll('tested.prop', testValue, 42));
          }
          return Promise.all(emits).then(function(emits) {
            var _j, _len1;
            for (_j = 0, _len1 = emits.length; _j < _len1; _j++) {
              success = emits[_j];
              if (!success) {
                return _this._deleteTask(task, Promise.resolve, null);
              }
            }
            return _this._deleteTask(task, Promise.resolve, _this);
          });
        }));
      };
    })(this))["catch"]((function(_this) {
      return function(err) {
        if (task.err == null) {
          _this.log.error(err);
        }
        _this._deleteTask(task);
        throw err;
      };
    })(this));
  };

  LayerController.prototype.render = function(tpl) {
    return _.template(tpl, this);
  };

  LayerController.prototype._originPath = function(path) {
    if (this.request.origin && path.search('//') !== 0 && path.search('/') === 0) {
      path = this.request.origin + path;
    }
    return path;
  };

  LayerController.prototype._load = function(path, key, data) {
    var paths, _key, _path;
    if (!this.data) {
      this.data = {};
    }
    if (!this._data) {
      this._data = {};
    }
    if (!path) {
      path = this.download;
      data = this.data;
      key = 'tpl';
    }
    if ((key != null) && !data) {
      data = this.data;
    }
    if (_.isString(path)) {
      path = this.render(path);
      path = this._originPath(path);
      if (this.request.cache[path]) {
        if (!((key != null) && data)) {
          return Promise.resolve(this.request.cache[path]);
        }
        data[key] = this.request.cache[path];
        return Promise.resolve(data);
      }
      if (!this.request.loading[path]) {
        this.request.loading[path] = this.request.agent.get(path);
        if (this.request.headers) {
          this.request.loading[path].set(this.request.headers);
        }
        this.request.loading[path].set('x-layer-controller-proxy', 'true');
        this.request.loading[path] = Promise.promisify(this.request.loading[path].end, this.request.loading[path])();
      }
      return this.request.loading[path].then((function(_this) {
        return function(res) {
          var _ref;
          delete _this.request.loading[path];
          if (res.error) {
            _this.log.error("load " + path + ":", ((_ref = res.error) != null ? _ref.message : void 0) || res.error);
            return;
          }
          if (res.body && Object.keys(res.body).length) {
            _this.request.cache[path] = res.body;
          } else {
            _this.request.cache[path] = res.text;
          }
          _this._data[path] = _this.request.cache[path];
          if (!((key != null) && data)) {
            return _this.request.cache[path];
          }
          data[key] = _this.request.cache[path];
          return data;
        };
      })(this));
    } else if (_.isArray(path)) {
      return Promise.each(path, (function(_this) {
        return function(item, i, value) {
          return _this._load(item, i, data);
        };
      })(this)).then(function(results) {
        return data;
      });
    } else if (_.isObject(path)) {
      paths = [];
      for (_key in path) {
        if (!__hasProp.call(path, _key)) continue;
        _path = path[_key];
        if (_.isObject(_path)) {
          data[_key] = {};
          paths.push(this._load(_path, _key, data[_key]));
        } else {
          paths.push(this._load(_path, _key, data));
        }
      }
      return Promise.all(paths).then(function() {
        return data;
      });
    }
  };

  LayerController.prototype.load = function() {
    var task;
    task = this._task('load');
    if (task.run) {
      return task.run;
    }
    if (this.data != null) {
      return Promise.resolve(this);
    }
    if (!this.download) {
      return Promise.reject(new Error(this.log.error('layer.download does not exist')));
    }
    return task.run = new Promise((function(_this) {
      return function(resolve, reject) {
        var emits;
        emits = [];
        emits.push(_this.emitAll('load'));
        return resolve(Promise.all(emits).then(function(emits) {
          var success, _i, _len;
          for (_i = 0, _len = emits.length; _i < _len; _i++) {
            success = emits[_i];
            if (!success) {
              return _this._deleteTask(task, Promise.resolve, null);
            }
          }
          return _this._load().then(function() {
            emits = [];
            emits.push(_this.emitAll('loaded'));
            return Promise.all(emits).then(function(emits) {
              var _j, _len1;
              for (_j = 0, _len1 = emits.length; _j < _len1; _j++) {
                success = emits[_j];
                if (!success) {
                  return _this._deleteTask(task, Promise.resolve, null);
                }
              }
              return _this._deleteTask(task, Promise.resolve, _this);
            });
          });
        }));
      };
    })(this))["catch"]((function(_this) {
      return function(err) {
        if (task.err == null) {
          _this.log.error(err);
        }
        _this._deleteTask(task);
        throw err;
      };
    })(this));
  };

  LayerController.prototype.reparseAll = function(force) {
    return this.reparse(force).then((function(_this) {
      return function(layer) {
        return Promise.all(_this.childLayers.map(function(layer) {
          return layer.reparse(force);
        }))["catch"]().then(function() {
          return _this;
        });
      };
    })(this));
  };

  LayerController.prototype.reparse = function(force) {
    var _ref;
    if (!((_ref = this.elementList) != null ? _ref.length : void 0) || !this.isShown) {
      if (!force) {
        return Promise.resolve(null);
      }
      return this.show(true).then((function(_this) {
        return function(layer) {
          if (layer) {
            return layer;
          }
          return _this.hideAll().then(function() {
            return layer;
          });
        };
      })(this));
    }
    return this._show(true).then((function(_this) {
      return function(layer) {
        if (layer || !force) {
          return layer;
        }
        return _this.hideAll().then(function() {
          return layer;
        });
      };
    })(this));
  };

  LayerController.prototype.parse = function(force) {
    var task, _ref;
    if (force == null) {
      force = false;
    }
    task = this._task('parse', force);
    if (task.run) {
      return task.run;
    }
    if ((this.html != null) && !force) {
      return Promise.resolve(this);
    }
    if (((_ref = this.data) != null ? _ref.tpl : void 0) == null) {
      return Promise.reject(new Error(this.log.error('layer.data.tpl does not exist')));
    }
    return task.run = new Promise((function(_this) {
      return function(resolve, reject) {
        var emits;
        emits = [];
        emits.push(_this.emitAll('parse'));
        return resolve(Promise.all(emits).then(function(emits) {
          var success, _i, _len;
          for (_i = 0, _len = emits.length; _i < _len; _i++) {
            success = emits[_i];
            if (!success) {
              return _this._deleteTask(task, Promise.resolve, null);
            }
          }
          _this.html = _this.render(_this.data.tpl);
          emits = [];
          emits.push(_this.emitAll('parsed'));
          return Promise.all(emits).then(function(emits) {
            var _j, _len1;
            for (_j = 0, _len1 = emits.length; _j < _len1; _j++) {
              success = emits[_j];
              if (!(!success)) {
                continue;
              }
              _this.html = null;
              return _this._deleteTask(task, Promise.resolve, null);
            }
            return _this._deleteTask(task, Promise.resolve, _this);
          });
        }));
      };
    })(this))["catch"]((function(_this) {
      return function(err) {
        if (task.err == null) {
          _this.log.error(err);
        }
        _this._deleteTask(task);
        throw err;
      };
    })(this));
  };

  LayerController.prototype._make = function(force) {
    var _ref;
    if (this.download) {
      return this.load().then((function(_this) {
        return function(layer) {
          if (!layer) {
            return null;
          }
          return _this.parse(force);
        };
      })(this));
    } else {
      if (((_ref = this.data) != null ? _ref.tpl : void 0) == null) {
        return Promise.resolve(this);
      }
      return this.parse(force);
    }
  };

  LayerController.prototype.make = function(force) {
    var task;
    if (force == null) {
      force = false;
    }
    task = this._task('make', force);
    if (task.run) {
      return task.run;
    }
    return task.run = new Promise((function(_this) {
      return function(resolve, reject) {
        var emits;
        emits = [];
        emits.push(_this.emitAll('make'));
        return resolve(Promise.all(emits).then(function(emits) {
          var success, _i, _len;
          for (_i = 0, _len = emits.length; _i < _len; _i++) {
            success = emits[_i];
            if (!success) {
              return _this._deleteTask(task, Promise.resolve, null);
            }
          }
          return _this._make(force).then(function(layer) {
            if (!layer) {
              return _this._deleteTask(task, Promise.resolve, null);
            }
            emits = [];
            emits.push(_this.emitAll('made'));
            return Promise.all(emits).then(function(emits) {
              var _j, _len1;
              for (_j = 0, _len1 = emits.length; _j < _len1; _j++) {
                success = emits[_j];
                if (!success) {
                  return _this._deleteTask(task, Promise.resolve, null);
                }
              }
              return _this._deleteTask(task, Promise.resolve, _this);
            });
          }, function(err) {
            throw task.err = err;
          });
        }));
      };
    })(this))["catch"]((function(_this) {
      return function(err) {
        if (task.err == null) {
          _this.log.error(err);
        }
        _this._deleteTask(task);
        throw err;
      };
    })(this));
  };

  LayerController.prototype.findElements = function(node, selectors) {
    var element, elementList, _i, _len, _ref, _ref1;
    if (node == null) {
      node = this.parentNode || ((_ref = this.parentLayer) != null ? _ref.elementList : void 0);
    }
    if (selectors == null) {
      selectors = this.selectors;
    }
    if (!node) {
      throw new Error('findElements: node does not exist');
    }
    if (!selectors) {
      throw new Error('findElements: selectors does not exist');
    }
    if (node.find && node.html) {
      return node.find(selectors);
    }
    if (node.querySelectorAll) {
      return _.toArray(node.querySelectorAll(selectors));
    }
    if (!((_ref1 = node[0]) != null ? _ref1.querySelectorAll : void 0)) {
      throw new Error(this.log.error('findElements: bad node'));
    }
    elementList = [];
    for (_i = 0, _len = node.length; _i < _len; _i++) {
      element = node[_i];
      elementList = elementList.concat(_.toArray(element.querySelectorAll(selectors)));
    }
    return elementList;
  };

  LayerController.prototype.htmlElements = function(elementList, html) {
    if (!elementList) {
      throw new Error('htmlElements: elementList does not exist');
    }
    if (html == null) {
      throw new Error('htmlElements: html does not exist');
    }
    if (elementList.html) {
      return elementList.html(html);
    }
    return Array.prototype.forEach.call(elementList, function(element) {
      return pasteHTML(element, html);
    });
  };

  LayerController.prototype.insert = function(force) {
    var task;
    if (force == null) {
      force = true;
    }
    task = this._task('insert', force);
    if (task.run) {
      return task.run;
    }
    if (!this.selectors) {
      return Promise.reject(new Error(this.log.error('layer.selectors does not exist')));
    }
    return task.run = new Promise((function(_this) {
      return function(resolve, reject) {
        var emits;
        emits = [];
        emits.push(_this.emitAll('insert'));
        if (typeof window !== "undefined" && window !== null) {
          emits.push(_this.emitAll('insert.window'));
        }
        return resolve(Promise.all(emits).then(function(emits) {
          var elementList, success, _i, _len, _ref;
          for (_i = 0, _len = emits.length; _i < _len; _i++) {
            success = emits[_i];
            if (!success) {
              return _this._deleteTask(task, Promise.resolve, null);
            }
          }
          if (!(!force && ((_ref = _this.elementList) != null ? _ref.length : void 0))) {
            _this.elementList = null;
            elementList = _this.findElements();
            if (!(elementList != null ? elementList.length : void 0)) {
              return _this._deleteTask(task, Promise.resolve, null);
            }
            _this.htmlElements(elementList, _this.html);
            _this.elementList = elementList;
          }
          emits = [];
          emits.push(_this.emitAll('domready'));
          if (typeof window !== "undefined" && window !== null) {
            emits.push(_this.emitAll('domready.window'));
          }
          return Promise.all(emits).then(function(emits) {
            var _j, _len1;
            for (_j = 0, _len1 = emits.length; _j < _len1; _j++) {
              success = emits[_j];
              if (!(!success)) {
                continue;
              }
              _this.elementList = null;
              return _this._deleteTask(task, Promise.resolve, null);
            }
            return _this._deleteTask(task, Promise.resolve, _this);
          });
        }));
      };
    })(this))["catch"]((function(_this) {
      return function(err) {
        if (task.err == null) {
          _this.log.error(err);
        }
        _this._deleteTask(task);
        throw err;
      };
    })(this));
  };

  LayerController.prototype._show = function(force) {
    return this.make(force).then((function(_this) {
      return function(layer) {
        if (!layer) {
          return null;
        }
        return _this.insert(force);
      };
    })(this));
  };

  LayerController.prototype.show = function(force) {
    var task, _ref, _ref1;
    if (force == null) {
      force = false;
    }
    task = this._task('show', force);
    if (task.run) {
      return task.run;
    }
    if (this.isShown && ((_ref = this.elementList) != null ? _ref.length : void 0)) {
      return Promise.resolve(this);
    }
    if (!(this.parentNode || (this.parentLayer && this.parentLayer.isShown && ((_ref1 = this.parentLayer.elementList) != null ? _ref1.length : void 0)))) {
      return Promise.resolve(null);
    }
    return task.run = new Promise((function(_this) {
      return function(resolve, reject) {
        var emits;
        emits = [];
        emits.push(_this.emitAll('show'));
        return resolve(Promise.all(emits).then(function(emits) {
          var success, _i, _len;
          for (_i = 0, _len = emits.length; _i < _len; _i++) {
            success = emits[_i];
            if (!success) {
              return _this._deleteTask(task, Promise.resolve, null);
            }
          }
          return _this._show(force).then(function(layer) {
            if (!layer) {
              return _this._deleteTask(task, Promise.resolve, null);
            }
            emits = [];
            emits.push(_this.emitAll('shown'));
            if (typeof window !== "undefined" && window !== null) {
              emits.push(_this.emitAll('shown.window'));
            }
            return Promise.all(emits).then(function(emits) {
              var _j, _len1;
              for (_j = 0, _len1 = emits.length; _j < _len1; _j++) {
                success = emits[_j];
                if (!success) {
                  return _this._deleteTask(task, Promise.resolve, null);
                }
              }
              _this.isShown = true;
              return _this._deleteTask(task, Promise.resolve, _this);
            });
          }, function(err) {
            throw task.err = err;
          });
        }));
      };
    })(this))["catch"]((function(_this) {
      return function(err) {
        if (task.err == null) {
          _this.log.error(err);
        }
        _this._deleteTask(task);
        throw err;
      };
    })(this));
  };

  LayerController.prototype.hideAll = function(force) {
    var task, _ref;
    if (force == null) {
      force = false;
    }
    this.log.debug('hideAll', force);
    task = this._task('hideAll', force);
    if (task.run) {
      return task.run;
    }
    if (!this.isShown && !((_ref = this.elementList) != null ? _ref.length : void 0) && !force) {
      return Promise.resolve(this);
    }
    return task.run = new Promise((function(_this) {
      return function(resolve, reject) {
        var emits;
        emits = [];
        emits.push(_this.emitAll('hide.all'));
        return resolve(Promise.all(emits).then(function(emits) {
          var success, _i, _len;
          for (_i = 0, _len = emits.length; _i < _len; _i++) {
            success = emits[_i];
            if (!success) {
              return _this._deleteTask(task, Promise.resolve, null);
            }
          }
          return Promise.all(_this.childLayers.map(function(layer) {
            return layer.hideAll(force);
          }))["catch"]().then(function() {
            return _this.hide(force).then(function() {
              emits = [];
              emits.push(_this.emitAll('hidden.all'));
              return Promise.all(emits).then(function(emits) {
                var _j, _len1;
                for (_j = 0, _len1 = emits.length; _j < _len1; _j++) {
                  success = emits[_j];
                  if (!success) {
                    return _this._deleteTask(task, Promise.resolve, null);
                  }
                }
                return _this._deleteTask(task, Promise.resolve, _this);
              });
            }, function(err) {
              throw task.err = err;
            });
          });
        }));
      };
    })(this))["catch"]((function(_this) {
      return function(err) {
        if (task.err == null) {
          _this.log.error(err);
        }
        _this._deleteTask(task);
        throw err;
      };
    })(this));
  };

  LayerController.prototype.hide = function(force) {
    var task, _ref;
    if (force == null) {
      force = false;
    }
    this.log.debug('hide', force);
    task = this._task('hide', force);
    if (task.run) {
      return task.run;
    }
    if (!this.isShown && !((_ref = this.elementList) != null ? _ref.length : void 0) && !force) {
      return Promise.resolve(this);
    }
    return task.run = new Promise((function(_this) {
      return function(resolve, reject) {
        var emits;
        emits = [];
        emits.push(_this.emitAll('hide'));
        return resolve(Promise.all(emits).then(function(emits) {
          var success, _i, _len, _ref1;
          for (_i = 0, _len = emits.length; _i < _len; _i++) {
            success = emits[_i];
            if (!success) {
              return _this._deleteTask(task, Promise.resolve, null);
            }
          }
          if (force && !((_ref1 = _this.elementList) != null ? _ref1.length : void 0)) {
            _this.htmlElements(_this.findElements(), '');
          } else {
            _this.htmlElements(_this.elementList, '');
          }
          _this.isShown = false;
          _this.elementList = null;
          emits = [];
          emits.push(_this.emitAll('hidden'));
          if (typeof window !== "undefined" && window !== null) {
            emits.push(_this.emitAll('hidden.window'));
          }
          return Promise.all(emits).then(function(emits) {
            var _j, _len1;
            for (_j = 0, _len1 = emits.length; _j < _len1; _j++) {
              success = emits[_j];
              if (!success) {
                return _this._deleteTask(task, Promise.resolve, null);
              }
            }
            return _this._deleteTask(task, Promise.resolve, _this);
          });
        }));
      };
    })(this))["catch"]((function(_this) {
      return function(err) {
        if (task.err == null) {
          _this.log.error(err);
        }
        _this._deleteTask(task);
        throw err;
      };
    })(this));
  };

  LayerController.prototype.stateAll = function(state) {
    var task;
    if (state == null) {
      state = '';
    }
    task = this._task('stateAll', state);
    if (task.run) {
      return task.run;
    }
    return task.run = new Promise((function(_this) {
      return function(resolve, reject) {
        var emits;
        emits = [];
        emits.push(_this.emitAll('state.all', state));
        return resolve(Promise.all(emits).then(function(emits) {
          var success, _i, _len;
          for (_i = 0, _len = emits.length; _i < _len; _i++) {
            success = emits[_i];
            if (!success) {
              return _this._deleteTask(task, Promise.resolve, null);
            }
          }
          return _this.state(state).then(function() {
            return Promise.all(_this.childLayers.map(function(layer) {
              return layer.stateAll(state);
            }))["catch"]().then(function() {
              emits = [];
              emits.push(_this.emitAll('stated.all', state));
              return Promise.all(emits).then(function(emits) {
                var _j, _len1;
                for (_j = 0, _len1 = emits.length; _j < _len1; _j++) {
                  success = emits[_j];
                  if (!success) {
                    return _this._deleteTask(task, Promise.resolve, null);
                  }
                }
                return _this._deleteTask(task, Promise.resolve, _this);
              });
            });
          }, function(err) {
            throw task.err = err;
          });
        }));
      };
    })(this))["catch"]((function(_this) {
      return function(err) {
        if (task.err == null) {
          _this.log.error(err);
        }
        _this._deleteTask(task);
        throw err;
      };
    })(this));
  };

  LayerController.prototype._state = function(state) {
    if (!this.selectors) {
      return Promise.resolve(this);
    }
    if (!(!this.regState || (state.search(this.regState) !== -1))) {
      return this.hideAll();
    }
    return this.show();
  };

  LayerController.prototype.state = function(state) {
    var pushed, task;
    if (state == null) {
      state = '';
    }
    if (!this.task.state) {
      this.task.state = {
        queue: []
      };
    }
    task = this._afterConflictTask('state', state);
    if (task.run) {
      pushed = task.queue.push(state);
      return task.run.then((function(_this) {
        return function() {
          if (task.queue.length !== pushed) {
            return null;
          }
          task.queue = [];
          return task.run = _this.state(state);
        };
      })(this));
    }
    return task.run = new Promise((function(_this) {
      return function(resolve, reject) {
        var emits;
        _this.task.state.next = state;
        _this.task.state.equal = (_this.task.state.current === _this.task.state.next ? true : false);
        _this.task.state.progress = ((_this.task.state.current != null) && !_this.task.state.equal ? true : false);
        _this.task.state.nofirst = _this.task.state.current != null;
        emits = [];
        emits.push(_this.emitAll('state', state));
        if (typeof window !== "undefined" && window !== null) {
          emits.push(_this.emitAll('state.window', state));
        }
        if (_this.task.state.nofirst) {
          emits.push(_this.emitAll('state.next', state));
        }
        if (_this.task.state.equal) {
          emits.push(_this.emitAll('state.equal', state));
          if (typeof window !== "undefined" && window !== null) {
            emits.push(_this.emitAll('state.equal.window', state));
          }
        } else {
          emits.push(_this.emitAll('state.different', state));
          if (typeof window !== "undefined" && window !== null) {
            emits.push(_this.emitAll('state.different.window', state));
          }
        }
        if (_this.task.state.progress) {
          emits.push(_this.emitAll('state.progress', state));
          if (typeof window !== "undefined" && window !== null) {
            emits.push(_this.emitAll('state.progress.window', state));
          }
        }
        return resolve(Promise.all(emits).then(function(emits) {
          var success, _i, _len;
          for (_i = 0, _len = emits.length; _i < _len; _i++) {
            success = emits[_i];
            if (!success) {
              return _this._deleteTask(task, Promise.resolve, null);
            }
          }
          return _this._state(state).then(function(layer) {
            if (!layer) {
              return _this._deleteTask(task, Promise.resolve, null);
            }
            _this.task.state.last = _this.task.state.current;
            _this.task.state.current = state;
            delete _this.task.state.next;
            emits = [];
            emits.push(_this.emitAll('stated', state));
            if (_this.task.state.nofirst) {
              emits.push(_this.emitAll('stated.next', state));
              if (typeof window !== "undefined" && window !== null) {
                emits.push(_this.emitAll('stated.next.window', state));
              }
            }
            return Promise.all(emits).then(function(emits) {
              var _j, _len1;
              for (_j = 0, _len1 = emits.length; _j < _len1; _j++) {
                success = emits[_j];
                if (!success) {
                  return _this._deleteTask(task, Promise.resolve, null);
                }
              }
              return _this._deleteTask(task, Promise.resolve, _this);
            });
          }, function(err) {
            throw task.err = err;
          });
        }));
      };
    })(this))["catch"]((function(_this) {
      return function(err) {
        if (task.err == null) {
          _this.log.error(err);
        }
        _this._deleteTask(task);
        throw err;
      };
    })(this));
  };

  LayerController.prototype._reset = function(cacheKey) {
    var data, path, _ref;
    delete this.html;
    delete this.elementList;
    delete this.data;
    if (!cacheKey) {
      return true;
    }
    if (!this._data || !this.download) {
      return false;
    }
    if (_.isString(cacheKey)) {
      path = this.render(this.download[cacheKey]);
      if (!path) {
        return false;
      }
      path = this._originPath(path);
      delete this._data[path];
      delete this.request.cache[path];
      return true;
    }
    if (_.isBoolean(cacheKey)) {
      _ref = this._data;
      for (path in _ref) {
        if (!__hasProp.call(_ref, path)) continue;
        data = _ref[path];
        delete this._data[path];
        delete this.request.cache[path];
      }
      return true;
    }
    return false;
  };

  LayerController.prototype.reset = function(cacheKey) {
    var task;
    task = this._task('reset', cacheKey);
    if (task.run) {
      return task.run;
    }
    return task.run = new Promise((function(_this) {
      return function(resolve, reject) {
        return process.nextTick(function() {
          return _this._deleteTask(task, resolve, _this._reset(cacheKey));
        });
      };
    })(this))["catch"]((function(_this) {
      return function(err) {
        if (task.err == null) {
          _this.log.error(err);
        }
        _this._deleteTask(task);
        throw err;
      };
    })(this));
  };

  LayerController.prototype.getFullName = function() {
    if (!this.parentLayer) {
      return this.name;
    }
    return this.parentLayer.getFullName() + '.' + this.name;
  };

  function LayerController(parentLayer) {
    LayerController.__super__.constructor.call(this, {
      wildcard: true
    });
    this.childLayers = [];
    if (parentLayer instanceof LayerController) {
      this.parentLayer = parentLayer;
      this.parentLayer.childLayers.push(this);
      this.main = parentLayer.main;
      this.request = this.main.request;
      this.layers = this.main.layers;
      this.layers.push(this);
      if (!this.name) {
        this.name = "" + this.parentLayer.childLayers.length + "(" + this.layers.length + ")";
      }
    } else {
      this.main = this;
      if (typeof document !== "undefined" && document !== null) {
        this.parentNode = document;
      }
      this.main.request = {};
      if (typeof window !== "undefined" && window !== null) {
        this.main.request.origin = window.location.origin || window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
      }
      this.main.request.agent = superagent;
      this.main.request.loading = {};
      this.main.request.cache = {};
      this.main.layers = [this];
      this.main.name = (parentLayer != null ? parentLayer.name : void 0) || this.main.name || 'main';
    }
    this.log = new Log(this);
    this.task = {};
    this.config = {};
    this.rel = {};
    LayerController.emit("init." + (this.getFullName()), this);
  }

  return LayerController;

})(Module);

LayerController._ = _;

LayerController.Promise = Promise;

LayerController.superagent = superagent;

LayerController.pasteHTML = pasteHTML;

LayerController.Log = Log;

module.exports = LayerController;

LayerController.Module = Module;

LayerController.EventEmitter2 = Module.EventEmitter2;

LayerController.extend(new Module.EventEmitter2({
  wildcard: true
}));


text:
package com.gmail.socraticphoenix.nebula.javasource.ast.annotation;

import java.util.Collection;

public interface JavaSourceAnnotatable<T extends JavaSourceAnnotatable<T>> {

    Collection<JavaSourceAnnotation> annotations();

    T addAnnotation(JavaSourceAnnotation annotation);

    default boolean hasAnnotation(JavaSourceAnnotation annotation) {
        return this.annotations().contains(annotation);
    }

}


text:
dotjs
=====

My ~/.js directory for dotjs!


text:
from distutils.core import setup
import os
from os.path import join

def get_data_files(path):
    total_files = []
    for root, dirs, files in os.walk(path):
        total_files += [join(root, name).split('/',1)[1] for name in files]
    return total_files

setup(name='wtdeploy',
      author = 'Javi Santana',
      author_email = 'jsantana@wtelecom.es',
      description = 'django projects deploy on ubuntu',
      url='https://github.com/wellnesstelecom/wtdeploy',
      version='0.3',
      packages=['wtdeploy', 'wtdeploy.modules'],
      scripts=['machine_gun'],
      requires = ['fabric'],
      package_data={'wtdeploy': ['fabfile.py.template'] + get_data_files('wtdeploy/base_template')}
)


text:
#ifndef PROJECT_VNS_FACTORY_H
#define PROJECT_VNS_FACTORY_H

#include "vns_interface.hpp"
#include "../ext/json.hpp"

#include "neighborhoods/dubins_optimization.hpp"
#include "neighborhoods/insertions.hpp"
#include "neighborhoods/smoothing.hpp"
#include "neighborhoods/shuffling.hpp"

namespace SAOP {

    std::shared_ptr<VariableNeighborhoodSearch> build_from_config(const std::string& json_config);

    std::shared_ptr<VariableNeighborhoodSearch> build_default();

    void check_field_is_present(json json_obj, std::string field);

}

#endif //PROJECT_VNS_FACTORY_H


text:
using MilpManager.Abstraction;

namespace MilpManager.Implementation.Constraints
{
    public class MultipleOfCalculator : IConstraintCalculator
    {
        public IVariable Set(IMilpManager milpManager, ConstraintType type, IVariable leftVariable, IVariable rightVariable)
        {
            IVariable any = milpManager.CreateAnonymous(Domain.AnyInteger);
            leftVariable.Set(ConstraintType.Equal,any.Operation(OperationType.Multiplication, rightVariable));

            return leftVariable;
        }
    }
}


text:
use crate::rune_vm::Rune;
use crate::game_state::GameState;
use crate::minion_card::UID;
use serde::{Serialize, Deserialize};
use hlua;

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct StartGame {}

implement_for_lua!(StartGame, |mut metatable| {});

impl StartGame {
    pub fn new() -> StartGame {
        StartGame {}
    }
}

impl Rune for StartGame {
    fn execute_rune(&self, _game_state: &mut GameState) {}

    fn can_see(&self, _controller: UID, _game_state: &GameState) -> bool {
        return true;
    }

    fn to_json(&self) -> String {
        "{\"runeType\":\"StartGame\"}".to_string()
    }

    fn into_box(&self) -> Box<dyn Rune> {
        Box::new(self.clone())
    }
}


text:
class AddSubdomainToSubscribemAccounts < ActiveRecord::Migration
  def change
    add_column :war_engine_accounts, :subdomain, :string
    add_index :war_engine_accounts, :subdomain
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:icon="@android:drawable/ic_menu_delete" android:id="@id/action_delete" android:title="@string/delete" />
    <item android:id="@id/action_select_all" android:title="@string/select_all" android:showAsAction="ifRoom" />
</menu>


text:
Partial Class news_Default
    Inherits System.Web.UI.Page
    Public cf As New comonfunctions
End Class


text:
// <copyright company="Benjamin Abt ( http://www.benjamin-abt.com - http://quickIO.NET )">
//      Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT
// </copyright>
// <author>Benjamin Abt</author>

using System;
using System.Diagnostics.Contracts;
using System.Text;
using System.Threading;

namespace SchwabenCode.QuickIO
{
    ///
    /// This class is used for hash calculations.
    /// Use <see>
    ///         <cref>Format</cref>
    ///     </see>
    ///     for human readable output.
    ///
    /// <example>
    ///
    /// // Show human readable hash
    /// QuickIOHashResult hashResult = QuickIOFile.CalculateSha256Hash( "C:\temp\image.bin" );
    /// Console.WriteLine("Hash: {0}", hashResult.Format( Encoding.UTF8, "x2" );
    ///
    /// </example>
    public class QuickIOHashResult
    {
        private readonly byte[ ] _hashBytes;

        ///
        /// The bytes that represents the calculation result
        ///
        public byte[ ] HashBytes
        {
            get
            {
                Contract.Ensures( Contract.Result<Byte[ ]>() != null );
                return _hashBytes;
            }
        }

        ///
        /// Creates an instance of <see cref="QuickIOHashResult"/>
        ///
        /// <param name="hashBytes"></param>
        internal QuickIOHashResult( byte[ ] hashBytes )
        {
            Contract.Requires( hashBytes != null );
            _hashBytes = hashBytes;
        }

        ///
        /// Formats the <see cref="HashBytes"/> as a hexadecimal string using UTF8 encoding.
        ///
        /// <returns>Formated string</returns>
        /// <example>
        ///
        /// // Show human readable hash
        /// QuickIOHashResult hashResult = QuickIOFile.CalculateSha256Hash( "C:\temp\image.bin" );
        /// Console.WriteLine("Hash: {0}", hashResult.Format( );
        ///
        /// </example>
        public string Format()
        {
            Contract.Ensures( Contract.Result<string>() != null );
            return Format( Encoding.UTF8 );
        }

        ///
        /// Formats the <see cref="HashBytes"/> as a hexadecimal string using specified encoding.
        ///
        /// <param name="encoding">Encoding for formatting</param>
        /// <returns>Formated string</returns>
        /// <example>
        ///
        /// // Show human readable hash
        /// QuickIOHashResult hashResult = QuickIOFile.CalculateSha256Hash( "C:\temp\image.bin" );
        /// Console.WriteLine("Hash: {0}", hashResult.Format( Encoding.UTF8 );
        ///
        /// </example>
        public string Format( Encoding encoding )
        {
            Contract.Requires( encoding != null );
            Contract.Ensures( Contract.Result<string>() != null );

            return Format( encoding, "x2" );
        }

        ///
        /// Formats the <see cref="HashBytes"/> using specified encoding and format.
        ///
        /// <param name="encoding">Encoding for formatting</param>
        /// <param name="format">Pattern for formatting. Use x2 for hexadecimal output.</param>
        /// <param name="cancellationToken">Cancel token</param>
        /// <returns>Formated string</returns>
        /// <example>
        ///
        /// // Show human readable hash
        /// QuickIOHashResult hashResult = QuickIOFile.CalculateSha256Hash( "C:\temp\image.bin" );
        /// Console.WriteLine("Hash: {0}", hashResult.Format( Encoding.UTF8, "x2" );
        ///
        /// </example>
        public string Format( Encoding encoding, String format, CancellationToken cancellationToken = default( CancellationToken ) )
        {
            Contract.Requires( encoding != null );
            Contract.Requires( !String.IsNullOrWhiteSpace( format ) );
            Contract.Ensures( Contract.Result<string>() != null );

            StringBuilder sb = new StringBuilder();
            foreach (byte t in HashBytes)
            {
                cancellationToken.ThrowIfCancellationRequested();

                sb.Append( t.ToString( format ) );
            }

            return sb.ToString();
        }
    }
}


text: A Very Bad Etsy Site


text:
from collections import MutableMapping
try:
    import simplejson as json
except ImportError:
    import json

import geojson

mapping_base = MutableMapping

GEO_INTERFACE_MARKER = "__geo_interface__"

def is_mapping(obj):
    return isinstance(obj, MutableMapping)

def to_mapping(obj):
    mapping = getattr(obj, GEO_INTERFACE_MARKER, None)

    if mapping is not None:
        return mapping

    if is_mapping(obj):
        return obj

    if isinstance(obj, geojson.GeoJSON):
        return dict(obj)

    return json.loads(json.dumps(obj))


text:
import * as React from 'react';

export interface HelloProps {
    compiler: string;
    framework: string;
}

export const Hello = (props: HelloProps) =>
Hello from {props.compiler} and {props.framework}!


text:
import omit from 'lodash/omit';
import path from 'path';
import fse from 'fs-extra';

const getExports = filePath => {
  const exportMap = require(filePath); // eslint-disable-line
  return Object.assign(exportMap.default || {}, omit(exportMap, 'default'));
};

export const loadResolvers = async dirPath => {
  const files = await fse.readdir(dirPath);
  const map = {};
  await Promise.all(
    files.map(async file => {
      const filePath = path.join(dirPath, file);
      const stat = await fse.stat(filePath);
      const isDirectory = stat && stat.isDirectory();
      if (isDirectory) {
        map[file] = await loadResolvers(filePath);
        return;
      }

      const extension = path.extname(file);
      if (extension !== '.js') {
        return;
      }
      const filename = file.substr(0, file.length - extension.length);
      const exportMap = getExports(filePath);

      if (filename === 'index') {
        Object.assign(map, exportMap);
      } else {
        map[filename] = exportMap;
      }
    }),
  );

  return map;
};

export const resolver = definition => (target, propr, descriptor) => {
  Object.assign(descriptor, {
    enumerable: true,
  });

  Object.assign(descriptor.value, {
    isResolver: true,
    definition,
  });

  return descriptor;
};


text:
"""
agileboards
~~~~~~~~~~~

:copyright: (c) 2013-2014 by Linovia, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""


text:
#include "dummy_protocol.h"

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

//@ import_module symbolic;

struct dummy_args
{
  int attacker;
  struct keypair *keypair;
};

/*@
predicate_family_instance pthread_run_pre(attacker_t)(void *data, any info) =
    exists(dummy_pub) &*& [_]world(dummy_pub, dummy_key_clsfy) &*&
    dummy_args_attacker(data, ?attacker) &*&
    true == bad(attacker) &*&
    principal(attacker, _) &*&
    dummy_args_keypair(data, ?keypair) &*&
    keypair(keypair, attacker, _, ?i, dummy_pub) &*&
    principals_created(_) &*& info == nil;
@*/

void *attacker_t(void* data) //@ : pthread_run_joinable
  //@ requires pthread_run_pre(attacker_t)(data, ?info);
  //@ ensures false;
{
  //@ open pthread_run_pre(attacker_t)(data, info);
  struct dummy_args *args = (void*) data;
  symbolic_attacker(args->attacker, args->keypair);
  return 0;
}

/*@
predicate_family_instance pthread_run_pre(sender_t)(void *data, any info) =
  [_]world(dummy_pub, dummy_key_clsfy) &*& principal(?sender, _) &*&
  info == cons(sender, nil);
predicate_family_instance pthread_run_post(sender_t)(void *data, any info) =
  principal(?sender, _) &*& info == cons(sender, nil);
@*/

void *sender_t(void* data) //@ : pthread_run_joinable
  //@ requires pthread_run_pre(sender_t)(data, ?x);
  //@ ensures pthread_run_post(sender_t)(data, x) &*& result == 0;
{
  //@ open pthread_run_pre(sender_t)(data, x);
  send();
  //@ close pthread_run_post(sender_t)(data, x);
  return 0;
}

/*@
predicate_family_instance pthread_run_pre(receiver_t)(void *data, any info) =
  [_]world(dummy_pub, dummy_key_clsfy) &*& principal(?receiver, _) &*&
  info == cons(receiver, nil);
predicate_family_instance pthread_run_post(receiver_t)(void *data, any info) =
  principal(?receiver, _) &*& info == cons(receiver, nil);
@*/

void *receiver_t(void* data) //@ : pthread_run_joinable
  //@ requires pthread_run_pre(receiver_t)(data, ?x);
  //@ ensures pthread_run_post(receiver_t)(data, x) &*& result == 0;
{
  //@ open pthread_run_pre(receiver_t)(data, x);
  struct item *i = receive();
  item_free(i);
  //@ close pthread_run_post(receiver_t)(data, x);
  return 0;
}

int main() //@ : main_full(main_app)
  //@ requires module(main_app, true);
  //@ ensures  true;
{
  struct keypair *s_keys;
  struct keypair *r_keys;

  printf("\n\tExecuting \"");
  printf("dummy protocol");
  printf("\" ... \n\n");

  //@ open_module();
  //@ PACK_PROOF_OBLIGATIONS(dummy)
  init_crypto_lib();

  int sender = create_principal(&s_keys);
  int receiver = create_principal(&r_keys);
  keypair_free(s_keys);
  keypair_free(r_keys);
  {
    struct keypair *apair;
    pthread_t a_thread;
    int attacker = create_principal(&apair);
    //@ assume (bad(attacker));
    struct dummy_args *args = malloc(sizeof(struct dummy_args));
    if (args == 0) abort();
    args->attacker = attacker;
    args->keypair = apair;
    //@ leak world(dummy_pub, dummy_key_clsfy);
    //@ close pthread_run_pre(attacker_t)(args, _);
    pthread_create(&a_thread, NULL, &attacker_t, args);
  }

  int i = 0;
#ifdef EXECUTE
  while (i++ < 10)
#else
  while (true)
#endif
    /*@ invariant [_]world(dummy_pub, dummy_key_clsfy) &*&
                  principal(sender, _) &*& principal(receiver, _); @*/
  {
    pthread_t s_thread, r_thread;
    {
      //@ close pthread_run_pre(sender_t)(NULL, cons(sender, nil));
      pthread_create(&s_thread, NULL, &sender_t, NULL);
      //@ close pthread_run_pre(receiver_t)(NULL, cons(receiver, nil));
      pthread_create(&r_thread, NULL, &receiver_t, NULL);
    }

    {
      pthread_join(r_thread, NULL);
      //@ open pthread_run_post(receiver_t)(NULL, _);
      pthread_join(s_thread, NULL);
      //@ open pthread_run_post(sender_t)(NULL, _);
    }
  }

  //@ close_module();
  //@ leak module(main_app, _);
  printf("Done\n");
}


text:
@interface FCDAddTeamController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *teamName;
@property (weak, nonatomic) IBOutlet UITextField *teamColor;
@end

@implementation FCDAddTeamController

- (void)viewDidLoad {
    [super viewDidLoad];

    if(_aTeam) {
        [_teamName setText:[_aTeam valueForKey:@"name"]];
        [_teamColor setText:[_aTeam valueForKey:@"color"]];
    }
}

-(IBAction)save:(id)sender {
    if([_delegate respondsToSelector:@selector(saveContext)]) {

        if(!_aTeam) {
            [_delegate addTeamWithParameters:@{@"name":_teamName.text, @"color":_teamColor.text}];
        } else {
            [_delegate saveContext];
        }

        [self.view endEditing:YES];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(IBAction)didChange:(id)sender {
    if(!_aTeam)
        return;

    if([sender isEqual:_teamName]) {
        [_aTeam setValue:[sender text] forKey:@"name"];
    } else {
        [_aTeam setValue:[sender text] forKey:@"color"];
    }
}

@end


text:
<?php

class Tipoaditivo extends AppModel {

        public $actsAs = array('Searchable');

	var $name = 'Tipoaditivo';
	var $displayField = 'title';
	var $validate = array(
		'title' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'Descrição é obrigatória',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
	);

        public $filterArgs = array(
            array('name'=>'title', 'type' => 'like')
	);

	//The Associations below have been created with all possible keys, those that are not needed can be removed

	var $hasMany = array(
		'Aditivo' => array(
			'className' => 'Aditivo',
			'foreignKey' => 'tipoaditivo_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		)
	);

        function afterFind($results, $primary = false) {
            parent::afterFind($results, $primary);

            foreach ($results as $key => $val) {
                if (isset($val['Tipoaditivo']['created'])) {
                    $results[$key]['Tipoaditivo']['created'] = $this->dateFormatAfterFind($val['Tipoaditivo']['created'],true);
                }
                if (isset($val['Tipoaditivo']['modified'])) {
                    $results[$key]['Tipoaditivo']['modified'] = $this->dateFormatAfterFind($val['Tipoaditivo']['modified'],true);
                }
            }
            return $results;
        }
}


text:
class Municipality < Place
  has_many :neighborhoods, foreign_key: :place_id, class_name: 'Place'

  def to_s
    name
  end
end


text:
import React, { PropTypes } from 'react';

const AppStore = require('../stores/AppStore');
const AppActions = require('../actions/AppActions');

class Component extends React.Component {
  constructor(props) {
    super(props);

    this.state = AppStore.getState();

    AppStore.addChangeListener(() => {
      console.log(9, 'app store changed', AppStore.getState());
      // self.setState({ title: 'test' });
      this.setState(AppStore.getState());
    });
  }

  render() {
    return (
State: {this.state.title}
);
  }
}

Component.propTypes = { title: PropTypes.string };
Component.defaultProps = { title: 'Title' };

module.exports = Component;