text:
"""
cli package (imdb package).

This package provides the command line interface for IMDbPY.

Copyright 2017 H. Turgut Uyar <uyar@tekir.org>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""

import sys
from argparse import ArgumentParser

from imdb import VERSION, IMDb

DEFAULT_RESULT_SIZE = 20

def list_results(items, type_, n=None):
    field = 'title' if type_ == 'movie' else 'name'
    print('  # IMDb id %s' % field)
    print('=== ======= %s' % ('=' * len(field),))
    for i, item in enumerate(items[:n]):
        print('%(index)3d %(imdb_id)7s %(title)s' % {
            'index': i + 1,
            'imdb_id': getattr(item, type_ + 'ID'),
            'title': item['long imdb ' + field]
        })

def search_item(args):
    connection = IMDb()
    n = args.n if args.n is not None else DEFAULT_RESULT_SIZE
    if args.type == 'keyword':
        items = connection.search_keyword(args.key)
        if args.first:
            items = connection.get_keyword(items[0])
            list_results(items, type_='movie', n=n)
        else:
            print('  # keyword')
            print('=== =======')
            for i, keyword in enumerate(items[:n]):
                print('%(index)3d %(kw)s' % {'index': i + 1, 'kw': keyword})
    else:
        if args.type == 'movie':
            items = connection.search_movie(args.key)
        elif args.type == 'person':
            items = connection.search_person(args.key)
        elif args.type == 'character':
            items = connection.search_character(args.key)
        elif args.type == 'company':
            items = connection.search_company(args.key)

        if args.first:
            connection.update(items[0])
            print(items[0].summary())
        else:
            list_results(items, type_=args.type, n=args.n)

def get_item(args):
    connection = IMDb()
    if args.type == 'keyword':
        n = args.n if args.n is not None else DEFAULT_RESULT_SIZE
        items = connection.get_keyword(args.key, results=n)
        list_results(items, type_='movie')
    else:
        if args.type == 'movie':
            item = connection.get_movie(args.key)
        elif args.type == 'person':
            item = connection.get_person(args.key)
        elif args.type == 'character':
            item = connection.get_character(args.key)
        elif args.type == 'company':
            item = connection.get_company(args.key)
        print(item.summary())

def list_ranking(items, n=None):
    print('  # rating   votes IMDb id title')
    print('=== ====== ======= ======= =====')
    n = n if n is not None else DEFAULT_RESULT_SIZE
    for i, movie in enumerate(items[:n]):
        print('%(index)3d    %(rating)s %(votes)7s %(imdb_id)7s %(title)s' % {
            'index': i + 1,
            'rating': movie.get('rating'),
            'votes': movie.get('votes'),
            'imdb_id': movie.movieID,
            'title': movie.get('long imdb title')
        })

def get_top_movies(args):
    connection = IMDb()
    items = connection.get_top250_movies()
    if args.first:
        connection.update(items[0])
        print(items[0].summary())
    else:
        list_ranking(items, n=args.n)

def get_bottom_movies(args):
    connection = IMDb()
    items = connection.get_bottom100_movies()
    if args.first:
        connection.update(items[0])
        print(items[0].summary())
    else:
        list_ranking(items, n=args.n)

def make_parser(prog):
    parser = ArgumentParser(prog)
    parser.add_argument('--version', action='version', version='%(prog)s ' + VERSION)

    command_parsers = parser.add_subparsers(metavar='command', dest='command')
    command_parsers.required = True

    command_search_parser = command_parsers.add_parser('search', help='search for items')
    command_search_parser.add_argument('type', help='type of item to search for',
                                       choices=['movie', 'person', 'character', 'company', 'keyword'])
    command_search_parser.add_argument('key', help='title or name of item to search for')
    command_search_parser.add_argument('-n', type=int, help='number of items to list')
    command_search_parser.add_argument('--first', action='store_true', help='display only the first result')
    command_search_parser.set_defaults(func=search_item)

    command_get_parser = command_parsers.add_parser('get', help='retrieve information about an item')
    command_get_parser.add_argument('type', help='type of item to retrieve',
                                    choices=['movie', 'person', 'character', 'company', 'keyword'])
    command_get_parser.add_argument('key', help='IMDb id (or keyword name) of item to retrieve')
    command_get_parser.add_argument('-n', type=int, help='number of movies to list (only for keywords)')
    command_get_parser.set_defaults(func=get_item)

    command_top_parser = command_parsers.add_parser('top', help='get top ranked movies')
    command_top_parser.add_argument('-n', type=int, help='number of movies to list')
    command_top_parser.add_argument('--first', action='store_true', help='display only the first result')
    command_top_parser.set_defaults(func=get_top_movies)

    command_bottom_parser = command_parsers.add_parser('bottom', help='get bottom ranked movies')
    command_bottom_parser.add_argument('-n', type=int, help='number of movies to list')
    command_bottom_parser.add_argument('--first', action='store_true', help='display only the first result')
    command_bottom_parser.set_defaults(func=get_bottom_movies)

    return parser

def main(argv=None):
    argv = argv if argv is not None else sys.argv
    parser = make_parser(prog='imdbpy')
    arguments = parser.parse_args(argv[1:])
    arguments.func(arguments)

if __name__ == '__main__':
    main()


text:
package goryachev.common.util;

public interface HasPrompts
{
	public void updatePrompts();
}

redpajama_set_name: RedPajamaGithub


text:
using content::RenderView;
using blink::WebLocalFrame;
using blink::WebView;

namespace {

RenderView* GetCurrentRenderView() {
  WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext();
  if (!frame)
    return nullptr;

  WebView* view = frame->view();
  if (!view)
    return nullptr;  // can happen during closing.

  return RenderView::FromWebView(view);
}

void Send(mate::Arguments* args,
          const base::string16& channel,
          const base::ListValue& arguments) {
  RenderView* render_view = GetCurrentRenderView();
  if (render_view == nullptr)
    return;

  bool success = render_view->Send(new AtomViewHostMsg_Message(
      render_view->GetRoutingID(), channel, arguments));

  if (!success)
    args->ThrowError("Unable to send AtomViewHostMsg_Message");
}

base::string16 SendSync(mate::Arguments* args,
                        const base::string16& channel,
                        const base::ListValue& arguments) {
  base::string16 json;

  RenderView* render_view = GetCurrentRenderView();
  if (render_view == nullptr)
    return json;

  IPC::SyncMessage* message = new AtomViewHostMsg_Message_Sync(
      render_view->GetRoutingID(), channel, arguments, &json);
  bool success = render_view->Send(message);

  if (!success)
    args->ThrowError("Unable to send AtomViewHostMsg_Message_Sync");

  return json;
}

void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
                v8::Local<v8::Context> context, void* priv) {
  mate::Dictionary dict(context->GetIsolate(), exports);
  dict.SetMethod("send", &Send);
  dict.SetMethod("sendSync", &SendSync);
}

}  // namespace

NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_renderer_ipc, Initialize)


text:
package org.bedework.util.security;

import java.io.Serializable;
import java.security.PrivateKey;

/** Interface for classes which encrypt and decrypt passwords
 *
 * @author Mike Douglass
 */
public interface PwEncryptionIntf extends Serializable {
  /** Bad stored password format */
  public static final String badPwFormat =
      "org.bedework.exception.security.badpwformat";

  /** Call before any other method.
   *
   * @param privKeys
   * @param pubKeys
   * @throws Throwable
   */
  public void init (final String privKeys,
                    final String pubKeys) throws Throwable;

  /** Encrypt the password and return the result.
   *
   * @param val
   * @return String
   * @throws Throwable
   */
  public String encrypt(String val) throws Throwable;

  /** Match the encrypted password - that is, encrypt the plain text and
   * compare.
   *
   * @param plain
   * @param encrypted
   * @return boolean true for a match
   * @throws Throwable
   */
  public boolean match(String plain,
                       String encrypted) throws Throwable;

  /** Decrypt the value
   *
   * @param encrypted
   * @return String plain text.
   * @throws Throwable
   */
  public String decrypt(String encrypted) throws Throwable;

  /**
   * @return the current public key
   * @throws Throwable
   */
  public byte[] getPublicKey() throws Throwable;

  /**
   * @return the current private key
   * @throws Throwable
   */
  public PrivateKey getPrivateKey() throws Throwable;
}


text:
/* @ngInject */
function routes($stateProvider) {
  $stateProvider
    .state('userList', {
      url: '/users',
      views: {
        content: {
          template: '<user-list flex layout="column"/>',
        },
      },
    })
    .state('userDetail', {
      url: '/users/{id:int}',
      back: 'userList',
      views: {
        content: {
          template: '<user-detail flex layout/>',
        },
      },
    });
}

export default routes;


text:
package cronapi.cloud;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dropbox.core.DbxException;
import com.dropbox.core.v2.DbxClientV2;
import com.dropbox.core.v2.files.FileMetadata;
import com.dropbox.core.v2.files.WriteMode;
import com.dropbox.core.v2.sharing.GetSharedLinksResult;
import com.dropbox.core.v2.sharing.SharedLinkMetadata;

public final class DropboxService implements CloudService {

	private static final Logger log = LoggerFactory.getLogger(DropboxService.class);

	private final DbxClientV2 client;

	private final List<FileObject> files;

	DropboxService(DbxClientV2 client, List<FileObject> files) {
		this.client = client;
		this.files = files;
	}

	@Override
	public void upload() {
		if (files == null || files.isEmpty()) {
			log.warn("File content not found to Dropbox upload");
			return;
		}
		files.forEach(fileObject -> {
			try {
				FileMetadata filesX = client.files().uploadBuilder(fileObject.getFileName())
						.withMode(WriteMode.OVERWRITE).uploadAndFinish(fileObject.getFileContent());

				GetSharedLinksResult sharedResult = client.sharing().getSharedLinks(filesX.getPathLower());
				if (sharedResult != null && sharedResult.getLinks() != null && sharedResult.getLinks().size() > 0)
					fileObject.setFileDirectUrl(convertToDirectLink(sharedResult.getLinks().get(0).getUrl()));
				else {
					SharedLinkMetadata shared = client.sharing().createSharedLinkWithSettings(filesX.getPathLower());
					fileObject.setFileDirectUrl(convertToDirectLink(shared.getUrl()));
				}

			} catch (DbxException | IOException e) {
				log.error(e.getMessage());
			}
		});
	}

	private String convertToDirectLink(String url) {
		return url.replace("https://www.dropbox.com/", "https://dl.dropboxusercontent.com/");
	}

	@Override
	public void popule(Object target) {
		this.files.forEach(fileObject -> {
			try {
				String fileName = fileObject.getFileName();
				String[] strings = fileName.split("/");
				if (strings.length > 0) {
					String fieldTarget = strings[2];
					Field declaredField = target.getClass().getDeclaredField(fieldTarget);
					declaredField.setAccessible(true);

					ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
					client.files().downloadBuilder(fileName).download(outputStream);

					declaredField.set(target, outputStream.toByteArray());
				}
			} catch (DbxException | IOException | NoSuchFieldException | IllegalAccessException e) {
				log.error(e.getMessage());
			}
		});
	}

	@Override
	public void delete() {
		this.files.forEach(fileObject -> {
			try {
				client.files().delete(fileObject.getFileName());
			} catch (DbxException e) {
				log.error(e.getMessage());
			}
		});
	}

}


text:
// Custom
#include "Utilities/PatchHelpers.h"
#include "DifferenceFunctions/Patch/GMHDifference.hpp"

// Submodules
#include <Helpers/ParallelSort.h>
#include <Mask/MaskOperations.h>

int main(int argc, char *argv[])
{
  if(argc < 2)
  {
    std::cerr << "Required arguments: fileName.png" << std::endl;
    return EXIT_FAILURE;
  }
//  typedef itk::Image<itk::CovariantVector<int, 3>, 2> ImageType;
  typedef itk::Image<itk::CovariantVector<unsigned char, 3>, 2> ImageType;

  std::string fileName = argv[1];

  typedef itk::Image<itk::CovariantVector<unsigned char, 3>, 2> ImageType;

  typedef std::vector<ImageType::Pointer> PatchesContainerType;
  PatchesContainerType patches =
    PatchHelpers::ReadTopPatchesGrid(fileName, 31, 10, 10);

  itk::Size<2> patchSize = patches[0]->GetLargestPossibleRegion().GetSize();

  std::vector<float> differences;

  unsigned int referencePatchId = 1;

  for(unsigned int i = 0; i < patches.size(); ++i)
  {
    itk::Index<2> dualCorner = {{0,0}};
    itk::Size<2> dualSize = {{patchSize[0]*2, patchSize[1]}};
    itk::ImageRegion<2> dualRegion(dualCorner, dualSize);
    ImageType::Pointer dualImage = ImageType::New();
    dualImage->SetRegions(dualRegion);
    dualImage->Allocate();

    Mask::Pointer mask = Mask::New();
    mask->SetRegions(dualRegion);
    mask->Allocate();
    ITKHelpers::SetImageToConstant(mask.GetPointer(), mask->GetValidValue());

    itk::Index<2> corner1 = {{0,0}};
    itk::ImageRegion<2> region1(corner1, patchSize);

    itk::Index<2> corner2 = {{static_cast<itk::Index<2>::IndexValueType>(patchSize[0]), 0}};
    itk::ImageRegion<2> region2(corner2, patchSize);

    ITKHelpers::CopyRegion(patches[referencePatchId].GetPointer(), dualImage.GetPointer(),
        patches[0]->GetLargestPossibleRegion(), region1);
    ITKHelpers::CopyRegion(patches[i].GetPointer(), dualImage.GetPointer(),
                           patches[0]->GetLargestPossibleRegion(), region2);

    ImageType::Pointer blurredImage = ImageType::New();
    float blurVariance = 1.2f;
    MaskOperations::MaskedBlur(dualImage.GetPointer(), mask, blurVariance, blurredImage.GetPointer());

//    GMHDifference<ImageType> gmhDifference(dualImage.GetPointer(), mask, 30);
    GMHDifference<ImageType> gmhDifference(blurredImage.GetPointer(), mask, 30);
    float difference = gmhDifference.Difference(region1, region2);

    differences.push_back(difference);
//    std::cout << difference << std::endl;
  }

  typedef ParallelSort<float> ParallelSortType;

  ParallelSortType::IndexedVector sortedDifferences =
      ParallelSortType::ParallelSortAscending(differences);

  PatchesContainerType sortedPatches(sortedDifferences.size());

  for(unsigned int i = 0; i < sortedDifferences.size(); ++i)
  {
    sortedPatches[i] = patches[sortedDifferences[i].index];
  }

  PatchHelpers::WriteTopPatchesGrid(sortedPatches,
                           10, 10,
                           "SortedPatches.png");

  return EXIT_SUCCESS;
}


text:
import time
import smbus
import math
from SDL_BM017CS.Adafruit_I2C import Adafruit_I2C

class ColorSensors:
    i2c = None
    mutexe_i2cs = []

    # i2C Addresses

    __ADDR_Mutex0 = 0x70 # register of the first mutex
    __ADDR_Mutex1 = 0x71 # register of the first mutex
    __ADDR_Mutex2 = 0x72 # register of the first mutex
    __CMD_MutexDisable = 0x00 # command to disable all channels
    __CMD_MutexZero = 0x04 # command to enable the first channel

    __SDL_BM017_SensorAddress = 0x29
    __SDL_BM017_EnableAddress = 0xa0  # register address + command bits
    __SDL_BM017_ATimeAddress = 0xa1  # register address + command bits
    __SDL_BM017_ControlAddress = 0xaf  # register address + command bits
    __SDL_BM017_IDAddress = 0xb2  # register address + command bits
    __SDL_BM017_ColorAddress = 0xb4  # register address + command bits
    __SDL_BM017_StatusAddress = 0xb3  # register address + command bits
    __SDL_BM017_ClearInterrupts = 0x66

    # bit definitions
    TCS34725_ENABLE_AIEN = (0x10)  # RGBC Interrupt Enable
    TCS34725_ENABLE_WEN = (0x08)  # Wait enable - Writing 1 activates the wait timer
    TCS34725_ENABLE_AEN = (0x02)  # RGBC Enable - Writing 1 actives the ADC, 0 disables it
    TCS34725_ENABLE_PON = (0x01)  # Power on - Writing 1 activates the internal oscillator, 0 disables it

    # color results
    clear_color = 0
    red_color = 0
    green_color = 0
    blue_color = 0

    __SDL_BM017_IntegrationTime = 0xF6
    __SDL_BM017_Gain = 0x02

    __NUM_SENSORS = 9
    __SENSORS_PER_MUTEX = 3

    active_mutex = None
    debug = False

    def __init__(self, debug=False):
        self.i2c = Adafruit_I2C(self.__SDL_BM017_SensorAddress)
        self.mutexe_i2cs.append(Adafruit_I2C(self.__ADDR_Mutex0))
        self.mutexe_i2cs.append(Adafruit_I2C(self.__ADDR_Mutex1))
        self.mutexe_i2cs.append(Adafruit_I2C(self.__ADDR_Mutex2))

        for i in range(self.__NUM_SENSORS):
            self.clear_active()
            self.set_sensor(i)
            time.sleep(0.100)
            self.i2c.write8(self.__SDL_BM017_ATimeAddress, self.__SDL_BM017_IntegrationTime)
            self.i2c.write8(self.__SDL_BM017_ControlAddress, self.__SDL_BM017_Gain)
            self.i2c.write8(self.__SDL_BM017_EnableAddress, 0x03)
            time.sleep(0.100)

        self.debug = debug

        if (self.debug):
            print("SDL_BM017 initialized")

    def set_sensor(self, sensor):
        if sensor >= self.__NUM_SENSORS:
            print("Tried to set sensor to ", sensor)
            return
        mutex = self.mutexe_i2cs[int(math.floor(sensor / self.__SENSORS_PER_MUTEX))]
        if mutex is not self.active_mutex:
            self.clear_active()

        cmd = self.__CMD_MutexZero + (sensor % self.__SENSORS_PER_MUTEX)
        mutex.write8(0, cmd)
        time.sleep(0.01)
        self.active_mutex = mutex

    def clear_active(self):
        if self.active_mutex is None:
            return
        self.active_mutex.write8(0, self.__CMD_MutexDisable)
        self.active_mutex = None

    def isSDL_BM017There(self):

        device = self.i2c.readU8(self.__SDL_BM017_IDAddress)

        if (device == 0x44):
            if (self.debug):
                print ("SDL_BM017 / TCS34725 is present")
            return 1
        else:
            if (self.debug):
                print ("SDL_BM017 / TCS34725 is NOT present")
            return 0

    def readStatus(self):

        status = self.i2c.readU8(self.__SDL_BM017_StatusAddress)

        if (self.debug):
            print("SDL_BM017 Status=", status)

        return status

    def getColors(self):

        colorList = self.i2c.readList(self.__SDL_BM017_ColorAddress, 8)

        if (self.debug):
            print("ColorList = ", colorList)

        if colorList is -1:
            print("Error reading colors")
            return

        self.clear_color = (colorList[1] << 8) + (colorList[0])
        self.red_color = (colorList[3] << 8) + (colorList[2])
        self.green_color = (colorList[5] << 8) + (colorList[4])
        self.blue_color = (colorList[7] << 8) + (colorList[6])
        colorList = [self.clear_color, self.red_color, self.green_color, self.blue_color]

        if (self.debug):
            print("clear_color= ", self.clear_color)
            print("red_color= ", self.red_color)
            print("green_color= ", self.green_color)
            print("blue_color= ", self.blue_color)

        return colorList

    def setIntegrationTimeAndGain(self, IT, Gain):

        self.i2c.write8(self.__SDL_BM017_ATimeAddress, IT)
        self.i2c.write8(self.__SDL_BM017_ControlAddress, Gain)
        self.i2c.write8(self.__SDL_BM017_EnableAddress, 0x03)
        time.sleep(0.700)

        if (self.debug):
            print("IT set to:", IT)
            print("Gain set to:", Gain)
        __SDL_BM017_IntegrationTime = IT
        __SDL_BM017_Gain = Gain

    def disableDevice(self):

        reg = self.i2c.readU8(self.__SDL_BM017_EnableAddress)

        self.i2c.write8(self.__SDL_BM017_EnableAddress, reg & ~(self.TCS34725_ENABLE_PON | self.TCS34725_ENABLE_AEN));

    # This can be used to trigger the LED.  Connect the INT pin to LEDON pin and connecting the VDD_LED pin to 3.3V
    def setInterrupt(self, state):

        reg = self.i2c.readU8(self.__SDL_BM017_EnableAddress)
        if (state):
            reg |= self.TCS34725_ENABLE_AIEN
            if (self.debug):
                print("Interrupt On")
        else:
            reg &= ~self.TCS34725_ENABLE_AIEN
            if (self.debug):
                print("Interrupt Off")

        self.i2c.write8(self.__SDL_BM017_EnableAddress, reg)

    def clearInterrupt(self):
        self.i2c.write8(0x66, 0x00)

    def setInterruptLimits(self, low, high):

        self.i2c.write8(0x04, low & 0xFF)
        self.i2c.write8(0x05, low >> 8)
        self.i2c.write8(0x06, high & 0xFF)
        self.i2c.write8(0x07, low >> 8)


text:
package rest

import (
	"k8s.io/apimachinery/pkg/runtime"
	genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
)

// RESTExportStrategy is the interface that defines how to export a Kubernetes object
type RESTExportStrategy interface {
	// Export strips fields that can not be set by the user.  If 'exact' is false
	// fields specific to the cluster are also stripped
	Export(ctx genericapirequest.Context, obj runtime.Object, exact bool) error
}


text:
<?php
namespace oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2;

use un\unece\uncefact\data\specification\UnqualifiedDataTypesSchemaModule\_2;

/**
 * @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2
 * @xmlType CodeType
 * @xmlName InspectionMethodCodeType
 * @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\InspectionMethodCodeType
 */
class InspectionMethodCodeType extends _2\CodeType
{
} // end class InspectionMethodCodeType


text:
<?php

declare(strict_types=1);

namespace Sonata\AdminBundle\Action;

use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Admin\Pool;
use Sonata\AdminBundle\Datagrid\DatagridInterface;
use Sonata\AdminBundle\FieldDescription\FieldDescriptionInterface;
use Sonata\AdminBundle\Filter\FilterInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

final class RetrieveAutocompleteItemsAction
{
    /**
     * @var Pool
     */
    private $pool;

    public function __construct(Pool $pool)
    {
        $this->pool = $pool;
    }

    /**
     * Retrieve list of items for autocomplete form field.
     *
     * @throws \RuntimeException
     * @throws AccessDeniedException
     */
    public function __invoke(Request $request): JsonResponse
    {
        $admin = $this->pool->getInstance($request->get('admin_code'));
        $admin->setRequest($request);
        $context = $request->get('_context', '');

        if ('filter' === $context) {
            $admin->checkAccess('list');
        } elseif (!$admin->hasAccess('create') && !$admin->hasAccess('edit')) {
            throw new AccessDeniedException();
        }

        // subject will be empty to avoid unnecessary database requests and keep autocomplete function fast
        $admin->setSubject($admin->getNewInstance());

        if ('filter' === $context) {
            // filter
            $fieldDescription = $this->retrieveFilterFieldDescription($admin, $request->get('field'));
            $filterAutocomplete = $admin->getDatagrid()->getFilter($fieldDescription->getName());

            $property = $filterAutocomplete->getFieldOption('property');
            $callback = $filterAutocomplete->getFieldOption('callback');
            $minimumInputLength = $filterAutocomplete->getFieldOption('minimum_input_length', 3);
            $itemsPerPage = $filterAutocomplete->getFieldOption('items_per_page', 10);
            $reqParamPageNumber = $filterAutocomplete->getFieldOption('req_param_name_page_number', DatagridInterface::PAGE);
            $toStringCallback = $filterAutocomplete->getFieldOption('to_string_callback');
            $targetAdminAccessAction = $filterAutocomplete->getFieldOption('target_admin_access_action', 'list');
            $responseItemCallback = $filterAutocomplete->getFieldOption('response_item_callback');
        } else {
            // create/edit form
            $fieldDescription = $this->retrieveFormFieldDescription($admin, $request->get('field'));
            $formAutocomplete = $admin->getForm()->get($fieldDescription->getName());

            $formAutocompleteConfig = $formAutocomplete->getConfig();
            if ($formAutocompleteConfig->getAttribute('disabled')) {
                throw new AccessDeniedException(
                    'Autocomplete list can`t be retrieved because the form element is disabled or read_only.'
                );
            }

            $property = $formAutocompleteConfig->getAttribute('property');
            $callback = $formAutocompleteConfig->getAttribute('callback');
            $minimumInputLength = $formAutocompleteConfig->getAttribute('minimum_input_length');
            $itemsPerPage = $formAutocompleteConfig->getAttribute('items_per_page');
            $reqParamPageNumber = $formAutocompleteConfig->getAttribute('req_param_name_page_number');
            $toStringCallback = $formAutocompleteConfig->getAttribute('to_string_callback');
            $targetAdminAccessAction = $formAutocompleteConfig->getAttribute('target_admin_access_action');
            $responseItemCallback = $formAutocompleteConfig->getAttribute('response_item_callback');
        }

        $searchText = $request->get('q', '');

        $targetAdmin = $fieldDescription->getAssociationAdmin();

        // check user permission
        $targetAdmin->checkAccess($targetAdminAccessAction);

        if (mb_strlen($searchText, 'UTF-8') < $minimumInputLength) {
            return new JsonResponse(['status' => 'KO', 'message' => 'Too short search string.'], Response::HTTP_FORBIDDEN);
        }

        $targetAdmin->setFilterPersister(null);
        $datagrid = $targetAdmin->getDatagrid();

        if (null !== $callback) {
            if (!\is_callable($callback)) {
                throw new \RuntimeException('Callback does not contain callable function.');
            }

            $callback($targetAdmin, $property, $searchText);
        } else {
            if (\is_array($property)) {
                // multiple properties
                foreach ($property as $prop) {
                    if (!$datagrid->hasFilter($prop)) {
                        throw new \RuntimeException(sprintf(
                            'To retrieve autocomplete items,'
                            .' you should add filter "%s" to "%s" in configureDatagridFilters() method.',
                            $prop,
                            \get_class($targetAdmin)
                        ));
                    }

                    $filter = $datagrid->getFilter($prop);
                    $filter->setCondition(FilterInterface::CONDITION_OR);

                    $datagrid->setValue($filter->getFormName(), null, $searchText);
                }
            } else {
                if (!$datagrid->hasFilter($property)) {
                    throw new \RuntimeException(sprintf(
                        'To retrieve autocomplete items,'
                        .' you should add filter "%s" to "%s" in configureDatagridFilters() method.',
                        $property,
                        \get_class($targetAdmin)
                    ));
                }

                $datagrid->setValue($datagrid->getFilter($property)->getFormName(), null, $searchText);
            }
        }

        $datagrid->setValue(DatagridInterface::PER_PAGE, null, $itemsPerPage);
        $datagrid->setValue(DatagridInterface::PAGE, null, $request->query->get($reqParamPageNumber, '1'));
        $datagrid->buildPager();

        $pager = $datagrid->getPager();

        $items = [];
        $results = $pager->getCurrentPageResults();

        foreach ($results as $model) {
            if (null !== $toStringCallback) {
                if (!\is_callable($toStringCallback)) {
                    throw new \RuntimeException('Option "to_string_callback" does not contain callable function.');
                }

                $label = $toStringCallback($model, $property);
            } else {
                $resultMetadata = $targetAdmin->getObjectMetadata($model);
                $label = $resultMetadata->getTitle();
            }

            $item = [
                'id' => $admin->id($model),
                'label' => $label,
            ];

            if (\is_callable($responseItemCallback)) {
                \call_user_func($responseItemCallback, $admin, $model, $item);
            }

            $items[] = $item;
        }

        return new JsonResponse([
            'status' => 'OK',
            'more' => \count($items) > 0 && !$pager->isLastPage(),
            'items' => $items,
        ]);
    }

    /**
     * Retrieve the filter field description given by field name.
     *
     * @throws \RuntimeException
     */
    private function retrieveFilterFieldDescription(
        AdminInterface $admin,
        string $field
    ): FieldDescriptionInterface {
        if (!$admin->hasFilterFieldDescription($field)) {
            throw new \RuntimeException(sprintf('The field "%s" does not exist.', $field));
        }

        $fieldDescription = $admin->getFilterFieldDescription($field);

        if (null === $fieldDescription->getTargetModel()) {
            throw new \RuntimeException(sprintf('No associated entity with field "%s".', $field));
        }

        return $fieldDescription;
    }

    /**
     * Retrieve the form field description given by field name.
     *
     * @throws \RuntimeException
     */
    private function retrieveFormFieldDescription(
        AdminInterface $admin,
        string $field
    ): FieldDescriptionInterface {
        if (!$admin->hasFormFieldDescription($field)) {
            throw new \RuntimeException(sprintf('The field "%s" does not exist.', $field));
        }

        $fieldDescription = $admin->getFormFieldDescription($field);

        if (null === $fieldDescription->getTargetModel()) {
            throw new \RuntimeException(sprintf('No associated entity with field "%s".', $field));
        }

        return $fieldDescription;
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Map.cs" company="Dormanil">
//   MIT License
//   Copyright (c) 2016 Dormanil
// </copyright>
// <summary>
//   Defines a Map made of Tiles.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Assets.Scripts.Models.World
{
    /// <summary>
    /// Defines a Map made of Tiles.
    /// </summary>
    public class Map
    {
    }
}


text:
package io.graceland.example.simple;

import java.util.concurrent.atomic.AtomicLong;

import org.joda.time.DateTime;

import io.graceland.example.counting.Counter;
import io.graceland.example.counting.CountingMachine;

public class SimpleCountingMachine implements CountingMachine {

    private final AtomicLong count = new AtomicLong();

    @Override
    public void increment() {
        count.incrementAndGet();
    }

    @Override
    public void resetCount() {
        count.set(0);
    }

    @Override
    public Counter getCurrentCount() {
        return new Counter(count.get(), DateTime.now());
    }
}


text:
define(["underscore", "backbone", "views/tab"], function(_, Backbone, TabView) {

    var WindowView = Backbone.View.extend({
        className: "window",

        events: {
            "click .new-tab" : "newTab",
            "mousedown .grip" : "startResize",
            "mousedown .bar" : "mouseDown",
            "mousedown .title" : "mouseDown",
            "mouseup .bar" : "focus",
            "mouseup .terminal" : "focus",
            "click .minimize-button" : "toggleHide",
            "click .maximize-button" : "maximize",
            "click .close-button" : "killTerminal"
        },

        initialize: function() {
            this.tabViews = [];

            this.model.on("change:hidden", this.updateHidden, this);
            this.model.on("change:top", this.updateWindowPosition, this);
            this.model.on("change:left", this.updateWindowPosition, this);
            this.model.on("change:z_index", this.updateWindowIndex, this);
            this.model.on("destroy", this.removeWindow, this);

            _.bindAll(this, "move", "up", "moveResize", "upResize");
        },

        updateWindowPosition: function() {
            this.el.style.top = this.model.get("top") + "px";
            this.el.style.left = this.model.get("left") + "px";
        },

        updateWindowIndex: function() {
            this.el.style.zIndex = this.model.get("z_index");
        },

        toggleHide : function() {
            this.model.save("hidden", !this.model.get("hidden"));
        },

        updateHidden: function() {
            if (this.model.get("hidden")) {
                this.iconElement.style.display = "inline-block";
                this.el.style.display = "none";
            } else {
                this.iconElement.style.display = "none";
                this.el.style.display = "block";
            }
        },

        tabRemoved: function(model) {
            // TODO: perhaps move this to the model
            var window_id = this.model.id;
            var windowTerminals = app.terminals.filter(function(terminal) { return terminal.get("window_id") == window_id && terminal != model});
            if (windowTerminals.length == 0) {
                this.model.destroy();
            }
        },

        newTab : function(ev) {
            if (ev.ctrlKey || ev.altKey || ev.metaKey || ev.shiftKey) {
                this.focused.model.destroy();
            } else {
                app.terminals.create({
                    connection_id : this.focused.model.get("connection_id"),
                    window_id : this.focused.model.get("window_id")
                });
            }
            return cancel(ev);
        },

        startResize : function(ev) {
            this.focus();
            this.resizing(ev);
            return cancel(ev);
        },

        mouseDown : function(ev) {
            this.focus();

            cancel(ev);

            if (new Date - this.last < 600) {
                return this.maximize();
            }
            this.last = new Date;

            this.drag(ev);

            return cancel(ev);
        },

        render : function () {
            var grip = document.createElement("div");
            grip.className = "grip";

            var bar = document.createElement("div");
            bar.className = "bar";

            // TODO: implement tabs proplery (use a separate bar, use full text, manage in window, listen on event
            // TODO: if content has changed from window)
            // var button = document.createElement("i");
            // button.className = "tab new-tab glyphicon glyphicon-plus-sign";
            // button.title = "New tab";

            // TODO: create a window template
            this.closeButton = document.createElement("i");
            this.minimizeButton = document.createElement("i");
            this.maximizeButton = document.createElement("i");

            this.closeButton.className = "tab close-button glyphicon glyphicon-remove-sign";
            this.minimizeButton.className = "tab minimize-button glyphicon glyphicon-minus-sign";
            this.maximizeButton.className = "tab maximize-button glyphicon glyphicon-plus-sign";

            var title = document.createElement("div");
            title.className = "title";
            title.innerHTML = "";

            this.grip = grip;
            this.bar = bar;
            // this.button = button;
            this.title = title;

            this.tabs = [];
            this.focused = null;

            this.iconImage = document.createElement("img");
            this.iconImage.src = "/static/img/logo.png";

            // TODO: bind text content to terminal
            this.iconText = document.createElement("div");
            this.iconText.textContent = "";

            this.iconElement = document.createElement("div");
            this.iconElement.className = "window-icon";
            this.iconElement.appendChild(this.iconImage);
            this.iconElement.appendChild(this.iconText);

            // TODO: move this view logic to the app
            app.windowIcons.appendChild(this.iconElement);
            this.iconElement.addEventListener("dblclick", _.bind(this.toggleHide, this));

            this.el.appendChild(grip);
            this.el.appendChild(bar);
            bar.appendChild(title);

            bar.appendChild(this.closeButton);
            bar.appendChild(this.minimizeButton);
            bar.appendChild(this.maximizeButton);

            // bar.appendChild(button);
            this.updateHidden();
            this.updateWindowPosition();

            return this.el;
        },

        focus : function () {
            var topmostWindow = this.model;

            app.windows.each(function(win) {
                if (win.get("z_index") > topmostWindow.get("z_index")) {
                    topmostWindow = win;
                }
            });

            if (topmostWindow != this.model) {
                this.model.save("z_index", topmostWindow.get("z_index") + 1);
            }

            // Focus Foreground Tab
            this.focused.focus();
        },

        destroy : function () {
            if (this.destroyed) return;
            this.destroyed = true;

            if (this.m) this.minimize();

            // delete this.tty.windows[this.id];

            this.el.parentNode.removeChild(this.el);

            this.each(function (term) {
                term.destroy();
            });
        },

        move : function(ev) {
            var el = this.el;
            var drag = this.currentDrag;

            var newX = (drag.left + ev.pageX - drag.pageX);
            var newY = (drag.top + ev.pageY - drag.pageY);

            if (newX < 0) newX = 0;
            if (newY < 50) newY = 50;

            el.style.left = newX + "px";
            el.style.top = newY + "px";
        },

        up : function() {

            this.el.style.opacity = "";
            this.el.style.cursor = "";
            this.title.style.cursor = "";
            this.bar.style.cursor = "";

            off(window, "mousemove", this.move);
            off(window, "mouseup", this.up);

            this.model.save({
                left: this.el.offsetLeft,
                top: this.el.offsetTop
            })
        },

        drag : function (ev) {

            this.currentDrag = {
                left: this.el.offsetLeft,
                top: this.el.offsetTop,
                pageX: ev.pageX,
                pageY: ev.pageY
            };

            if (this.m) return;

            this.el.style.opacity = "0.60";
            this.title.style.cursor = "move";
            this.bar.style.cursor = "move";
            //document.body.style.cursor = "move";

            // TODO: backbone-ify
            on(window, "mousemove", this.move);
            on(window, "mouseup", this.up);
        },

        resizing : function (ev) {
            if (this.m) delete this.m;

            this.resizeInitialSize = {
                w: this.el.clientWidth,
                h: this.el.clientHeight
            };

            // TODO: use class instead of styles
            this.el.style.overflow = "hidden";
            this.el.style.opacity = "0.70";

            document.body.style.cursor = "se-resize";

            on(document, "mousemove", this.moveResize);
            on(document, "mouseup", this.upResize);
        },

        moveResize : function(ev) {
            var x = ev.pageX - this.el.offsetLeft;
            var y = ev.pageY - this.el.offsetTop;
            this.el.style.width = x + "px";
            this.el.style.height = y + "px";
        },

        upResize : function(ev) {
            var x, y;

            x = this.el.clientWidth / this.resizeInitialSize.w;
            y = this.el.clientHeight / this.resizeInitialSize.h;
            x = (x * this.focused.cols) | 0;
            y = (y * this.focused.rows) | 0;

            this.resize(x, y);

            this.el.style.width = "";
            this.el.style.height = "";

            // TODO: use class instead of styles
            this.el.style.overflow = "";
            this.el.style.opacity = "";

            document.body.style.cursor = "";
            this.focused.el.style.height = "";

            off(document, "mousemove", this.moveResize);
            off(document, "mouseup", this.upResize);
        },

        maximize : function () {
            if (this.m) return this.minimize();

            this.m = {
                cols: this.focused.cols,
                rows: this.focused.rows,
                left: this.el.offsetLeft,
                top: this.el.offsetTop,
                root: document.body.className
            };

            window.scrollTo(0, 0);

            var root = document.body;

            var x = root.clientWidth / this.focused.el.offsetWidth;
            var y = (root.clientHeight - 50) / this.focused.el.offsetHeight;
            x = (x * this.focused.cols) | 0;
            y = (y * this.focused.rows) | 0;

            this.el.style.left = "0px";
            this.el.style.top = "50px";
            this.el.style.width = "100%";
            this.el.style.height = "100%";
            this.el.style.borderRadius = "0";
            this.focused.el.style.width = "100%";
            this.focused.el.style.height = "100%";
            this.el.style.boxSizing = "border-box";
            this.grip.style.display = "none";
            root.className = "maximized";

            this.resize(x, y);

            this.trigger("maximize");
        },

        minimize : function () {
            this.el.style.left = this.m.left + "px";
            this.el.style.top = this.m.top + "px";
            this.el.style.width = "";
            this.el.style.height = "";
            this.el.style.borderRadius = "5px";
            this.focused.el.style.width = "";
            this.focused.el.style.height = "";
            this.el.style.boxSizing = "";
            this.grip.style.display = "";
            document.body.className = this.m.root;

            this.resize(this.m.cols, this.m.rows);

            this.trigger("minimize");

            delete this.m;
        },

        resize : function (cols, rows) {
            this.model.save({
                cols: cols,
                rows: rows
            });

              this.trigger("resize", cols, rows);
        },

        killTerminal : function() {
            this.focused.model.destroy();
        },

        each : function (func) {
            var i = this.tabs.length;
            while (i--) {
                func(this.tabs[i], i);
            }
        },

        createTab : function (model) {
            var tabView = new TabView({
                model: model,
                window: this
            });

            tabView.render();
            model.on("destroy", this.tabRemoved, this);

            this.tabViews.push(tabView);

            this.focus();
        },

        focusTab : function (next) {
            var tabViews = this.tabViews
                , i = indexOf(tabViews, this.focused)
                , l = tabViews.length;

            if (!next) {
                if (tabViews[--i]) return tabViews[i].focus();
                if (tabViews[--l]) return tabViews[l].focus();
            } else {
                if (tabViews[++i]) return tabViews[i].focus();
                if (tabViews[0]) return tabViews[0].focus();
            }

            return this.focused && this.focused.focus();
        },

        nextTab : function () {
            return this.focusTab(true);
        },

        previousTab : function () {
            return this.focusTab(false);
        },

        removeWindow : function() {
            app.windowIcons.removeChild(this.iconElement);
            this.remove();
        }

    });

    return WindowView;
});


text:
package org.apache.flink.runtime.iterative.concurrent;

import org.apache.flink.runtime.event.TaskEvent;
import org.apache.flink.runtime.iterative.event.AllWorkersDoneEvent;
import org.apache.flink.runtime.iterative.event.TerminationEvent;

import org.junit.Test;

import java.util.Random;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/** Tests for {@link SuperstepBarrier}. */
public class SuperstepBarrierTest {

    @Test
    public void syncAllWorkersDone() throws InterruptedException {
        for (int n = 0; n < 20; n++) {
            sync(new AllWorkersDoneEvent());
        }
    }

    @Test
    public void syncTermination() throws InterruptedException {
        for (int n = 0; n < 20; n++) {
            sync(new TerminationEvent());
        }
    }

    private void sync(TaskEvent event) throws InterruptedException {

        TerminationSignaled terminationSignaled = new TerminationSignaled();

        SuperstepBarrier barrier = new SuperstepBarrier(getClass().getClassLoader());
        barrier.setup();

        Thread headThread = new Thread(new IterationHead(barrier, terminationSignaled));
        Thread syncThread = new Thread(new IterationSync(barrier, event));

        headThread.start();
        syncThread.start();

        headThread.join();
        syncThread.join();

        if (event instanceof TerminationEvent) {
            assertTrue(terminationSignaled.isTerminationSignaled());
        } else {
            assertFalse(terminationSignaled.isTerminationSignaled());
        }
    }

    class IterationHead implements Runnable {

        private final SuperstepBarrier barrier;

        private final TerminationSignaled terminationSignaled;

        private final Random random;

        IterationHead(SuperstepBarrier barrier, TerminationSignaled terminationSignaled) {
            this.barrier = barrier;
            this.terminationSignaled = terminationSignaled;
            random = new Random();
        }

        @Override
        public void run() {
            try {
                Thread.sleep(random.nextInt(10));

                barrier.waitForOtherWorkers();

                if (barrier.terminationSignaled()) {
                    terminationSignaled.setTerminationSignaled();
                }

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    class IterationSync implements Runnable {

        private final SuperstepBarrier barrier;

        private final TaskEvent event;

        private final Random random;

        IterationSync(SuperstepBarrier barrier, TaskEvent event) {
            this.barrier = barrier;
            this.event = event;
            random = new Random();
        }

        @Override
        public void run() {
            try {
                Thread.sleep(random.nextInt(10));

                barrier.onEvent(event);

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    class TerminationSignaled {

        private volatile boolean terminationSignaled;

        public boolean isTerminationSignaled() {
            return terminationSignaled;
        }

        public void setTerminationSignaled() {
            terminationSignaled = true;
        }
    }
}


text:
/* global CustomEvent */
import { assign, mutateSet, run, queryEach } from './common.js'
import $ from './proxy-node.js'

/* const watched = Object.create(null)
const watch = (name, opts) => {
  if (opts == null) throw new TypeError(`attr.watch: useless watcher opts == null`)
  watched[name] = opts = Object.assign(Object.create(null), opts)
}
watch.update = (name, el, value = el.getAttribute(name)) => {}
*/

const Initiated = new Map()
const beenInitiated = (name, el) => Initiated.has(name) && Initiated.get(name)(el)

export const attributeObserver = (el, name, opts) => {
  el = $(el)
  let { init, update, remove } = opts
  if (!init && !update && opts instanceof Function) {
    [init, update] = [opts, opts]
  }
  const intialize = (present, value) => {
    if (present && !beenInitiated(name, el)) {
      if (init) init(el, value)
      if (!Initiated.has(name)) {
        Initiated.set(name, mutateSet(new WeakSet()))
      }
      Initiated.get(name)(el, true)
      return true
    }
    return beenInitiated(name, el)
  }
  let removedBefore = false
  let old = el.attr[name]
  intialize(el.attr.has(name), old)
  const stop = el.on.attr(({ name: attrName, value, oldvalue, present }) => {
    if (
      attrName === name &&
      old !== value &&
      value !== oldvalue &&
      intialize(present, value)
    ) {
      if (present) {
        if (update) update(el, value, old)
        removedBefore = false
      } else if (!removedBefore) {
        if (remove) remove(el, value, old)
        removedBefore = true
      }
      old = value
    }
  })

  const manager = () => {
    stop()
    if (Initiated.has(name)) Initiated.get(name)(el, false)
  }
  manager.start = () => {
    stop.on()
    Initiated.get(name)(el, true)
  }
  return (manager.stop = manager)
}

export const directives = new Map()
export const directive = (name, opts) => {
  const directive = new Map()
  directive.init = el => {
    if (!beenInitiated(name, el)) {
      directive.set(el, attributeObserver(el, name, opts))
    }
  }
  directive.stop = el => {
    if (directive.has(el)) directive.get(el)()
  }
  directives.set(name, directive)
  run(() => queryEach('[' + name + ']', n => attributeChange(n, name)))
  return directive
}

export const attributeChange = (
  el,
  name,
  oldvalue,
  value = el.getAttribute(name),
  present = el.hasAttribute(name)
) => {
  if (directives.has(name)) directives.get(name).init($(el))
  if (value !== oldvalue) {
    el.dispatchEvent(assign(new CustomEvent('attr'), {
      name,
      value,
      oldvalue,
      present
    }))
  }
}


text:
/*
	commonatlases is a package full of `atlas.Entry` definions for common
	types in the standard library.

	A frequently useful example is the standard library `time.Time` type,
	which is frequently serialized in some custom way: as a unix int for
	example, or perhaps an RFC3339 string; there are many popular choices.
	(`time.Time` is also an example of where *some* custom behavior is
	pretty much required, because a default struct-mapping is useless on
	a struct with no exported fields.)
*/
package commonatlases


text:
/**
* This class draws the stop icon that is displayed
* when there are no search results.
*/
function StopIcon(color) {
	this.hite = window.innerHeight / 7;

	this.centerIcon = (window.innerHeight - this.hite) / 2;
	this.color = color;
	this.iconDiv = document.createElement('div');
	this.iconDiv.setAttribute('style', 'text-align: center;');
	this.iconCanvas = null;
	Object.seal(this);
}
StopIcon.prototype.showIcon = function() {
	if (this.iconCanvas === null) {
		this.iconCanvas = this.drawIcon();
	}
	document.body.appendChild(this.iconDiv);
	this.iconDiv.appendChild(this.iconCanvas);

	TweenMax.set(this.iconCanvas, { y: - this.hite });
	TweenMax.to(this.iconCanvas, 0.5, { y: this.centerIcon });
};
StopIcon.prototype.hideIcon = function() {
	if (this.iconDiv && this.iconCanvas && this.iconDiv.hasChildNodes()) {
		this.iconDiv.removeChild(this.iconCanvas);
	}
	if (this.iconDiv && this.iconDiv.parentNode === document.body) {
		document.body.removeChild(this.iconDiv);
	}
};
StopIcon.prototype.drawIcon = function() {
	var lineThick = this.hite / 7.0;
	var radius = (this.hite / 2) - lineThick;
	var coordX = radius + lineThick;
	var coordY = radius + lineThick;
	var edgeX = coordX - radius / 1.5;
	var edgeY = coordY - radius / 1.5;

	var canvas = document.createElement('canvas');
	canvas.setAttribute('height', this.hite);
	canvas.setAttribute('width', this.hite);
	var graphics = canvas.getContext('2d');

	graphics.beginPath();
	graphics.arc(coordX, coordY, radius, 0, Math.PI*2, true);
	graphics.moveTo(edgeX, edgeY);
	graphics.lineTo(edgeX + radius * 1.5, edgeY + radius * 1.5);
	graphics.closePath();

	graphics.lineWidth = lineThick;
	graphics.strokeStyle = this.color;
	graphics.stroke();
	return(canvas);
};

// stop = new StopIcon(200, '#FF0000');
//stop.showIcon();


text:
ALTER TABLE `team` CHANGE `startTime` `startTime` DATETIME NULL DEFAULT NULL;
ALTER TABLE `team` CHANGE `cached_contestants` `cached_contestants` VARCHAR(300) CHARACTER SET utf8 COLLATE utf8_general_ci NULL;
ALTER TABLE `team` CHANGE `nbContestants` `nbContestants` TINYINT(1) NULL;
ALTER TABLE `team` CHANGE `iVersion` `iVersion` INT(11) NULL;
ALTER TABLE `contestant` CHANGE `grade` `grade` INT(11) NULL;
ALTER TABLE `contestant` CHANGE `firstName` `firstName` VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL;
ALTER TABLE `contestant` CHANGE `lastName` `lastName` VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL;
ALTER TABLE `contestant` CHANGE `studentID` `studentID` VARCHAR(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL;
ALTER TABLE `contestant` CHANGE `cached_schoolID` `cached_schoolID` BIGINT(20) NULL;
ALTER TABLE `contestant` CHANGE `iVersion` `iVersion` INT(11) NULL;


text:
___
🚧 DEPRECATED - This repository is deprecated in favor of [mqr](https://github.com/lgraubner/mqr) and will not be updated anymore. Use at your own risk.
___

# StateManager

[![Travis](https://img.shields.io/travis/lgraubner/state-manager.svg)](https://travis-ci.org/lgraubner/state-manager) [![David Dev](https://img.shields.io/david/dev/lgraubner/state-manager.svg)](https://david-dm.org/lgraubner/state-manager#info=devDependencies) [![npm](https://img.shields.io/npm/v/responsive-state-manager.svg)](https://www.npmjs.com/package/responsive-state-manager)

> Javascript handling for mediaquery breakpoints.

This small library is a wrapper for `matchMedia` and `matchMedia.listen` to easily deal with Media Queries in Javascript.

## Dependencies

None.

## Supported Browsers

StateManager relies on `window.matchMedia` for Media Query checks which is supported by the following browsers:

* Chrome 10+
* Firefox 6+
* Safari 5.1+
* IE 10+

To support legacy browsers a [polyfill](https://github.com/paulirish/matchMedia.js) is required.

## Installation

Install it via npm or download the source directly.

```Bash
npm install responsive-state-manager --save
```

**Classic**

Include `StateManager.min.js` before the closing `body` tag.

```HTML
<script src="node_modules/responsive-state-manager/dist/StateManager.min.js"></script>
```

**CommonJS**

```JavaScript
var StateManager = require("responsive-state-manager");
```

## Usage

Initialize it:

```JavaScript
var sm = new StateManager();
```

### `.register()`

Registers a listener for a Media Query. The callback function is triggered every time the breakpoint is passed and the state changes. Additionally the callback is triggered when the Listener gets registered. The suplied argument is `true` or `false` depending on whether the Media Query matches.
It returns a reference to the Listener Object.

```JavaScript
var handler = sm.register("screen and (max-width: 768px)", function (matches) {
    // fires on register and every time the state changes
    if (matches) {
        // Media Query matches
    } else {
        // Media Query doesn't match
    }
});
```

### `.deregister()`

Deregisters an attached listener. Accepts a reference to a listener Object.

```JavaScript
sm.deregister(handler);
```

### `.matches()`

You can also check directly if a media query matches.

```JavaScript
var mobile = sm.matches("screen and (max-width: 768px)"); // does not attach listener

console.log(mobile); // true/false
```


text:
<?php
    namespace Nature;
    define('VERSION', '0.1.0');
    define('VERSION_NAME', 'WestLake');
    /**
     * nature library 核心类
     */
    require_once __DIR__.'/nature.function.php';
    class App {
        static $configure=[];
        function __construct($app_dir=null) {
            if (is_null($app_dir)) {
                $app_dir = realpath(__DIR__.'/../');
            }
            define('APP_DIR', $app_dir);
            set_include_path(get_include_path().':'.__DIR__);
            $this->load_config();
            spl_autoload_register([$this, 'autoloader']);
            set_exception_handler([$this, 'exception_handler']);
            $this->power();
        }
        function autoloader($className) {
            $className = trim($className, "\\");
            $file = APP_DIR
                    .DIRECTORY_SEPARATOR
                    .str_replace("\\", DIRECTORY_SEPARATOR, $className)
                    .'.class.php';
            $globalFile = APP_DIR.DIRECTORY_SEPARATOR.'Global'
                            .DIRECTORY_SEPARATOR.$className.'.class.php';
            $files = [$file, $globalFile];
            foreach($files as $file){
                if(file_exists($file)){
                    require($file);
                    break;
                }
            }
        }
        function run() {
            $this->call_controller();
            $this->call_function();
        }
        function exception_handler($exception){
            if(!is_a($exception, 'Nature\HTTPException')) {
                http_response_code(500);
                $tpl = singleton('tpl');
                $tpl->assign('exception', $exception);
                $tpl->assign('msg', $exception->getMessage());
                $tpl->display('500.html');
            }
        }
        function parse_config($configure, &$position){
            if(!is_array($configure)) {
                return null;
            }
            foreach($configure as $key=>$value){
                $pointer = &$position;
                $keys = explode('.', $key);
                $key = array_pop($keys);
                foreach($keys as $item){
                    $pointer = &$pointer[$item];
                }
                if(is_array($value)) {
                    self::parse_config($value, $pointer[$key]);
                } else {
                    $pointer[$key] = $value;
                }
            }
        }
        function load_config(){
            self::parse_config(require(__DIR__.'/configure.php'), self::$configure);
            if(file_exists(APP_DIR.'/configure.php')) {
                self::parse_config(include(APP_DIR.'/configure.php'), self::$configure);
            }
            return self::$configure;
        }
        function rest($object=null){
            $method = strtolower($_SERVER['REQUEST_METHOD']);
            $types = array(
                'post'=>$_POST,
                'get'=>$_GET,
                'delete'=>$_REQUEST,
                'put'=>$_REQUEST
            );
            $params = $types[$method];
            if(!is_null($object)) {
                $method = [$object, $method];
            }
            if(is_callable($method)){
                $returnData = call_user_func($method, $params);

                switch (gettype($returnData)) {
                    case 'array':
                        echo json_encode($returnData);
                        break;
                    case 'string':
                    case 'integer':
                    case 'float':
                    case 'double':
                        echo $returnData;
                        break;
                }

            }
        }
        /**
         * alias of rest
         */
        function call_function(){
            $this->rest();
        }
        function call_controller() {
            foreach (get_declared_classes() as $class) {
                $reflection = new \ReflectionClass($class);
                if($reflection->isSubclassOf('Nature\\Controller') && !$reflection->isAbstract()) {
                    $obj = $reflection->newInstance();
                    $this->rest($obj);
                }
            }
        }
        function power(){
	        if (configure('x-powered-by')) {
		       header('X-Powered-By: Nature/'.VERSION.' ('.VERSION_NAME.')');
	        }
        }
    }


text:
require "test_helper"

class WithTranslationsTest < ActiveSupport::TestCase
  setup do
    role = build(:ministerial_role)
    with_locale(:en) do
      role.name = "Minister of fun"
    end
    with_locale(:fr) do
      role.name = "Ministre de l'amusement"
    end
    role.save!
  end

  test "with_translations with no arguments returns each item once only" do
    assert_equal 1, Role.with_translations.count
  end

  test "with_translations with no arguments preloads all the translations on each item" do
    loaded_role = Role.with_translations.first

    query_count = count_queries { loaded_role.name }
    assert_equal 0, query_count
  end
end


text:
var ApiCache = new Mongo.Collection('eveonlinejs_apicache')

/**
 * Cache in Meteor integrated MongoDB
 *
 * @exports MongoCache as eveonlinejs.cache.MongoCache
 * @constructor
 */
function MongoCache() {
}

MongoCache.prototype = Object.create(eveonlinejs.cache.Cache.prototype)

/**
 * Store value in cache.
 *
 * @param {String}   key      Cache key
 * @param {String}   value    Cache Value
 * @param {Number}   duration Number of seconds this cache entry will live
 * @param {Function} cb       Callback
 */
MongoCache.prototype.write = Meteor.bindEnvironment(function (key, value, duration, cb) {
    var expireTime = (new Date()).getTime() + duration

    ApiCache.findAndModify({
        query: {
            key: key
        },
        update: {
            value: value,
            key: key,
            expire: new Date(expireTime)
        },
        upsert: true,
        new: true
    })

    cb(null)
})

/**
 * Retrieve value from cache.
 *
 * @param  {String}   key Cache key
 * @param  {Function} cb  Callback
 * @return {String}       Cache value
 */
MongoCache.prototype.read = Meteor.bindEnvironment(function (key, cb) {
    var res = ApiCache.findOne({
        key: key,
        expire: {$gt: new Date()}
    })

    cb(null, res && res.value)
})

/**
 * cleanup old data from cache
 */
MongoCache.cleanup = function () {
    return ApiCache.remove({
        expire: {$lt: new Date()}
    })
}

// export
eveonlinejs.cache.MongoCache = MongoCache

// and set default
eveonlinejs.setCache(new eveonlinejs.cache.MongoCache())


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Rain - incertae sedis</title>
    <meta name="description" content="" />

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

    <link rel="shortcut icon" href="https://evolgenomology.github.io/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//evolgenomology.github.io/themes/ichi/assets/css/normalize.css?v=1475050879839" />
    <link rel="stylesheet" type="text/css" href="//evolgenomology.github.io/themes/ichi/assets/css/foundation.min.css?v=1475050879839" />

    <link rel="stylesheet" type="text/css" href="//evolgenomology.github.io/themes/ichi/assets/fonts/foundation-icons/foundation-icons.css?v=1475050879839" />
    <link rel="stylesheet" type="text/css" href="//evolgenomology.github.io/themes/ichi/assets/css/styles.css?v=1475050879839" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Open+Sans:300,700,400|Source+Sans+Pro:300,400,600,700,900,300italic,400italic,600italic,700italic,900italic" />

    <link rel="canonical" href="https://evolgenomology.github.io/https://evolgenomology.github.io/tag/Rain/" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="incertae sedis" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Rain - incertae sedis" />
    <meta property="og:url" content="https://evolgenomology.github.io/https://evolgenomology.github.io/tag/Rain/" />
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Rain - incertae sedis" />
    <meta name="twitter:url" content="https://evolgenomology.github.io/https://evolgenomology.github.io/tag/Rain/" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="incertae sedis" href="https://evolgenomology.github.io/rss/" />

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

    <button type="button" class="overlay-close">Close</button>

Home

incertae sedis

musing on science and evolution ...
oh, and other important stuff, like Rugby for example.

Rain

            <time datetime="2016-07-12">12 Jul 2016</time>

Happy Birthday Marike

My little sister has a birthday today and I am very proud of her. So, I am sending her all the best from London, with a good coffee cheers and, well, some rain of course. In Germany we’d say: "er sieht aus wie ein begossener Pudel".…

        Read more
        Posted on Birthday,  Sister,  Greetings,  London,  Rain

    Page 1 of 1


text:
class AddRequireRegistrationToEvents < ActiveRecord::Migration
  def change
    add_column :events, :require_registration, :boolean
  end
end


text:
"""Test cases for Zinnia's markups"""
import builtins
import warnings

from django.test import TestCase

from zinnia import markups
from zinnia.markups import html_format
from zinnia.markups import markdown
from zinnia.markups import restructuredtext
from zinnia.markups import textile
from zinnia.tests.utils import skip_if_lib_not_available

class MarkupsTestCase(TestCase):
    text = 'Hello *World* !'

    @skip_if_lib_not_available('textile')
    def test_textile(self):
        self.assertHTMLEqual(
            textile(self.text).strip(),
            '
Hello World !
'
        )

    @skip_if_lib_not_available('markdown')
    def test_markdown(self):
        self.assertHTMLEqual(
            markdown(self.text).strip(),
            '
Hello World !
'
        )

    @skip_if_lib_not_available('markdown')
    def test_markdown_extensions(self):
        text = '[TOC]\n\n# Header 1\n\n## Header 2'
        self.assertHTMLEqual(
            markdown(text).strip(),
            '
[TOC]
\n
Header 1
'
            '\n
Header 2
'
        )
        self.assertHTMLEqual(
            markdown(text, extensions=['markdown.extensions.toc']).strip(),
            '
\n
\n
'
            'Header 1
\n
'
            'Header 2
\n
\n
\n
\n
'
            '\n
Header 1
\n'
            '
Header 2
'
        )
        from markdown.extensions.toc import TocExtension
        tocext = TocExtension(marker='--TOC--', permalink='PL')
        self.assertHTMLEqual(
            markdown(text, extensions=[tocext]).strip(),
            '
[TOC]
\n
Header 1'
            'PL
\n'
            '
Header 2'
            'PL
'
        )

    @skip_if_lib_not_available('docutils')
    def test_restructuredtext(self):
        self.assertHTMLEqual(
            restructuredtext(self.text).strip(),
            '
Hello World !
'
        )

    @skip_if_lib_not_available('docutils')
    def test_restructuredtext_settings_override(self):
        text = 'My email is toto@example.com'
        self.assertHTMLEqual(
            restructuredtext(text).strip(),
            '
My email is '
            'toto@example.com
'
        )
        self.assertHTMLEqual(
            restructuredtext(text, {'cloak_email_addresses': True}).strip(),
            '
My email is '
            'toto@example.com
'
        )

class MarkupFailImportTestCase(TestCase):
    exclude_list = ['textile', 'markdown', 'docutils']

    def setUp(self):
        self.original_import = builtins.__import__
        builtins.__import__ = self.import_hook

    def tearDown(self):
        builtins.__import__ = self.original_import

    def import_hook(self, name, *args, **kwargs):
        if name in self.exclude_list:
            raise ImportError('%s module has been disabled' % name)
        else:
            self.original_import(name, *args, **kwargs)

    def test_textile(self):
        with warnings.catch_warnings(record=True) as w:
            result = textile('My *text*')
        self.tearDown()
        self.assertEqual(result, 'My *text*')
        self.assertTrue(issubclass(w[-1].category, RuntimeWarning))
        self.assertEqual(
            str(w[-1].message),
            "The Python textile library isn't installed.")

    def test_markdown(self):
        with warnings.catch_warnings(record=True) as w:
            result = markdown('My *text*')
        self.tearDown()
        self.assertEqual(result, 'My *text*')
        self.assertTrue(issubclass(w[-1].category, RuntimeWarning))
        self.assertEqual(
            str(w[-1].message),
            "The Python markdown library isn't installed.")

    def test_restructuredtext(self):
        with warnings.catch_warnings(record=True) as w:
            result = restructuredtext('My *text*')
        self.tearDown()
        self.assertEqual(result, 'My *text*')
        self.assertTrue(issubclass(w[-1].category, RuntimeWarning))
        self.assertEqual(
            str(w[-1].message),
            "The Python docutils library isn't installed.")

class HtmlFormatTestCase(TestCase):

    def setUp(self):
        self.original_rendering = markups.MARKUP_LANGUAGE

    def tearDown(self):
        markups.MARKUP_LANGUAGE = self.original_rendering

    def test_html_format_default(self):
        markups.MARKUP_LANGUAGE = None
        self.assertHTMLEqual(html_format(''), '')
        self.assertHTMLEqual(html_format('Content'), '
Content
')
        self.assertEqual(html_format('Content
'), 'Content
')
        self.assertHTMLEqual(
            html_format('Hello\nworld!'),
            '
Hello
world!
'
        )

    @skip_if_lib_not_available('textile')
    def test_html_content_textitle(self):
        markups.MARKUP_LANGUAGE = 'textile'
        value = 'Hello world !\n\n' \
                'this is my content :\n\n' \
                '* Item 1\n* Item 2'
        self.assertHTMLEqual(
            html_format(value),
            '\t
Hello world !
\n\n\t'
            '
this is my content :
\n\n\t'
            '
\n\t\t
Item 1
\n\t\t'
            '
Item 2
\n\t
'
        )

    @skip_if_lib_not_available('markdown')
    def test_html_content_markdown(self):
        markups.MARKUP_LANGUAGE = 'markdown'
        value = 'Hello world !\n\n' \
                'this is my content :\n\n' \
                '* Item 1\n* Item 2'
        self.assertHTMLEqual(
            html_format(value),
            '
Hello world !
\n'
            '
this is my content :
'
            '\n
\n
Item 1
\n'
            '
Item 2
\n
'
        )

    @skip_if_lib_not_available('docutils')
    def test_html_content_restructuredtext(self):
        markups.MARKUP_LANGUAGE = 'restructuredtext'
        value = 'Hello world !\n\n' \
                'this is my content :\n\n' \
                '* Item 1\n* Item 2'
        self.assertHTMLEqual(
            html_format(value),
            '
Hello world !
\n'
            '
this is my content :
'
            '\n
\n
Item 1
\n'
            '
Item 2
\n
\n'
        )


text:
#ifndef __src_vnsw_agent_vrouter_ksync_ksync_flow_memory_h
#define __src_vnsw_agent_vrouter_ksync_ksync_flow_memory_h

/*
 * Module responsible to manage the VRouter memory mapped to agent
 */
#include <list>

class Timer;
class KSync;
class FlowKey;
struct vr_flow_entry;
struct vr_flow_entry;

class KSyncFlowMemory {
public:
    // Time to sweep flow-table for audit
    static const uint32_t kAuditSweepTime = 180;
    // Timer interval for audit process
    static const uint32_t kAuditYieldTimer = 100;  // in msec
    // Flows in HOLD state longer than kAuditTimeout are deleted
    static const uint32_t kAuditTimeout = (5 * 1000 * 1000); // in usec
    // Upper limit on number of entries to visit per timer
    static const uint32_t kAuditYieldMax = (1024);
    // Lower limit on number of entries to visit per timer
    static const uint32_t kAuditYieldMin = (100);

    KSyncFlowMemory(KSync *ksync);
    ~KSyncFlowMemory();

    void Init();
    void InitFlowMem();
    void InitTest();
    void Shutdown();

    const vr_flow_entry *GetKernelFlowEntry(uint32_t idx,
                                            bool ignore_active_status) const;
    const vr_flow_entry *GetValidKFlowEntry(const FlowKey &key,
                                            uint32_t idx, uint8_t gen_id) const;
    bool GetFlowKey(uint32_t index, FlowKey *key);

    uint32_t flow_table_entries_count() { return flow_table_entries_count_; }

    bool AuditProcess();
    void MapFlowMem();
    void UnmapFlowMemTest();
    void MapSharedMemory();
    void GetFlowTableSize();
    bool IsEvictionMarked(const vr_flow_entry *entry) const;

    KSync *ksync() const { return ksync_; }
    void set_major_devid(int id) { major_devid_ = id; }
    void set_flow_table_size(int count) { flow_table_size_ = count; }
    void set_flow_table_path(const std::string &path) {
        flow_table_path_ = path;
    }
    uint32_t audit_timeout() const { return audit_timeout_; }
private:
    struct AuditEntry {
        AuditEntry(uint32_t flow_idx, uint8_t gen_id,
                   uint64_t t) : audit_flow_idx(flow_idx),
                   audit_flow_gen_id(gen_id), timeout(t) {}

        uint32_t audit_flow_idx;
        uint8_t audit_flow_gen_id;
        uint64_t timeout;
    };
    void KFlow2FlowKey(const vr_flow_entry *entry, FlowKey *key) const;

    KSync                   *ksync_;
    vr_flow_entry           *flow_table_;
    // Name of file used to map flow table
    std::string             flow_table_path_;
    // major dev-id on linux based implementation
    int                     major_devid_;
    // Size of flow table memory
    int                     flow_table_size_;
    // Count of entries in flow-table
    uint32_t                flow_table_entries_count_;
    // Audit related entries
    Timer                   *audit_timer_;
    uint32_t                audit_timeout_;
    uint32_t                audit_yield_;
    uint32_t                audit_interval_;
    uint32_t                audit_flow_idx_;
    std::list<AuditEntry> audit_flow_list_;
};

#endif //  __src_vnsw_agent_vrouter_ksync_ksync_flow_memory_h


text:
#ifndef BASEPARTICLEFACTORY_H
#define BASEPARTICLEFACTORY_H

#include "pandabase.h"
#include "referenceCount.h"

#include "baseParticle.h"
#include "particleCommonFuncs.h"

#include <stdlib.h>

/**
 * Pure Virtual base class for creating particles
 */
class EXPCL_PANDAPHYSICS BaseParticleFactory : public ReferenceCount {
PUBLISHED:
  virtual ~BaseParticleFactory();

  INLINE void set_lifespan_base(PN_stdfloat lb);
  INLINE void set_lifespan_spread(PN_stdfloat ls);
  INLINE void set_mass_base(PN_stdfloat mb);
  INLINE void set_mass_spread(PN_stdfloat ms);
  INLINE void set_terminal_velocity_base(PN_stdfloat tvb);
  INLINE void set_terminal_velocity_spread(PN_stdfloat tvs);

  INLINE PN_stdfloat get_lifespan_base() const;
  INLINE PN_stdfloat get_lifespan_spread() const;
  INLINE PN_stdfloat get_mass_base() const;
  INLINE PN_stdfloat get_mass_spread() const;
  INLINE PN_stdfloat get_terminal_velocity_base() const;
  INLINE PN_stdfloat get_terminal_velocity_spread() const;

  virtual BaseParticle *alloc_particle() const = 0;

  void populate_particle(BaseParticle* bp);

  virtual void output(ostream &out) const;
  virtual void write(ostream &out, int indent=0) const;

protected:
  BaseParticleFactory();
  BaseParticleFactory(const BaseParticleFactory &copy);

private:
  PN_stdfloat _lifespan_base;
  PN_stdfloat _lifespan_spread;

  PN_stdfloat _mass_base;
  PN_stdfloat _mass_spread;

  PN_stdfloat _terminal_velocity_base;
  PN_stdfloat _terminal_velocity_spread;

  virtual void populate_child_particle(BaseParticle *bp) const = 0;
};

#include "baseParticleFactory.I"

#endif // BASEPARTICLEFACTORY_H


text:
'use strict';

var staticLanguages = ['C', 'C++', 'Java'];
var dynamicLanguages = ['JavaScript', 'PHP', 'Ruby'];

var languages = [].concat(staticLanguages, ['C#'], dynamicLanguages, ['Phyton']);

console.log(languages);

function add(x, y, z) {
	console.log(x + y + z);
}

var numbers = [1, 2, 3];

add.apply(undefined, numbers);


text:
'use strict';

angular.module('shoppingCart')
    .factory('OrdersResource', ['$resource', '$q',
        function OrdersResource ($resource, $q) {
            var Order = $resource('/api/orders/:orderId', { orderId: '@orderId' });

            return {
                getAllOrders : function () {
                    return Order.query();
                },
                getOrderById: function (id){
                    var deferred = $q.defer();

                    Order.get({orderId: id}, function (order) {
                        deferred.resolve(order);
                    });

                    return deferred.promise;
                }
            };
        }
    ]);


text:
#include <aws/emr-serverless/model/ApplicationState.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace EMRServerless
  {
    namespace Model
    {
      namespace ApplicationStateMapper
      {

        static const int CREATING_HASH = HashingUtils::HashString("CREATING");
        static const int CREATED_HASH = HashingUtils::HashString("CREATED");
        static const int STARTING_HASH = HashingUtils::HashString("STARTING");
        static const int STARTED_HASH = HashingUtils::HashString("STARTED");
        static const int STOPPING_HASH = HashingUtils::HashString("STOPPING");
        static const int STOPPED_HASH = HashingUtils::HashString("STOPPED");
        static const int TERMINATED_HASH = HashingUtils::HashString("TERMINATED");

        ApplicationState GetApplicationStateForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == CREATING_HASH)
          {
            return ApplicationState::CREATING;
          }
          else if (hashCode == CREATED_HASH)
          {
            return ApplicationState::CREATED;
          }
          else if (hashCode == STARTING_HASH)
          {
            return ApplicationState::STARTING;
          }
          else if (hashCode == STARTED_HASH)
          {
            return ApplicationState::STARTED;
          }
          else if (hashCode == STOPPING_HASH)
          {
            return ApplicationState::STOPPING;
          }
          else if (hashCode == STOPPED_HASH)
          {
            return ApplicationState::STOPPED;
          }
          else if (hashCode == TERMINATED_HASH)
          {
            return ApplicationState::TERMINATED;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<ApplicationState>(hashCode);
          }

          return ApplicationState::NOT_SET;
        }

        Aws::String GetNameForApplicationState(ApplicationState enumValue)
        {
          switch(enumValue)
          {
          case ApplicationState::CREATING:
            return "CREATING";
          case ApplicationState::CREATED:
            return "CREATED";
          case ApplicationState::STARTING:
            return "STARTING";
          case ApplicationState::STARTED:
            return "STARTED";
          case ApplicationState::STOPPING:
            return "STOPPING";
          case ApplicationState::STOPPED:
            return "STOPPED";
          case ApplicationState::TERMINATED:
            return "TERMINATED";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace ApplicationStateMapper
    } // namespace Model
  } // namespace EMRServerless
} // namespace Aws


text:
using namespace simdjson;

namespace object_tests {
  using namespace std;
  using simdjson::ondemand::json_type;

  bool object_index() {
    TEST_START();
    auto json = R"({ "a": 1, "b": 2, "c/d": 3})"_padded;
    SUBTEST("ondemand::object", test_ondemand_doc(json, [&](auto doc_result) {
      ondemand::object object;
      ASSERT_SUCCESS( doc_result.get(object) );

      ASSERT_EQUAL( object["a"].get_uint64().value_unsafe(), 1 );
      ASSERT_EQUAL( object["b"].get_uint64().value_unsafe(), 2 );
      ASSERT_EQUAL( object["c/d"].get_uint64().value_unsafe(), 3 );

      ASSERT_EQUAL( object["a"].get_uint64().value_unsafe(), 1 );
      ASSERT_ERROR( object["d"], NO_SUCH_FIELD );
      return true;
    }));
    SUBTEST("simdjson_result<ondemand::object>", test_ondemand_doc(json, [&](auto doc_result) {
      simdjson_result<ondemand::object> object;
      object = doc_result.get_object();

      ASSERT_EQUAL( object["a"].get_uint64().value_unsafe(), 1 );
      ASSERT_EQUAL( object["b"].get_uint64().value_unsafe(), 2 );
      ASSERT_EQUAL( object["c/d"].get_uint64().value_unsafe(), 3 );

      ASSERT_EQUAL( object["a"].get_uint64().value_unsafe(), 1 );
      ASSERT_ERROR( object["d"], NO_SUCH_FIELD );
      return true;
    }));
    TEST_SUCCEED();
  }

  bool document_object_index() {
    TEST_START();
    auto json = R"({ "a": 1, "b": 2, "c/d": 3})"_padded;
    SUBTEST("ondemand::document", test_ondemand_doc(json, [&](auto doc_result) {
      ondemand::document doc;
      ASSERT_SUCCESS( std::move(doc_result).get(doc) );
      ASSERT_EQUAL( doc["a"].get_uint64().value_unsafe(), 1 );
      ASSERT_EQUAL( doc["b"].get_uint64().value_unsafe(), 2 );
      ASSERT_EQUAL( doc["c/d"].get_uint64().value_unsafe(), 3 );

      ASSERT_EQUAL( doc["a"].get_uint64().value_unsafe(), 1 );
      ASSERT_ERROR( doc["d"], NO_SUCH_FIELD );
      return true;
    }));
    SUBTEST("simdjson_result<ondemand::document>", test_ondemand_doc(json, [&](auto doc_result) {
      ASSERT_EQUAL( doc_result["a"].get_uint64().value_unsafe(), 1 );
      ASSERT_EQUAL( doc_result["b"].get_uint64().value_unsafe(), 2 );
      ASSERT_EQUAL( doc_result["c/d"].get_uint64().value_unsafe(), 3 );

      ASSERT_EQUAL( doc_result["a"].get_uint64().value_unsafe(), 1 );
      ASSERT_ERROR( doc_result["d"], NO_SUCH_FIELD );
      return true;
    }));
    TEST_SUCCEED();
  }

  bool value_object_index() {
    TEST_START();
    auto json = R"({ "outer": { "a": 1, "b": 2, "c/d": 3 } })"_padded;
    SUBTEST("ondemand::value", test_ondemand_doc(json, [&](auto doc_result) {
      ondemand::value object;
      ASSERT_SUCCESS( doc_result["outer"].get(object) );
      ASSERT_EQUAL( object["a"].get_uint64().value_unsafe(), 1 );
      ASSERT_EQUAL( object["b"].get_uint64().value_unsafe(), 2 );
      ASSERT_EQUAL( object["c/d"].get_uint64().value_unsafe(), 3 );

      ASSERT_EQUAL( object["a"].get_uint64().value_unsafe(), 1 );
      ASSERT_ERROR( object["d"], NO_SUCH_FIELD );
      return true;
    }));
    SUBTEST("simdjson_result<ondemand::value>", test_ondemand_doc(json, [&](auto doc_result) {
      simdjson_result<ondemand::value> object = doc_result["outer"];
      ASSERT_EQUAL( object["a"].get_uint64().value_unsafe(), 1 );
      ASSERT_EQUAL( object["b"].get_uint64().value_unsafe(), 2 );
      ASSERT_EQUAL( object["c/d"].get_uint64().value_unsafe(), 3 );

      ASSERT_EQUAL( object["a"].get_uint64().value_unsafe(), 1 );
      ASSERT_ERROR( object["d"], NO_SUCH_FIELD );
      return true;
    }));
    TEST_SUCCEED();
  }

  bool document_nested_object_index() {
    TEST_START();
    auto json = R"({ "x": { "y": { "z": 2 } } }})"_padded;
    SUBTEST("simdjson_result<ondemand::document>", test_ondemand_doc(json, [&](auto doc_result) {
      ASSERT_EQUAL( doc_result["x"]["y"]["z"].get_uint64().value_unsafe(), 2 );
      return true;
    }));
    SUBTEST("ondemand::document", test_ondemand_doc(json, [&](auto doc_result) {
      ondemand::document doc;
      ASSERT_SUCCESS( std::move(doc_result).get(doc) );
      ASSERT_EQUAL( doc["x"]["y"]["z"].get_uint64().value_unsafe(), 2 );
      return true;
    }));
    TEST_SUCCEED();
  }

  bool nested_object_index() {
    TEST_START();
    auto json = R"({ "x": { "y": { "z": 2 } } }})"_padded;
    SUBTEST("simdjson_result<ondemand::object>", test_ondemand_doc(json, [&](auto doc_result) {
      simdjson_result<ondemand::object> object = doc_result.get_object();
      ASSERT_EQUAL( object["x"]["y"]["z"].get_uint64().value_unsafe(), 2 );
      return true;
    }));
    SUBTEST("ondemand::object", test_ondemand_doc(json, [&](auto doc_result) {
      ondemand::object object;
      ASSERT_SUCCESS( doc_result.get(object) );
      ASSERT_EQUAL( object["x"]["y"]["z"].get_uint64().value_unsafe(), 2 );
      return true;
    }));
    TEST_SUCCEED();
  }

  bool value_nested_object_index() {
    TEST_START();
    auto json = R"({ "x": { "y": { "z": 2 } } }})"_padded;
    SUBTEST("simdjson_result<ondemand::value>", test_ondemand_doc(json, [&](auto doc_result) {
      simdjson_result<ondemand::value> x = doc_result["x"];
      ASSERT_EQUAL( x["y"]["z"].get_uint64().value_unsafe(), 2 );
      return true;
    }));
    SUBTEST("ondemand::value", test_ondemand_doc(json, [&](auto doc_result) {
      ondemand::value x;
      ASSERT_SUCCESS( doc_result["x"].get(x) );
      ASSERT_EQUAL( x["y"]["z"].get_uint64().value_unsafe(), 2 );
      return true;
    }));
    TEST_SUCCEED();
  }

  bool object_index_partial_children() {
    TEST_START();
    auto json = R"(
      {
        "scalar_ignore":       0,
        "empty_array_ignore":  [],
        "empty_object_ignore": {},
        "object_break":        { "x": 3, "y": 33 },
        "object_break_unused": { "x": 4, "y": 44 },
        "object_index":        { "x": 5, "y": 55 },
        "object_index_unused": { "x": 6, "y": 66 },
        "array_break":         [ 7, 77, 777 ],
        "array_break_unused":  [ 8, 88, 888 ],
        "quadruple_nested_break": { "a": [ { "b": [ 9, 99 ], "c": 999 }, 9999 ], "d": 99999 },
        "actual_value": 10
      }
    )"_padded;
    SUBTEST("ondemand::object", test_ondemand_doc(json, [&](auto doc_result) {
      ondemand::object object;
      ASSERT_SUCCESS( doc_result.get(object) );

      ASSERT_SUCCESS( object["scalar_ignore"] );
      std::cout << "  - After ignoring empty scalar ..." << std::endl;

      ASSERT_SUCCESS( object["empty_array_ignore"] );
      std::cout << "  - After ignoring empty array ..." << std::endl;

      ASSERT_SUCCESS( object["empty_object_ignore"] );
      std::cout << "  - After ignoring empty object ..." << std::endl;

      // Break after using first value in child object
      {
        auto value = object["object_break"];
        for (auto [ child_field, error ] : value.get_object()) {
          ASSERT_SUCCESS(error);
          ASSERT_EQUAL(child_field.key(), "x");
          uint64_t x;
          ASSERT_SUCCESS( child_field.value().get(x) );
          ASSERT_EQUAL(x, 3);
          break; // Break after the first value
        }
        std::cout << "  - After using first value in child object ..." << std::endl;
      }

      // Break without using first value in child object
      {
        auto value = object["object_break_unused"];
        for (auto [ child_field, error ] : value.get_object()) {
          ASSERT_SUCCESS(error);
          ASSERT_EQUAL(child_field.key(), "x");
          break;
        }
        std::cout << "  - After reaching (but not using) first value in child object ..." << std::endl;
      }

      // Only look up one field in child object
      {
        auto value = object["object_index"];

        uint64_t x;
        ASSERT_SUCCESS( value["x"].get(x) );
        ASSERT_EQUAL( x, 5 );
        std::cout << "  - After looking up one field in child object ..." << std::endl;
      }

      // Only look up one field in child object, but don't use it
      {
        auto value = object["object_index_unused"];

        ASSERT_SUCCESS( value["x"] );
        std::cout << "  - After looking up (but not using) one field in child object ..." << std::endl;
      }

      // Break after first value in child array
      {
        auto value = object["array_break"];

        for (auto child_value : value) {
          uint64_t x;
          ASSERT_SUCCESS( child_value.get(x) );
          ASSERT_EQUAL( x, 7 );
          break;
        }
        std::cout << "  - After using first value in child array ..." << std::endl;
      }

      // Break without using first value in child array
      {
        auto value = object["array_break_unused"];

        for (auto child_value : value) {
          ASSERT_SUCCESS(child_value);
          break;
        }
        std::cout << "  - After reaching (but not using) first value in child array ..." << std::endl;
      }

      // Break out of multiple child loops
      {
        auto value = object["quadruple_nested_break"];
        for (auto child1 : value.get_object()) {
          for (auto child2 : child1.value().get_array()) {
            for (auto child3 : child2.get_object()) {
              for (auto child4 : child3.value().get_array()) {
                uint64_t x;
                ASSERT_SUCCESS( child4.get(x) );
                ASSERT_EQUAL( x, 9 );
                break;
              }
              break;
            }
            break;
          }
          break;
        }
        std::cout << "  - After breaking out of quadruply-nested arrays and objects ..." << std::endl;
      }

      // Test the actual value
      {
        auto value = object["actual_value"];
        uint64_t actual_value;
        ASSERT_SUCCESS( value.get(actual_value) );
        ASSERT_EQUAL( actual_value, 10 );
      }

      return true;
    }));

    SUBTEST("simdjson_result<ondemand::document>", test_ondemand_doc(json, [&](auto doc_result) {
      ASSERT_SUCCESS( doc_result["scalar_ignore"] );
      std::cout << "  - After ignoring empty scalar ..." << std::endl;

      ASSERT_SUCCESS( doc_result["empty_array_ignore"] );
      std::cout << "  - After ignoring empty array ..." << std::endl;

      ASSERT_SUCCESS( doc_result["empty_object_ignore"] );
      std::cout << "  - After ignoring empty doc_result ..." << std::endl;

      // Break after using first value in child object
      {
        auto value = doc_result["object_break"];
        for (auto [ child_field, error ] : value.get_object()) {
          ASSERT_SUCCESS(error);
          ASSERT_EQUAL(child_field.key(), "x");
          uint64_t x;
          ASSERT_SUCCESS( child_field.value().get(x) );
          ASSERT_EQUAL(x, 3);
          break; // Break after the first value
        }
        std::cout << "  - After using first value in child object ..." << std::endl;
      }

      // Break without using first value in child object
      {
        auto value = doc_result["object_break_unused"];
        for (auto [ child_field, error ] : value.get_object()) {
          ASSERT_SUCCESS(error);
          ASSERT_EQUAL(child_field.key(), "x");
          break;
        }
        std::cout << "  - After reaching (but not using) first value in child object ..." << std::endl;
      }

      // Only look up one field in child object
      {
        auto value = doc_result["object_index"];

        uint64_t x;
        ASSERT_SUCCESS( value["x"].get(x) );
        ASSERT_EQUAL( x, 5 );
        std::cout << "  - After looking up one field in child object ..." << std::endl;
      }

      // Only look up one field in child object, but don't use it
      {
        auto value = doc_result["object_index_unused"];

        ASSERT_SUCCESS( value["x"] );
        std::cout << "  - After looking up (but not using) one field in child object ..." << std::endl;
      }

      // Break after first value in child array
      {
        auto value = doc_result["array_break"];

        for (auto child_value : value) {
          uint64_t x;
          ASSERT_SUCCESS( child_value.get(x) );
          ASSERT_EQUAL( x, 7 );
          break;
        }
        std::cout << "  - After using first value in child array ..." << std::endl;
      }

      // Break without using first value in child array
      {
        auto value = doc_result["array_break_unused"];

        for (auto child_value : value) {
          ASSERT_SUCCESS(child_value);
          break;
        }
        std::cout << "  - After reaching (but not using) first value in child array ..." << std::endl;
      }

      // Break out of multiple child loops
      {
        auto value = doc_result["quadruple_nested_break"];
        for (auto child1 : value.get_object()) {
          for (auto child2 : child1.value().get_array()) {
            for (auto child3 : child2.get_object()) {
              for (auto child4 : child3.value().get_array()) {
                uint64_t x;
                ASSERT_SUCCESS( child4.get(x) );
                ASSERT_EQUAL( x, 9 );
                break;
              }
              break;
            }
            break;
          }
          break;
        }
        std::cout << "  - After breaking out of quadruply-nested arrays and objects ..." << std::endl;
      }

      // Test the actual value
      {
        auto value = doc_result["actual_value"];
        uint64_t actual_value;
        ASSERT_SUCCESS( value.get(actual_value) );
        ASSERT_EQUAL( actual_value, 10 );
      }

      return true;
    }));

    return true;
  }

#if SIMDJSON_EXCEPTIONS

  bool object_index_exception() {
    TEST_START();
    auto json = R"({ "a": 1, "b": 2, "c/d": 3})"_padded;
    SUBTEST("ondemand::object", test_ondemand_doc(json, [&](auto doc_result) {
      ondemand::object object = doc_result;

      ASSERT_EQUAL( uint64_t(object["a"]), 1 );
      ASSERT_EQUAL( uint64_t(object["b"]), 2 );
      ASSERT_EQUAL( uint64_t(object["c/d"]), 3 );

      return true;
    }));
    TEST_SUCCEED();
  }
  bool nested_object_index_exception() {
    TEST_START();
    auto json = R"({ "x": { "y": { "z": 2 } } }})"_padded;
    SUBTEST("simdjson_result<ondemand::document>", test_ondemand_doc(json, [&](auto doc_result) {
      ASSERT_EQUAL( uint64_t(doc_result["x"]["y"]["z"]), 2 );
      return true;
    }));
    TEST_SUCCEED();
  }

#endif // SIMDJSON_EXCEPTIONS

  bool run() {
    return
           object_index() &&
           document_object_index() &&
           value_object_index() &&
           nested_object_index() &&
           document_nested_object_index() &&
           value_nested_object_index() &&
           object_index_partial_children() &&
#if SIMDJSON_EXCEPTIONS
           object_index_exception() &&
           nested_object_index_exception() &&
#endif // SIMDJSON_EXCEPTIONS
           true;
  }

} // namespace object_tests

int main(int argc, char *argv[]) {
  return test_main(argc, argv, object_tests::run);
}


text:
package colossus.util.compress

import java.io.{ByteArrayInputStream, ByteArrayOutputStream}
import java.util.zip.{GZIPInputStream, GZIPOutputStream}

import akka.util.{ByteString, ByteStringBuilder}

class GzipCompressor(bufferKB: Int = 10) extends Compressor {
  override def compress(bytes: ByteString): ByteString = {
    val bos  = new ByteArrayOutputStream(bytes.length)
    val gzip = new GZIPOutputStream(bos)
    gzip.write(bytes.toArray)
    gzip.close()
    val compressed = bos.toByteArray
    bos.close()
    ByteString(compressed)
  }

  override def decompress(bytes: ByteString): ByteString = {
    val inputStream         = new GZIPInputStream(new ByteArrayInputStream(bytes.toArray))
    val buffer: Array[Byte] = new Array[Byte](1024 * bufferKB)
    var read: Int           = 0
    val builder             = new ByteStringBuilder
    read = inputStream.read(buffer)
    while (read > 0) {
      builder.putBytes(buffer, 0, read)
      read = inputStream.read(buffer)
    }

    inputStream.close()
    builder.result()
  }
}


text:
class CircleObject;

class MAPGRAPHICSSHARED_EXPORT PolygonObject : public MapGraphicsObject
{
    Q_OBJECT
public:
    explicit PolygonObject(QPolygonF geoPoly, QColor fillColor = QColor(200,200,200,200), QObject *parent = 0);
    virtual ~PolygonObject();

    //pure-virtual from MapGraphicsObject
    QRectF boundingRect() const;

    //virtual from MapGraphicsObject
    bool contains(const QPointF &geoPos) const;

    //pure-virtual from MapGraphicsObject
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);

    //virtual from MapGraphicsObject
    virtual void setPos(const QPointF &);

    QPolygonF geoPoly() const;

    virtual void setGeoPoly(const QPolygonF& newPoly);

    void setFillColor(const QColor& color);

signals:
    void polygonChanged(const QPolygonF& poly);

public slots:

protected:
    //virtual from MapGraphicsObject
    virtual void mousePressEvent(QGraphicsSceneMouseEvent * event);
    virtual void keyReleaseEvent(QKeyEvent *event);

private slots:
    void handleEditCirclePosChanged();
    void handleAddVertexCircleSelected();
    void handleEditCircleDestroyed();

private:
    void fixAddVertexCirclePos();

    CircleObject * constructEditCircle();
    void destroyEditCircle(MapGraphicsObject * obj);

    CircleObject * constructAddVertexCircle();
    void destroyAddVertexCircle(MapGraphicsObject * obj);

    QPolygonF _geoPoly;
    QColor _fillColor;

    QList<MapGraphicsObject *> _editCircles;
    QList<MapGraphicsObject *> _addVertexCircles;

};

#endif // POLYGONOBJECT_H