text:
package uk.gov.gchq.gaffer.cache;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import uk.gov.gchq.gaffer.cache.exception.CacheOperationException;
import uk.gov.gchq.gaffer.cache.util.CacheProperties;
import uk.gov.gchq.gaffer.commonutil.exception.OverwritingException;

import java.util.Properties;

import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;

public class CacheTest {

    private static final String CACHE_SERVICE_CLASS_STRING = "uk.gov.gchq.gaffer.cache.impl.HashMapCacheService";
    private static Cache<Integer> cache;
    private static Properties properties = new Properties();

    @BeforeAll
    public static void setUp() {
        properties.setProperty(CacheProperties.CACHE_SERVICE_CLASS, CACHE_SERVICE_CLASS_STRING);
        CacheServiceLoader.initialise(properties);
        cache = new Cache<>("serviceName1");
    }

    @BeforeEach
    public void beforeEach() throws CacheOperationException {
        cache.clearCache();
    }

    @Test
    public void shouldAddAndGetValueFromCache() throws CacheOperationException {
        cache.addToCache("key1", 1, true);

        assertEquals((Integer) 1, cache.getFromCache("key1"));
        assertNull(cache.getFromCache("key2"));
    }

    @Test
    public void shouldAddAndGetCacheOverwrite() throws CacheOperationException {
        cache.addToCache("key1", 1, true);
        cache.addToCache("key1", 2, true);

        assertEquals(2, cache.getFromCache("key1").intValue());
    }

    @Test
    public void shouldAddAndGetCacheNoOverwrite() throws CacheOperationException {
        cache.addToCache("key1", 1, true);

        assertThatExceptionOfType(OverwritingException.class)
                .isThrownBy(() -> cache.addToCache("key1", 2, false))
                .withMessage("Cache entry already exists for key: key1");

        assertEquals(1, cache.getFromCache("key1").intValue());
    }

    @Test
    public void shouldGetCacheServiceName() {
        assertEquals("serviceName1", cache.getCacheName());
    }

    @Test
    public void shouldDeleteKeyValuePair() throws CacheOperationException {
        cache.addToCache("key1", 1, false);
        cache.deleteFromCache("key1");

        assertNull(cache.getFromCache("key1"));
    }
}


text:
Daniel Kershaw - Lancaster University

## Refrences

redpajama_set_name: RedPajamaGithub


text:
package com.vaslabs.units;
import com.vaslabs.units.composite.VelocityUnit;
import junit.framework.TestCase;

import static com.vaslabs.units.TestConstants.DIFF;

/**
 * Created by nicolaouv on 8/17/15.
 */
public class TestVelocityUnit extends TestCase {

    public void setUp() {

    }

    public void test_minutes_per_second_to_km_per_hour() {
        double minutesPerSecondValue = 32.432;
        VelocityUnit minutesPerSecondVelocity = new VelocityUnit(
                                                        DistanceUnit.METERS, TimeUnit.SECONDS,
                                                        minutesPerSecondValue);
        VelocityUnit kmPerHour = minutesPerSecondVelocity.convert(DistanceUnit.KM, TimeUnit.HOURS);

        assertEquals(116.7552, kmPerHour.DISTANCE_VALUE, DIFF);

        minutesPerSecondValue = 0;
        minutesPerSecondVelocity = new VelocityUnit(
                DistanceUnit.METERS, TimeUnit.SECONDS,
                minutesPerSecondValue);
        kmPerHour = minutesPerSecondVelocity.convert(DistanceUnit.KM, TimeUnit.HOURS);

        assertEquals(0, kmPerHour.DISTANCE_VALUE, DIFF);

    }

    public void test_minutes_per_second_to_feet_per_second() {
        double minutesPerSecondValue = 32.432;
        VelocityUnit minutesPerSecondVelocity = new VelocityUnit(
                DistanceUnit.METERS, TimeUnit.SECONDS,
                minutesPerSecondValue);
        VelocityUnit kmPerHour = minutesPerSecondVelocity.convert(DistanceUnit.FEET, TimeUnit.SECONDS);

        assertEquals(106.404199, kmPerHour.DISTANCE_VALUE, DIFF);

        minutesPerSecondValue = 0;
        minutesPerSecondVelocity = new VelocityUnit(
                DistanceUnit.METERS, TimeUnit.SECONDS,
                minutesPerSecondValue);
        kmPerHour = minutesPerSecondVelocity.convert(DistanceUnit.FEET, TimeUnit.SECONDS);

        assertEquals(0, kmPerHour.DISTANCE_VALUE, DIFF);

        minutesPerSecondValue = 0.8;
        minutesPerSecondVelocity = new VelocityUnit(
                DistanceUnit.METERS, TimeUnit.SECONDS,
                minutesPerSecondValue);
        kmPerHour = minutesPerSecondVelocity.convert(DistanceUnit.FEET, TimeUnit.SECONDS);

        assertEquals(2.62467192, kmPerHour.DISTANCE_VALUE, DIFF);

    }

    public void test_km_per_hour_to_meters_per_second() {
        double kmPerHourValue = 203;
        VelocityUnit kmPerHour = new VelocityUnit(DistanceUnit.KM, TimeUnit.HOURS, kmPerHourValue);

        VelocityUnit metersPerSecond = kmPerHour.convert(DistanceUnit.METERS, TimeUnit.SECONDS);

        assertEquals(56.3888889, metersPerSecond.DISTANCE_VALUE, DIFF);

        kmPerHourValue = 0.3;
        kmPerHour = new VelocityUnit(DistanceUnit.KM, TimeUnit.HOURS, kmPerHourValue);

        metersPerSecond = kmPerHour.convert(DistanceUnit.METERS, TimeUnit.SECONDS);

        assertEquals(0.0833333333, metersPerSecond.DISTANCE_VALUE, DIFF);

        kmPerHourValue = 0;
        kmPerHour = new VelocityUnit(DistanceUnit.KM, TimeUnit.HOURS, kmPerHourValue);

        metersPerSecond = kmPerHour.convert(DistanceUnit.METERS, TimeUnit.SECONDS);

        assertEquals(0, metersPerSecond.DISTANCE_VALUE, DIFF);
    }

    public void test_km_per_hour_to_miles_per_hour() {
        double kmPerHourValue = 203;
        VelocityUnit kmPerHour = new VelocityUnit(DistanceUnit.KM, TimeUnit.HOURS, kmPerHourValue);

        VelocityUnit metersPerSecond = kmPerHour.convert(DistanceUnit.MILES, TimeUnit.HOURS);

        assertEquals(126.13835202417879, metersPerSecond.DISTANCE_VALUE, DIFF);

        kmPerHourValue = 0.3;
        kmPerHour = new VelocityUnit(DistanceUnit.KM, TimeUnit.HOURS, kmPerHourValue);

        metersPerSecond = kmPerHour.convert(DistanceUnit.MILES, TimeUnit.HOURS);

        assertEquals(0.186411, metersPerSecond.DISTANCE_VALUE, DIFF);

        kmPerHourValue = 0;
        kmPerHour = new VelocityUnit(DistanceUnit.KM, TimeUnit.HOURS, kmPerHourValue);

        metersPerSecond = kmPerHour.convert(DistanceUnit.MILES, TimeUnit.HOURS);

        assertEquals(0, metersPerSecond.DISTANCE_VALUE, DIFF);
    }
}


text:
import os.path
import logging
from copy import deepcopy
import numpy

import rmgpy.constants as constants
from rmgpy.kinetics import Arrhenius, ArrheniusEP, ThirdBody, Lindemann, Troe, \
                           PDepArrhenius, MultiArrhenius, MultiPDepArrhenius, \
                           Chebyshev, KineticsData
from rmgpy.molecule import Molecule, Group
from rmgpy.species import Species
from rmgpy.reaction import Reaction
from rmgpy.data.base import LogicNode, DatabaseError

from .family import  KineticsFamily
from .library import LibraryReaction, KineticsLibrary
from .common import filterReactions

################################################################################

class KineticsDatabase(object):
    """
    A class for working with the RMG kinetics database.
    """

    def __init__(self):
        self.recommendedFamilies = {}
        self.families = {}
        self.libraries = {}
        self.libraryOrder = []     # a list of tuples in the format ('library_label', LibraryType),
                                   # where LibraryType is set to either 'Reaction Library' or 'Seed'.
        self.local_context = {
            'KineticsData': KineticsData,
            'Arrhenius': Arrhenius,
            'ArrheniusEP': ArrheniusEP,
            'MultiArrhenius': MultiArrhenius,
            'MultiPDepArrhenius': MultiPDepArrhenius,
            'PDepArrhenius': PDepArrhenius,
            'Chebyshev': Chebyshev,
            'ThirdBody': ThirdBody,
            'Lindemann': Lindemann,
            'Troe': Troe,
            'R': constants.R,
        }
        self.global_context = {}

    def __reduce__(self):
        """
        A helper function used when pickling a KineticsDatabase object.
        """
        d = {
            'families': self.families,
            'libraries': self.libraries,
            'libraryOrder': self.libraryOrder,
        }
        return (KineticsDatabase, (), d)

    def __setstate__(self, d):
        """
        A helper function used when unpickling a KineticsDatabase object.
        """
        self.families = d['families']
        self.libraries = d['libraries']
        self.libraryOrder = d['libraryOrder']

    def load(self, path, families=None, libraries=None, depositories=None):
        """
        Load the kinetics database from the given `path` on disk, where `path`
        points to the top-level folder of the families database.
        """
        self.loadRecommendedFamiliesList(os.path.join(path, 'families', 'recommended.py')),
        self.loadFamilies(os.path.join(path, 'families'), families, depositories)
        self.loadLibraries(os.path.join(path, 'libraries'), libraries)

    def loadRecommendedFamiliesList(self, filepath):
        """
        Load the list of recommended families from the given file

        The file is usually 'kinetics/families/recommended.py'.
        This is stored as a dictionary of True or False values (checked here),
        and should contain entries for every available family (checked in loadFamilies).
        """
        try:
            global_context = {}
            global_context['__builtins__'] = None
            global_context['True'] = True
            global_context['False'] = False
            local_context = {}
            local_context['__builtins__'] = None
            f = open(filepath, 'r')
            exec f in global_context, local_context
            f.close()
            self.recommendedFamilies = local_context['recommendedFamilies']
        except:
            raise DatabaseError('Error while reading list of recommended families from {0}/recommended.py.'.format(filepath))
        for recommended in self.recommendedFamilies.values():
            if not isinstance(recommended, bool):
                raise DatabaseError("recommendedFamilies dictionary should contain only True or False values")

    def loadFamilies(self, path, families=None, depositories=None):
        """
        Load the kinetics families from the given `path` on disk, where `path`
        points to the top-level folder of the kinetics families.
        """

        familiesToLoad = []
        for (root, dirs, files) in os.walk(os.path.join(path)):
            if root == path:
                break  # all we wanted was the list of dirs in the base path

        if families == 'default':
            logging.info('Loading default kinetics families from {0}'.format(path))
            for d in dirs:  # load them in directory listing order, like other methods (better than a random dict order)
                try:
                    recommended = self.recommendedFamilies[d]
                except KeyError:
                    raise DatabaseError('Family {0} not found in recommendation list (probably at {1}/recommended.py)'.format(d, path))
                if recommended:
                    familiesToLoad.append(d)
            for label, value in self.recommendedFamilies.iteritems():
                if label not in dirs:
                    raise DatabaseError('Family {0} found (in {1}/recommended.py) not found on disk.'.format(label, path))

        elif families == 'all':
            # All families are loaded
            logging.info('Loading all of the kinetics families from {0}'.format(path))
            for d in dirs:
                familiesToLoad.append(d)
        elif families == 'none':
            logging.info('Not loading any of the kinetics families from {0}'.format(path))
            # Don't load any of the families
            familiesToLoad = []
        elif isinstance(families, list):
            logging.info('Loading the user-specified kinetics families from {0}'.format(path))
            # If all items in the list start with !, all families will be loaded except these
            if len(families) == 0:
                raise DatabaseError('Kinetics families should be a non-empty list, or set to `default`, `all`, or `none`.')
            elif all([label.startswith('!') for label in families]):
                for d in dirs:
                    if '!{0}'.format(d) not in families:
                        familiesToLoad.append(d)
            elif any([label.startswith('!') for label in families]):
                raise DatabaseError('Families list must either all or none have prefix "!", but not a mix.')
            else:  # only the families given will be loaded
                for d in dirs:
                    if d in families:
                        familiesToLoad.append(d)
                for label in families:
                    if label not in dirs:
                        raise DatabaseError('Family {0} not found on disk.'.format(label))
        else:
            raise DatabaseError('Kinetics families was not specified properly.  Should be set to `default`,`all`,`none`, or a list.')

        # Now we know what families to load, so let's load them
        self.families = {}
        for label in familiesToLoad:
            familyPath = os.path.join(path, label)
            family = KineticsFamily(label=label)
            family.load(familyPath, self.local_context, self.global_context, depositoryLabels=depositories)
            self.families[label] = family

    def loadLibraries(self, path, libraries=None):
        """
        Load the listed kinetics libraries from the given `path` on disk.

        Loads them all if `libraries` list is not specified or `None`.
        The `path` points to the folder of kinetics libraries in the database,
        and the libraries should be in files like :file:`<path>/<library>.py`.
        """
        self.libraries = {}

        if libraries is not None:
            for library_name in libraries:
                library_file = os.path.join(path, library_name,'reactions.py')
                if os.path.exists(library_file):
                    logging.info('Loading kinetics library {0} from {1}...'.format(library_name, library_file))
                    library = KineticsLibrary(label=library_name)
                    library.load(library_file, self.local_context, self.global_context)
                    self.libraries[library.label] = library
                else:
                    raise IOError("Couldn't find kinetics library {0}".format(library_file))
            # library order should've been set prior to this, with the given seed mechs and reaction libraries
            assert (len(self.libraryOrder) == len(libraries))
        else:# load all the libraries you can find (this cannot be activated in a normal RMG job.  Only activated when loading the database for other purposes)
            self.libraryOrder = []
            for (root, dirs, files) in os.walk(os.path.join(path)):
                for f in files:
                    name, ext = os.path.splitext(f)
                    if ext.lower() == '.py':
                        library_file = os.path.join(root, f)
                        label=os.path.dirname(library_file)[len(path)+1:]
                        logging.info('Loading kinetics library {0} from {1}...'.format(label, library_file))
                        library = KineticsLibrary(label=label)
                        library.load(library_file, self.local_context, self.global_context)
                        self.libraries[library.label] = library
                        self.libraryOrder.append((library.label,'Reaction Library'))

    def save(self, path):
        """
        Save the kinetics database to the given `path` on disk, where `path`
        points to the top-level folder of the kinetics database.
        """
        path = os.path.abspath(path)
        if not os.path.exists(path): os.mkdir(path)
        self.saveRecommendedFamilies(os.path.join(path, 'families'))
        self.saveFamilies(os.path.join(path, 'families'))
        self.saveLibraries(os.path.join(path, 'libraries'))

    def saveRecommendedFamilies(self, path):
        """
        Save the list of recommended families in a dictionary stored at
        `path`/recommended.py
        """
        import codecs

        if not os.path.exists(path): os.mkdir(path)
        f = codecs.open(os.path.join(path,'recommended.py'), 'w', 'utf-8')
        f.write('''# This file contains a dictionary of kinetics families.  The families
# set to `True` are recommended by RMG and turned on by default by setting
# kineticsFamilies = 'default' in the RMG input file. Families set to `False`
# are not turned on by default because the family is severely lacking in data.
# These families should only be turned on with caution.''')
        f.write('\n\n')
        f.write('recommendedFamilies = {\n')
        for label in sorted(self.recommendedFamilies.keys()):
            f.write("'{label}':{value},\n".format(label=label,value=self.recommendedFamilies[label]))
        f.write('}')
        f.close()

    def saveFamilies(self, path):
        """
        Save the kinetics families to the given `path` on disk, where `path`
        points to the top-level folder of the kinetics families.
        """
        if not os.path.exists(path): os.mkdir(path)
        for label, family in self.families.iteritems():
            familyPath = os.path.join(path, label)
            if not os.path.exists(familyPath): os.mkdir(familyPath)
            family.save(familyPath)

    def saveLibraries(self, path):
        """
        Save the kinetics libraries to the given `path` on disk, where `path`
        points to the top-level folder of the kinetics libraries.
        """
        for label, library in self.libraries.iteritems():
            folders = label.split(os.sep)
            try:
                os.makedirs(os.path.join(path, *folders))
            except OSError:
                pass
            library.save(os.path.join(path, label, 'reactions.py'))
            library.saveDictionary(os.path.join(path, label, 'dictionary.txt'))

    def loadOld(self, path):
        """
        Load the old RMG kinetics database from the given `path` on disk, where
        `path` points to the top-level folder of the old RMG database.
        """
        self.families = {}
        self.libraries = {}

        librariesPath = os.path.join(path, 'kinetics_libraries')
        for (root, dirs, files) in os.walk(os.path.join(path, 'kinetics_libraries')):
            if os.path.exists(os.path.join(root, 'species.txt')) and os.path.exists(os.path.join(root, 'reactions.txt')):
                library = KineticsLibrary(label=root[len(librariesPath)+1:], name=root[len(librariesPath)+1:])
                logging.warning("Loading {0}".format(root))
                library.loadOld(root)
                self.libraries[library.label] = library

        for (root, dirs, files) in os.walk(os.path.join(path, 'kinetics_groups')):
            if os.path.exists(os.path.join(root, 'dictionary.txt')) and os.path.exists(os.path.join(root, 'rateLibrary.txt')):
                label = os.path.split(root)[1]
                family = KineticsFamily(label=label)
                logging.warning("Loading {0}".format(root))
                family.loadOld(root)
                self.families[family.label] = family

        return self

    def saveOld(self, path):
        """
        Save the old RMG kinetics database to the given `path` on disk, where
        `path` points to the top-level folder of the old RMG database.
        """
        librariesPath = os.path.join(path, 'kinetics_libraries')
        if not os.path.exists(librariesPath): os.mkdir(librariesPath)
        for library in self.libraries.values():
            libraryPath = os.path.join(librariesPath, library.label)
            library.saveOld(libraryPath)

        groupsPath = os.path.join(path, 'kinetics_groups')
        if not os.path.exists(groupsPath): os.mkdir(groupsPath)
        for label, family in self.families.iteritems():
            groupPath = os.path.join(groupsPath, label)
            family.saveOld(groupPath)

        with open(os.path.join(path,'kinetics_groups','families.txt'),'w') as f:
            f.write("""
////////////////////////////////////////////////////////////////////////////////
//
// REACTION FAMILIES USED BY RMG
//
// Notes:
//
// The name of each forward reaction should match up with a folder
// in this directory containing the dictionary, tree, library, and adjusts
// for that family.
//
// Families can be deactivated by simply changing the "on/off" column to off.
//
// This file was generated by exporting the entirety of RMG-Py,
// so the on/off decisions come from the defaults there.
//
////////////////////////////////////////////////////////////////////////////////

// No.  on/off  Forward reaction
""")
            for number, label in enumerate(sorted(self.families.keys())):
                onoff = 'on ' if self.recommendedFamilies[label] else 'off'
                f.write("{num:<2d}    {onoff}     {label}\n".format(num=number, label=label, onoff=onoff))

    def generateReactions(self, reactants, products=None, failsSpeciesConstraints=None):
        """
        Generate all reactions between the provided list of one or two
        `reactants`, which should be :class:`Molecule` objects. This method
        searches the depository, libraries, and groups, in that order.
        """
        reactionList = []
        reactionList.extend(self.generateReactionsFromLibraries(reactants, products, failsSpeciesConstraints=failsSpeciesConstraints))
        reactionList.extend(self.generateReactionsFromFamilies(reactants, products, failsSpeciesConstraints=failsSpeciesConstraints))
        return reactionList

    def generateReactionsFromLibraries(self, reactants, products, failsSpeciesConstraints=None):
        """
        Generate all reactions between the provided list of one or two
        `reactants`, which should be :class:`Molecule` objects. This method
        searches the depository.
        """
        reactionList = []
        for label, libraryType in self.libraryOrder:
            # Generate reactions from reaction libraries (no need to generate them from seeds)
            if libraryType == "Reaction Library":
                reactionList.extend(self.generateReactionsFromLibrary(reactants, products, self.libraries[label], failsSpeciesConstraints=failsSpeciesConstraints))
        return reactionList

    def generateReactionsFromLibrary(self, reactants, products, library, failsSpeciesConstraints=None):
        """
        Generate all reactions between the provided list of one or two
        `reactants`, which should be :class:`Molecule` objects. This method
        searches the depository.
        """
        reactionList = []
        for entry in library.entries.values():
            if entry.item.matchesMolecules(reactants):
                reaction = LibraryReaction(
                    reactants = entry.item.reactants[:],
                    products = entry.item.products[:],
                    degeneracy = entry.item.degeneracy,
                    reversible = entry.item.reversible,
                    duplicate = entry.item.duplicate,
                    kinetics = deepcopy(entry.data),
                    library = library,
                    entry = entry,
                )
                reactionList.append(reaction)
        if products:
            reactionList = filterReactions(reactants, products, reactionList)
        return reactionList

    def generateReactionsFromFamilies(self, reactants, products, only_families=None, failsSpeciesConstraints=None):
        """
        Generate all reactions between the provided list of one or two
        `reactants`, which should be :class:`Molecule` objects. This method
        applies the reaction family.
        If `only_families` is a list of strings, only families with those labels
        are used.
        """
        # If there are two structures and they are the same, then make a copy
        # of the second one so we can independently manipulate both of them
        # This is for the case where A + A --> products
        if len(reactants) == 2 and reactants[0] == reactants[1]:
            reactants[1] = reactants[1].copy(deep=True)

        reactionList = []
        for label, family in self.families.iteritems():
            if only_families is None or label in only_families:
                reactionList.extend(family.generateReactions(reactants, failsSpeciesConstraints=failsSpeciesConstraints))
        if products:
            reactionList = filterReactions(reactants, products, reactionList)
        return reactionList

    def getForwardReactionForFamilyEntry(self, entry, family, thermoDatabase):
        """
        For a given `entry` for a reaction of the given reaction `family` (the
        string label of the family), return the reaction with kinetics and
        degeneracy for the "forward" direction as defined by the reaction
        family. For families that are their own reverse, the direction the
        kinetics is given in will be preserved. If the entry contains
        functional groups for the reactants, assume that it is given in the
        forward direction and do nothing. Returns the reaction in the direction
        consistent with the reaction family template, and the matching template.
        Note that the returned reaction will have its kinetics and degeneracy
        set appropriately.

        In order to reverse the reactions that are given in the reverse of the
        direction the family is defined, we need to compute the thermodynamics
        of the reactants and products. For this reason you must also pass
        the `thermoDatabase` to use to generate the thermo data.
        """

        def generateThermoData(species, thermoDatabase):
            thermoData = [thermoDatabase.getThermoData(species)]
            thermoData.sort(key=lambda x: x.getEnthalpy(298))
            return thermoData[0]

        def matchSpeciesToMolecules(species, molecules):
            if len(species) == len(molecules) == 1:
                return species[0].isIsomorphic(molecules[0])
            elif len(species) == len(molecules) == 2:
                if species[0].isIsomorphic(molecules[0]) and species[1].isIsomorphic(molecules[1]):
                    return True
                elif species[0].isIsomorphic(molecules[1]) and species[1].isIsomorphic(molecules[0]):
                    return True
            return False

        reaction = None; template = None

        # Get the indicated reaction family
        try:
            groups = self.families[family].groups
        except KeyError:
            raise ValueError('Invalid value "{0}" for family parameter.'.format(family))

        if all([(isinstance(reactant, Group) or isinstance(reactant, LogicNode)) for reactant in entry.item.reactants]):
            # The entry is a rate rule, containing functional groups only
            # By convention, these are always given in the forward direction and
            # have kinetics defined on a per-site basis
            reaction = Reaction(
                reactants = entry.item.reactants[:],
                products = [],
                kinetics = entry.data,
                degeneracy = 1,
            )
            template = [groups.entries[label] for label in entry.label.split(';')]

        elif (all([isinstance(reactant, Molecule) for reactant in entry.item.reactants]) and
            all([isinstance(product, Molecule) for product in entry.item.products])):
            # The entry is a real reaction, containing molecules
            # These could be defined for either the forward or reverse direction
            # and could have a reaction-path degeneracy

            reaction = Reaction(reactants=[], products=[])
            for molecule in entry.item.reactants:
                reactant = Species(molecule=[molecule])
                reactant.generateResonanceIsomers()
                reactant.thermo = generateThermoData(reactant, thermoDatabase)
                reaction.reactants.append(reactant)
            for molecule in entry.item.products:
                product = Species(molecule=[molecule])
                product.generateResonanceIsomers()
                product.thermo = generateThermoData(product, thermoDatabase)
                reaction.products.append(product)

            # Generate all possible reactions involving the reactant species
            generatedReactions = self.generateReactionsFromFamilies([reactant.molecule for reactant in reaction.reactants], [], only_families=[family])

            # Remove from that set any reactions that don't produce the desired reactants and products
            forward = []; reverse = []
            for rxn in generatedReactions:
                if matchSpeciesToMolecules(reaction.reactants, rxn.reactants) and matchSpeciesToMolecules(reaction.products, rxn.products):
                    forward.append(rxn)
                if matchSpeciesToMolecules(reaction.reactants, rxn.products) and matchSpeciesToMolecules(reaction.products, rxn.reactants):
                    reverse.append(rxn)

            # We should now know whether the reaction is given in the forward or
            # reverse direction
            if len(forward) == 1 and len(reverse) == 0:
                # The reaction is in the forward direction, so use as-is
                reaction = forward[0]
                template = reaction.template
                # Don't forget to overwrite the estimated kinetics from the database with the kinetics for this entry
                reaction.kinetics = entry.data
            elif len(reverse) == 1 and len(forward) == 0:
                # The reaction is in the reverse direction
                # First fit Arrhenius kinetics in that direction
                Tdata = 1000.0 / numpy.arange(0.5, 3.301, 0.1, numpy.float64)
                kdata = numpy.zeros_like(Tdata)
                for i in range(Tdata.shape[0]):
                    kdata[i] = entry.data.getRateCoefficient(Tdata[i]) / reaction.getEquilibriumConstant(Tdata[i])
                kunits = 'm^3/(mol*s)' if len(reverse[0].reactants) == 2 else 's^-1'
                kinetics = Arrhenius().fitToData(Tdata, kdata, kunits, T0=1.0)
                kinetics.Tmin = entry.data.Tmin
                kinetics.Tmax = entry.data.Tmax
                kinetics.Pmin = entry.data.Pmin
                kinetics.Pmax = entry.data.Pmax
                # Now flip the direction
                reaction = reverse[0]
                reaction.kinetics = kinetics
                template = reaction.template
            elif len(reverse) > 0 and len(forward) > 0:
                print 'FAIL: Multiple reactions found for {0!r}.'.format(entry.label)
            elif len(reverse) == 0 and len(forward) == 0:
                print 'FAIL: No reactions found for "%s".' % (entry.label)
            else:
                print 'FAIL: Unable to estimate kinetics for {0!r}.'.format(entry.label)

        assert reaction is not None
        assert template is not None
        return reaction, template


text:
*To Configure this system follow below steps:*

- Install Python-PIP

  $ sudo apt-get install python-pip

- Install python virtaulenv on ubuntu

  $ sudo pip install virtualenvwrapper

- Create python virtaulenv

  $ virtualenv env --no-site-packages

- Activate python virtualenv

  $ source env/bin/activate

- To check the python location

  $ which python

- Install all the required packages

  $ pip install -r requirements.txt

- Go to manage.py file

  $ cd apiss

- Create tables in "apiss" database (please create a database "apiss")

  $ python manage.py migrate

- To Insert Default data

  $ python manage.py loaddata initial_data

- To start django server

  $ python manage.py runserver 0.0.0.0:8000


text:
class ApplicationServicesPropertiesController < ApplicationController

include Engines::Api

  def show
    @application_services_properties = Application.find_by(container_name: application_name).build_application_services_properties
    @application_services_properties.build_application_services
  end

private

  def application_name
    params[:application_name]
  end

  # def application_services_properties_params
  #   params.require(:application_services_properties).permit!
  # end

end


text:
<?php

namespace JavierEguiluz\Bundle\EasyAdminBundle\Search;

use Pagerfanta\Pagerfanta;

/**
 * @author Javier Eguiluz <javier.eguiluz@gmail.com>
 */
class Finder
{
    const MAX_RESULTS = 15;

    /** @var QueryBuilder */
    private $queryBuilder;

    /** @var Paginator */
    private $paginator;

    public function __construct(QueryBuilder $queryBuilder, Paginator $paginator)
    {
        $this->queryBuilder = $queryBuilder;
        $this->paginator = $paginator;
    }

    /**
     * @param array  $entityConfig
     * @param string $searchQuery
     * @param int    $page
     * @param int    $maxResults
     * @param string $sortField
     * @param string $sortDirection
     *
     * @return Pagerfanta
     */
    public function findByAllProperties(array $entityConfig, $searchQuery, $page = 1, $maxResults = self::MAX_RESULTS, $sortField = null, $sortDirection = null, $dqlFilter = null)
    {
        $queryBuilder = $this->queryBuilder->createSearchQueryBuilder($entityConfig, $searchQuery, $sortField, $sortDirection, $dqlFilter);

        return $this->paginator->createOrmPaginator($queryBuilder, $page, $maxResults);
    }
}


text:
layout: page-category
title: "Articles"
date:
modified:
excerpt:
tags: []
image:
  feature: flatirons.png
---
{% for post in site.categories.articles %}
    {% include _home-post.html %}
{% endfor %}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
//
// Whitespace layout package
//

var Container = exports.Container = require('./container').Container;
var GridContainer = exports.GridContainer = require('./gridcontainer').GridContainer;
var Grid = exports.Grid = require('./grid').Grid;
var Item = exports.Item = require('./item').Item;


text:
package org.plantuml.idea;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.event.CaretListener;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.editor.event.EditorEventMulticaster;
import com.intellij.openapi.editor.event.SelectionListener;
import org.jetbrains.annotations.NotNull;
import org.plantuml.idea.preview.listener.PlantUmlCaretListener;
import org.plantuml.idea.preview.listener.PlantUmlDocumentListener;
import org.plantuml.idea.preview.listener.PlantUmlSelectionListener;

public class PlantUmlApplicationComponent implements ApplicationComponent, Disposable {
    private DocumentListener plantUmlDocumentListener = new PlantUmlDocumentListener();
    private CaretListener plantUmlCaretListener = new PlantUmlCaretListener();
    private SelectionListener selectionListener = new PlantUmlSelectionListener();

    public PlantUmlApplicationComponent() {
        PlantUmlApplicationComponent.class.getClassLoader().setDefaultAssertionStatus(false);
    }

    @Override
    public void initComponent() {
        EditorEventMulticaster eventMulticaster = EditorFactory.getInstance().getEventMulticaster();
        eventMulticaster.addDocumentListener(plantUmlDocumentListener, this);
        eventMulticaster.addCaretListener(plantUmlCaretListener, this);
        eventMulticaster.addSelectionListener(selectionListener, this);
    }

    @Override
    public void disposeComponent() {
        EditorEventMulticaster eventMulticaster = EditorFactory.getInstance().getEventMulticaster();
        eventMulticaster.removeDocumentListener(plantUmlDocumentListener);
        eventMulticaster.removeCaretListener(plantUmlCaretListener);
        eventMulticaster.removeSelectionListener(selectionListener);
    }

    @Override
    @NotNull
    public String getComponentName() {
        return "PlantUmlApplicationComponent";
    }

    @Override
    public void dispose() {
    }
}


text:
package com.christy.spcd.wsapi.order;

import org.springframework.stereotype.Component;

@Component
public class OrderAPIHystrix implements OrderApi{

	@Override
	public String orderTest(String client) {
		return "出错了啊啊啊啊";
	}

	@Override
	public String pay(Integer orderId) {
		return "支付失败,请稍后再试";
	}

	@Override
	public String pay2(Integer orderId) {
		return "支付失败,请稍后再试";
	}

}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using MyTypes;
using System;

public enum GunMode
{
    Teleporter = 0,
    Scaler,
    ModeCount
}

public class RaygunComponent : MonoBehaviour {
    #region Variables
    // Raygun //
    [Tooltip("How far the weapon should shoot")]
    public float weaponShootRange = 25;
    [Tooltip("The end of the gun [Empty gameobject]")]
    public Transform gunEnd;
    private Camera fpsCam;      // There should be a better transform reference to use instead of camera, it makes it so if multiple guns are present, there won't be enough transform to instantiate the beacon
    // Raygun //

    // Teleport //
    // TODO: BEACON NEEDS TO BE OBJECT POOLED!!!
    public Beacon beaconProjectile = null;
    private Beacon beacon = null;
    private GameObject lastObject = null;
    // Teleport //

    // Sizer //
    private bool stuck = false;//check if you haved hooked to an object
    private bool canFire = true;

    private LineRenderer laserLine;
    private GameObject currentHit;
    private Color currentColor;
    //where the beam ends [it starts from the center of the screen]
    private Vector3 endPos;
    [SerializeField]
    [Tooltip("Layer to ignore for the beam")]
    private LayerMask beamMask;

    [SerializeField]
    [Tooltip("Layer to ignore for the fit checkers")]
    private LayerMask fitterMask;
    // Sizer //
    #endregion Variables

    #region Monobehaviour
    void Start()
    {
        laserLine = GetComponent<LineRenderer>();
        fpsCam = GetComponentInParent<Camera>();
        if (!fpsCam)
        {
            fpsCam = FindObjectOfType<Camera>();
        }
    }
    #endregion Monobehaviour

    // Gun Modes:
    #region Teleport Beam
    // Primary fire
    public void TeleportBeam()
    {
        if (beacon != null)
        {
            RaycastHit hitInfo;
            InteractMessage msg;

            if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hitInfo, weaponShootRange))
            {
                if (hitInfo.collider.GetComponent<Interactable>())
                {
                    lastObject = hitInfo.collider.gameObject;

                    msg = new InteractMessage(Interaction.TELEPORTING, "Teleport", beacon);
                    lastObject.SendMessage("Interact", msg);
                }
            }
        }
        else
        {
            Debug.Log("Beacon needs to be fired first before teleporting an object.");
        }
    }

    // Secondary fire
    public void DeployBeacon()
    {
        if (beacon != null)
        {
            Destroy(beacon.gameObject);    // Create cool destruction animation call that before destruction
        }

        beacon = Instantiate(beaconProjectile, fpsCam.transform.position, fpsCam.transform.rotation) as Beacon;
    }

    public void RotateHologram(bool onX)
    {
        if (beacon != null)
        {
            if (onX)
            {
                beacon.RotateOnXAxis();
            }
            else
            {
                beacon.RotateOnYAxis();
            }
        }
    }

    public void DisplayHologram()
    {
        if (beacon != null)
        {
            RaycastHit hitInfo;
            InteractMessage msg;

            if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hitInfo, weaponShootRange))
            {
                if (hitInfo.collider.GetComponent<Interactable>())
                {
                    lastObject = hitInfo.collider.gameObject;
                    msg = new InteractMessage(Interaction.TELEPORTING, "HitBegin", beacon);

                    lastObject.SendMessage("Interact", msg);
                }
                else
                {
                    StopDisplayingHologram();
                }
            }
        }
    }

    private void StopDisplayingHologram()
    {
        if (beacon != null)
        {
            if (lastObject != null)
            {
                InteractMessage msg;
                msg = new InteractMessage(Interaction.TELEPORTING, "HitEnd");
                lastObject.SendMessage("Interact", msg);
                lastObject = null;
            }
        }
    }

    // Still unused feature (for later)
    public void DestroyBeacon()
    {
        if (beacon != null)
        {
            Destroy(beacon.gameObject);
            beacon = null;
        }
    }
    #endregion Teleport Beam

    #region Scaler Beam
    public void ShootRay(string rayType)
    {
        Vector3 camCenter = fpsCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0.0f));
        Vector3 rayOrigin = camCenter;
        RaycastHit normalhit;
        //lines 'resting' position
        laserLine.SetPosition(0, gunEnd.position);
        laserLine.SetPosition(1, camCenter);
        if (!stuck)
        {
            if (Physics.Raycast(rayOrigin, fpsCam.transform.forward, out normalhit, weaponShootRange))
            {
                Debug.DrawRay(rayOrigin, fpsCam.transform.forward * weaponShootRange, Color.red);
                if (normalhit.transform.gameObject.GetComponent<ScaleComponent>())
                {
                    stuck = true;
                    currentHit = normalhit.transform.gameObject;
                    //first set the raycast to the pos of object [lock it]
                    currentColor = currentHit.GetComponent<Renderer>().material.color;
                    currentHit.GetComponent<Renderer>().material.color = new Color(0, 0, 255);
                    laserLine.enabled = true;
                }
            }
            else
            {
                print("too far");
            }
        }
        else
        {
            //if you are hooked to an object, draw line to that object
            endPos = currentHit.transform.GetComponent<Renderer>().bounds.center;
            laserLine.SetPosition(1, endPos);
            this.transform.Rotate(new Vector3(0, 0, 60 * Time.deltaTime));
            Debug.DrawLine(rayOrigin, endPos, Color.green);
            if (Physics.Linecast(rayOrigin, endPos, out normalhit, beamMask))
            {
                if (normalhit.collider.gameObject != currentHit)
                {
                    print(normalhit.collider.gameObject);
                    print("blocked");
                    canFire = false;
                }
                else
                {
                    //send scale msg to obj
                    InteractMessage sendMsg = new InteractMessage(Interaction.SCALING, "");
                    if (rayType == "growing")
                    {
                        sendMsg.msg = "GROW";
                        currentHit.SendMessage("Interact", sendMsg);
                    }
                    else if (rayType == "shrinking")
                    {
                        sendMsg.msg = "SHRINK";
                        currentHit.SendMessage("Interact", sendMsg);
                    }
                }
            }
        }
    }

    public void StopScaling()
    {
        if (!canFire)
        {
            laserLine.enabled = false;
            if (stuck || !canFire)
            {
                InteractMessage sendMsg = new InteractMessage(Interaction.SCALING, "STOPGROW");
                currentHit.SendMessage("Interact", sendMsg);
                sendMsg.msg = "STOPSHRINK";
                currentHit.SendMessage("Interact", sendMsg);

                currentHit.GetComponent<Renderer>().material.color = currentColor;
                stuck = false;
                currentHit = null;
                canFire = true;
            }
        }
    }
    #endregion Scaler Beam
}


text:
Take a screenshot of the map.

![Image of take screenshot](TakeScreenshot.png)

## How to use the sample

Click the "Take Screenshot" button to export the image. In the file chooser that opens, set a file name and location to save the image.

## How it works

1. Call `mapView.exportImageAsync()` and set it to a `ListenableFuture<Bitmap>`.
2. On done, call `get()` on the `ListenableFuture<Image>` and save it to the device.

## Relevant API

* ArcGISMap
* MapView

## Tags

capture, export, image, print, screen capture, screenshot, share, shot


text:
package pl.touk.nussknacker.ui.config.processtoolbar

import io.circe.{Decoder, Encoder}
import pl.touk.nussknacker.ui.config.processtoolbar.ToolbarButtonConfigType.ToolbarButtonType

case class ToolbarButtonConfig(
  `type`: ToolbarButtonType,
  name: Option[String],
  title: Option[String],
  icon: Option[String],
  url: Option[String],
  hidden: Option[ToolbarCondition],
  disabled: Option[ToolbarCondition]
) {

  if (ToolbarButtonConfigType.requiresNameParam(`type`)) {
    require(name.isDefined, s"Button ${`type`} requires param: 'name'.")
  }

  if (ToolbarButtonConfigType.requiresUrlParam(`type`)) {
    require(url.isDefined, s"Button ${`type`} requires param: 'url'.")
  } else {
    require(url.isEmpty, s"Button ${`type`} doesn't contain param: 'url'.")
  }
}

object ToolbarButtonConfigType extends Enumeration {
  implicit val typeEncoder: Encoder[ToolbarButtonType] = Encoder.encodeEnumeration(ToolbarButtonConfigType)
  implicit val typeDecoder: Decoder[ToolbarButtonType] = Decoder.decodeEnumeration(ToolbarButtonConfigType)

  type ToolbarButtonType = Value

  private lazy val customButtons: List[ToolbarButtonType] = List(
    CustomAction,
    CustomLink
  )

  private lazy val urlButtons: List[ToolbarButtonType] = List(
    CustomLink
  )

  val ProcessSave: Value = Value("process-save")
  val ProcessCancel: Value = Value("process-cancel")
  val ProcessDeploy: Value = Value("process-deploy")

  val EditUndo: Value = Value("edit-undo")
  val EditRedo: Value = Value("edit-redo")
  val EditCopy: Value = Value("edit-copy")
  val EditPaste: Value = Value("edit-paste")
  val EditDelete: Value = Value("edit-delete")
  val EditLayout: Value = Value("edit-layout")

  val ProcessProperties: Value = Value("process-properties")
  val ProcessCompare: Value = Value("process-compare")
  val ProcessMigrate: Value = Value("process-migrate")
  val ProcessImport: Value = Value("process-import")
  val ProcessJSON: Value = Value("process-json")
  val ProcessPDF: Value = Value("process-pdf")

  val ProcessArchiveToggle: Value = Value("process-archive-toggle")
  val ProcessArchive: Value = Value("process-archive")
  val ProcessUnarchive: Value = Value("process-unarchive")

  val TestFromFile: Value = Value("test-from-file")
  val TestGenerate: Value = Value("test-generate")
  val TestCounts: Value = Value("test-counts")
  val TestHide: Value = Value("test-hide")

  val ViewZoomIn: Value = Value("view-zoom-in")
  val ViewZoomOut: Value = Value("view-zoom-out")
  val ViewReset: Value = Value("view-reset")

  val CustomLink: Value = Value("custom-link")
  val CustomAction: Value = Value("custom-action")

  def requiresNameParam(`type`: ToolbarButtonType): Boolean =
    customButtons.contains(`type`)

  def requiresUrlParam(`type`: ToolbarButtonType): Boolean =
    urlButtons.contains(`type`)

}


text:
namespace cpr {

class Session {
  public:
    Session();
    ~Session();

    void SetUrl(const Url& url);
    void SetParameters(const Parameters& parameters);
    void SetParameters(Parameters&& parameters);
    void SetHeader(const Header& header);
    void SetTimeout(const Timeout& timeout);
    void SetAuth(const Authentication& auth);
    void SetDigest(const Digest& auth);
    void SetPayload(Payload&& payload);
    void SetPayload(const Payload& payload);
    void SetProxies(Proxies&& proxies);
    void SetProxies(const Proxies& proxies);
    void SetMultipart(Multipart&& multipart);
    void SetMultipart(const Multipart& multipart);
    void SetRedirect(const bool& redirect);
    void SetMaxRedirects(const MaxRedirects& max_redirects);
    void SetCookies(const Cookies& cookies);
    void SetBody(Body&& body);
    void SetBody(const Body& body);

    // Used in templated functions
    void SetOption(const Url& url);
    void SetOption(const Parameters& parameters);
    void SetOption(Parameters&& parameters);
    void SetOption(const Header& header);
    void SetOption(const Timeout& timeout);
    void SetOption(const Authentication& auth);
    void SetOption(const Digest& auth);
    void SetOption(Payload&& payload);
    void SetOption(const Payload& payload);
    void SetOption(Proxies&& proxies);
    void SetOption(const Proxies& proxies);
    void SetOption(Multipart&& multipart);
    void SetOption(const Multipart& multipart);
    void SetOption(const bool& redirect);
    void SetOption(const MaxRedirects& max_redirects);
    void SetOption(const Cookies& cookies);
    void SetOption(Body&& body);
    void SetOption(const Body& body);

    Response Delete();
    Response Get();
    Response Head();
    Response Options();
    Response Patch();
    Response Post();
    Response Put();

  private:
    class Impl;
    std::unique_ptr<Impl> pimpl_;
};

} // namespace cpr

#endif


text:
import sciunit
from sciunit import Model, Test, Score

import quantities
import os

class SampleScore(Score):
    """For testing purposes"""
    @classmethod
    def compute(cls):
        return SampleScore(1.0)

class SampleTest(Test):
    """For testing purposes"""

    score_type = SampleScore

    def __init__(self,
                 observation={},
                 name="Sample Test"):
        required_capabilities = ()
        sciunit.Test.__init__(self, observation, name)

    def validate_observation(self, observation):
        pass

    def generate_prediction(self, model, verbose=False):
        return 1.0

    def compute_score(self, observation, prediction, verbose=False):
        return SampleScore.compute()

class SampleModel(Model):
    """For testing purposes"""
    def __init__(self, name = "Test Model", model_uuid="", model_version="", model_instance_uuid=""):
        sciunit.Model.__init__(self, name=name)
        self.model_uuid = model_uuid
        self.model_version = model_version
        self.model_instance_uuid = model_instance_uuid


text:
package com.intellij.openapi.editor.ex;

import com.intellij.openapi.editor.event.DocumentListener;

import java.util.Comparator;

/**
 * @author max
 */
public interface PrioritizedDocumentListener extends DocumentListener {
  /**
   * Comparator that sorts {@link DocumentListener} objects by their {@link PrioritizedDocumentListener#getPriority() priorities} (if any).
   *

   * The rules are:
   *

   *

   *
{@link PrioritizedDocumentListener} has more priority than {@link DocumentListener};

   *
{@link PrioritizedDocumentListener} with lower value returned from {@link #getPriority()} has more priority than another;

   *

   *

   */
  Comparator<? super DocumentListener> COMPARATOR = new Comparator<Object>() {
    public int compare(Object o1, Object o2) {
      return getPriority(o1) - getPriority(o2);
    }

    private int getPriority(Object o) {
      if (o instanceof PrioritizedDocumentListener) return ((PrioritizedDocumentListener)o).getPriority();
      return Integer.MAX_VALUE;
    }
  };

  int getPriority();
}


text:
// createthreads test
//   create & exit a whole bunch of threads
//   tests for memory, thread and resource recycling

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

//const int NC_MAX_THREADS = 512;

const int kJoinLoopCount = 2500;
const int kDelayedJoinInnerLoopCount = (NC_MAX_THREADS - 1);
const int kDelayedJoinLoopCount = 20;
const int kDetachLoopCount = (NC_MAX_THREADS - 1);
int g_create;

void* ThreadEntry(void *userdata) {
  // do nothing and immediately exit
  return userdata;
}

void Fail() {
  printf("Main: Unable to create thread!\n");
  printf("Main: [After %d calls to pthread_create()]\n", g_create);
  printf("TEST FAILED\n");
  exit(-1);
}

/* creates and waits via pthread_join() for thread to exit */
void Test0() {
  pthread_t thread_id;
  void *thread_ret;
  int p = pthread_create(&thread_id, NULL, ThreadEntry, NULL);
  if (0 != p)
    Fail();
  else
    g_create++;
  /* wait for thread to exit */
  pthread_join(thread_id, &thread_ret);
}

/* creates, but does not wait for thread to exit */
void Test1a(int i, pthread_t *thread_id) {
  int p = pthread_create(&thread_id[i], NULL, ThreadEntry, NULL);
  if (0 != p)
    Fail();
  else
    g_create++;
  /* join up after a large block of threads created */
}

void Test1() {
  pthread_t thread_id_array[kDelayedJoinInnerLoopCount];
  void *thread_ret;
  for (int i = 0; i < kDelayedJoinInnerLoopCount; ++i)
    Test1a(i, thread_id_array);
  for (int i = 0; i < kDelayedJoinInnerLoopCount; ++i) {
    pthread_join(thread_id_array[i], &thread_ret);
  }
}

/* creates as detached thread, cannot join */
void Test2() {
  pthread_t thread_id;
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  int p = pthread_create(&thread_id, NULL, ThreadEntry, NULL);
  if (0 != p)
    Fail();
  else
    g_create++;
  /* cannot join on detached thread */
}

int main(int argc, char **argv) {

#if 0
  // todo: enable for nacl when defined in limits.h
  printf("Max threads PTHREAD_THREADS_MAX: %d\n", PTHREAD_THREADS_MAX);
  printf("Max threads sysconf(_SC_THREAD_THREADS_MAX): %d\n", sysconf(_SC_THREAD_THREADS_MAX));
#else
  printf("Max threads NC_THREADS_MAX: %d\n", NC_MAX_THREADS);
#endif

  printf("Test0() creating & joining threads...\n");
  for (int i = 0; i < kJoinLoopCount; ++i)
    Test0();
  printf("Test0() completed\n");

  printf("Test1() create batch & join batch...\n");
  for (int i = 0; i < kDelayedJoinLoopCount; ++i)
    Test1();
  printf("Test1() completed\n");

  printf("Test2() create detached threads...\n");
  for (int i = 0; i < kDetachLoopCount; ++i)
    Test2();
  printf("Test2() completed\n");
  printf("%d calls to pthread_create() were made\n", g_create);

  printf("TEST PASSED\n");
  return 0;
}


text:
using Autofac;

namespace TrafficPark.Builder
{
    public static class ApplicationProperties
    {
        public static bool IsInTest { get; set; }

        public static IContainer Container { get; set; }
    }
}


text:
#include "sf_snort_plugin_api.h"
#include "sf_snort_packet.h"

#include "so-util.h"

//#define DEBUG
#ifdef DEBUG
#define DEBUG_SO(code) code
#else
#define DEBUG_SO(code)
#endif

/* declare detection functions */
int rule23847eval(void *p);

/* declare rule data structures */
/* flow:established, to_client; */
static FlowFlags rule23847flow0 =
{
    FLOW_ESTABLISHED|FLOW_TO_CLIENT
};

static RuleOption rule23847option0 =
{
    OPTION_TYPE_FLOWFLAGS,
    {
        &rule23847flow0
    }
};
// content:"|FF|SMB|25|", depth 0, fast_pattern;
static ContentInfo rule23847content1 =
{
    (uint8_t *) "|FF|SMB|25 00 00 00 00|", /* pattern (now in snort content format) */
    9, /* depth */
    4, /* offset */
    CONTENT_FAST_PATTERN|CONTENT_BUF_NORMALIZED, /* flags */
    NULL, /* holder for boyer/moore PTR */
    NULL, /* more holder info - byteform */
    0, /* byteform length */
    0 /* increment length*/
};

static RuleOption rule23847option1 =
{
    OPTION_TYPE_CONTENT,
    {
        &rule23847content1
    }
};
// content:"|EA 00|", offset 47, depth 2, relative;
static ContentInfo rule23847content2 =
{
    (uint8_t *) "|EA 00|", /* pattern (now in snort content format) */
    2, /* depth */
    47, /* offset */
    CONTENT_RELATIVE|CONTENT_BUF_NORMALIZED, /* flags */
    NULL, /* holder for boyer/moore PTR */
    NULL, /* more holder info - byteform */
    0, /* byteform length */
    0 /* increment length*/
};

static RuleOption rule23847option2 =
{
    OPTION_TYPE_CONTENT,
    {
        &rule23847content2
    }
};

/* references for sid 23847 */
/* reference: cve "2012-1667"; */
static RuleReference rule23847ref1 =
{
    "cve", /* type */
    "2012-1850" /* value */
};

/* reference: url "technet.microsoft.com/en-us/security/bulletin/MS12-054"; */
static RuleReference rule23847ref2 =
{
    "url", /* type */
    "technet.microsoft.com/en-us/security/bulletin/MS12-054" /* value */
};

static RuleReference *rule23847refs[] =
{
    &rule23847ref1,
    &rule23847ref2,
    NULL
};
/* metadata for sid 23847 */
/* metadata:service netbios-ssn; */
static RuleMetaData rule23847service1 =
{
    "service netbios-ssn"
};

static RuleMetaData *rule23847metadata[] =
{
    &rule23847service1,
    NULL
};

RuleOption *rule23847options[] =
{
    &rule23847option0,
    &rule23847option1,
    &rule23847option2,
    NULL
};

Rule rule23847 = {
   /* rule header, akin to => tcp any any -> any any */
   {
       IPPROTO_TCP, /* proto */
       "$EXTERNAL_NET", /* SRCIP     */
       "[139,445]", /* SRCPORT   */
       0, /* DIRECTION */
       "$HOME_NET", /* DSTIP     */
       "any", /* DSTPORT   */
   },
   /* metadata */
   {
       3,  /* genid */
       23847, /* sigid */
       3, /* revision */
       "attempted-admin", /* classification */
       0,  /* hardcoded priority XXX NOT PROVIDED BY GRAMMAR YET! */
       "NETBIOS MS-RAP NetServerEnum2 read access violation attempt",     /* message */
       rule23847refs, /* ptr to references */
       rule23847metadata
   },
   rule23847options, /* ptr to rule options */
   &rule23847eval, /* use the built in detection function */
   0 /* am I initialized yet? */
};

/* detection functions */
int rule23847eval(void *p) {
    const uint8_t *cursor_normal = 0;
    SFSnortPacket *sp = (SFSnortPacket *) p;
    const uint8_t *end_of_payload = 0;
    const uint8_t *beg_of_payload = 0;
    const uint8_t *beg_of_servers = 0;
    const uint8_t *start_of_smb = 0;

    int16_t converter = 0;
    int16_t server_comment = 0;
    int16_t server_comment_position = 0;

    uint32_t entries = 0;
    uint32_t netbios_message_length = 0;

    int i;

    if(sp == NULL)
        return RULE_NOMATCH;

    if(sp->payload == NULL)
        return RULE_NOMATCH;

    // flow:established, to_client;
    if (checkFlow(p, rule23847options[0]->option_u.flowFlags) <= 0 )
      return RULE_NOMATCH;

    // Verify we are looking at an SMB Trans (0x25) response.
    // Verify the SMB Request was STATUS_SUCCESS (0x00000000)
    // content:"|FF|SMB|25 00 00 00 00|", depth 0, fast_pattern;
    if (contentMatch(p, rule23847options[1]->option_u.content, &cursor_normal) <= 0)
      return RULE_NOMATCH;

    // Verify LANMAN protocol is reporting additional data available.
    // content:"|EA 00|", offset 47, depth 2, relative;
    if(contentMatch(p, rule23847options[2]->option_u.content, &cursor_normal) <= 0)
      return RULE_NOMATCH;

    // Get the beginning of payload and end of payload positions.
    if(getBuffer(sp, CONTENT_BUF_NORMALIZED, &beg_of_payload, &end_of_payload) <= 0)
      return RULE_NOMATCH;

    start_of_smb = beg_of_payload + 4;  // Beginning of 9-byte content match

    netbios_message_length = read_big_16(beg_of_payload + 2); // 2 byte size field
    DEBUG_SO(fprintf(stderr,"\nnetbios_message_length: %d\n", netbios_message_length);)
    DEBUG_SO(fprintf(stderr, "start_of_smb + netbios_message_length: %p\n", start_of_smb + netbios_message_length);)

    // Verify we have data to read for mutiplier and start of servers field.
    // remember, we are after the |EA 00| match above for LANMAN protocol
    if((cursor_normal + 29) > end_of_payload)
      return RULE_NOMATCH;

    // Read in the mutiplier (called "Convert" in the protocol) we will use
    // this value later to calculate the indicated server comment position.
    converter = read_little_16(cursor_normal);
    DEBUG_SO(fprintf(stderr,"converter: %d\n",converter);)
    cursor_normal += 2;

    // Account for default converter offset
    // observed in live MS-RAP traffic
    if(converter == 0)
      converter = 0x45;

    // Read in the server entry count.
    entries = read_little_16(cursor_normal);
    DEBUG_SO(fprintf(stderr,"number of entries: %d\n",entries);)

    // Store the position of the servers entry array. We will use
    // this later to calculate the indicated server comment position.
    // Note we do not increment cursor_normal because it turns out we are
    // perfectly lined up for reading what we need already.
    beg_of_servers = cursor_normal + 4;

    // Now we need to loop through each entry in the server entry array to check
    // for the vulnerability condition i.e. if the indicated server comment position
    // is beyond the SMB message length.

    // Limit the number of checks we'll do
    if(entries > 20)
       entries = 20;

    for(i = 0; i < entries; i++) {

      // Verify we have a server comment position (2 byte field) to read.
      if((cursor_normal + 27) > end_of_payload)
        return RULE_NOMATCH;

      DEBUG_SO(fprintf(stderr,"Entry: %d\n", i+1);)

      // Set the cursor to the server comment field.
      cursor_normal += 26; // each record is 26 bytes long.

      // Read the server comment base position.
      server_comment = read_little_16(cursor_normal);
      DEBUG_SO(fprintf(stderr, "server_comment: %d\n", server_comment);)

      // Calculate the server comment position relative to the beginning of the server entry array.
      server_comment_position = server_comment - converter;
      DEBUG_SO(fprintf(stderr, "beg_of_servers + server_comment_position > start_of_smb + netbios_message_length ?");)
      DEBUG_SO(fprintf(stderr, " %p > %p\n", (beg_of_servers + server_comment_position), (start_of_smb + netbios_message_length));)

      // If the absolute server comment position (beginning of servers array + relative server comment position)
      // is beyond the smb message length the vulnerability condition has been met.
      if((beg_of_servers + server_comment_position) > (start_of_smb + netbios_message_length))
        return RULE_MATCH;
    }

    return RULE_NOMATCH;
}
/*
Rule *rules[] = {
    &rule23847,
    NULL
};
*/


text:
package picasso.utils.tools.armc

import picasso.model.integer._
import java.io._
import scala.collection.GenSeq
import picasso.utils._
import picasso.graph._

object ARMCPrinter extends PrologLikePrinter {

  protected def loc(pc: Option[String], vars: Seq[Variable])(implicit writer: BufferedWriter) {
    val pcString = pc match {
      case Some(s) => "pc(" + asLit(s) + ")"
      case None => "_"
    }
    val data = vars.map(asVar).mkString("",", ","")
    writer.write("p("+ pcString +", data("+ data +"))")
  }

  protected def loc(pc: String, vars: Seq[Variable])(implicit writer: BufferedWriter) {
    loc(Some(pc), vars)
  }

  protected def var2names(vars: Seq[Variable])(implicit writer: BufferedWriter) {
    writer.write("var2names( ")
    loc(None, vars)
    writer.write(", [")
    writer.write(vars.map(v => "(" + asVar(v) + ", '" + v.name + "')" ).mkString("",", ",""))
    writer.write("]).")
    writer.newLine
  }

  protected def preds(vars: Seq[Variable])(implicit writer: BufferedWriter) {
    writer.write("preds( ")
    loc(None, vars)
    writer.write(", []).")
    writer.newLine
  }

  protected def start(pc: String)(implicit writer: BufferedWriter) {
    writer.write("start( pc(" + asLit(pc) + ")).")
    writer.newLine
  }

  protected def transPreds(vars: Seq[Variable], prog: Program)(implicit writer: BufferedWriter) {
    //TODO namedTPreds
    val vars2 = vars map primeVar
    writer.write("trans_preds(")
    writer.newLine
    writer.write("  ")
    loc(None, vars)
    writer.write(",  ")
    writer.newLine
    writer.write("  ")
    loc(None, vars2)
    writer.write(",  ")
    writer.newLine
    writer.write("  [")
    //automatically generated preds
    val genreatedPreds =
      if (Config.makeTPreds) {
        val preds = prog.candidateRankingFcts
        preds.iterator.flatMap( varSet => {
          val sum1 = varSet.reduceLeft[Expression](Plus(_,_))
          val sum2 = varSet.map(primeVar).reduceLeft[Expression](Plus(_,_))
          val c1 = printCondition( Lt(sum2, sum1) )
          val c2 = printCondition( Eq(sum2, sum1) )
          Seq(c1, c2)
        } )
      } else {
        Nil.iterator
      }
    //preds given by user
    val namedPreds =
      Config.namedTPreds.iterator.flatMap( prefixes => {
        val needed = vars.filter(v => prefixes exists v.name.startsWith)
        if (!needed.isEmpty) {
          val sum1 = needed.reduceLeft[Expression](Plus(_,_))
          val sum2 = needed.map(primeVar).reduceLeft[Expression](Plus(_,_))
          val c1 = printCondition( Lt(sum2, sum1) )
          val c2 = printCondition( Eq(sum2, sum1) )
          Seq(c1, c2)
        } else Nil
      })
    //generic TPreds about individual variables
    val varPreds = vars.iterator.flatMap( v => Seq( Eq(Constant(0), primeVar(v)), Leq(Constant(0), primeVar(v)), Lt(primeVar(v), v), Eq(primeVar(v), v) ) map printCondition)
    //all preds
    val allPreds = genreatedPreds ++ namedPreds ++ varPreds
    writer.write(allPreds.mkString(" ",",\n    ","\n"))
    writer.write("  ]).")
    writer.newLine
  }

  protected def cutpoints(p: Program)(implicit writer: BufferedWriter) {
    val trs = p.transitions
    //find all the cycles in the graph (induced cycles generate the complete cycle space)
    //then set hitting problem (combinatorial optimisation) (can we do is as linear algebra in the cycle space or only as ILP ?)
    val cfa = DiGraph[GT.ULGT{type V = String}](trs.map(t => (t.sourcePC, t.targetPC)).seq)
    //TODO considering all the elementaryCycles is sufficient, but not necessary. We can do better and consider less cycles
    val cycles = cfa.elementaryCycles
    val setsToHit = cycles.map( _.states.toSet )
    //for the moment, use a greedy algorithm ...
    def greedy(candidate: Set[String], toCover: Seq[Set[String]], acc: Set[String]): Set[String] = {
      if (candidate.isEmpty || toCover.isEmpty) {
        assert(toCover.isEmpty)
        acc
      } else {
        val best = candidate.maxBy( x => toCover.filter(_ contains x).length )
        val toCover2 = toCover filterNot (_ contains best)
        greedy(candidate - best, toCover2, acc + best)
      }
    }
    val cutpoints = greedy(cfa.vertices, setsToHit, Set())
    for (pc <- cutpoints) {
        writer.write("cutpoint(pc(" + asLit(pc) + ")).")
        writer.newLine
    }
  }

  protected def r(t: Transition, idx: Int, vars: Seq[Variable])(implicit writer: BufferedWriter) {
    val vars2 = vars map primeVar
    val frame = vars.filterNot( t.range(_) ).toList
    //val additionalCstr = frame.map(v => Eq(v, primeVar(v)))
    val additionalCstr = frame.map(v => Eq(primeVar(v), Constant(0) ))
    val pre = vars.iterator.map( v => (v,v) ).toMap
    val post = vars.iterator.map( v => (v,primeVar(v)) ).toMap
    val subst = t.substForRelation(pre, post)
    val relation = And(Condition.alpha(t.relation, subst) :: additionalCstr)
    writer.write("% " + t.comment); writer.newLine
    writer.write("r(  ")
    loc(t.sourcePC, vars)
    writer.write(",")
    writer.newLine
    writer.write("    ")
    loc(t.targetPC, vars2)
    writer.write(",")
    writer.newLine
    writer.write("    [ ")
    writer.write(printCondition(relation))
    writer.write(" ],")
    writer.newLine
    writer.write("    [], " + idx + ")." )
  }

  def apply(implicit writer: BufferedWriter, prog: Program, withPreds: Boolean = true) {
    val vars = prog.variables.toSeq
    writer.write(preamble); writer.newLine
    var2names(vars); writer.newLine
    preds(vars); writer.newLine
    if (withPreds) { transPreds(vars, prog); writer.newLine }
    start(prog.initialPC)
    cutpoints(prog); writer.newLine
    for ( (t, idx) <- prog.transitions.seq.zipWithIndex ) {
      r(t, idx, vars)
      writer.newLine
    }
    writer.flush
  }

  protected val preamble = """% BEGIN FIXED PREAMBLE
:- multifile r/5,implicit_updates/0,var2names/2,preds/2,trans_preds/3,
cube_size/1,start/1,error/1,refinement/1,cutpoint/1,invgen_template/2,
invgen_template/1,cfg_exit_relation/1,stmtsrc/2,strengthening/2,globals/3,
bound_var/2,bounding_vars/2,transition_access/2,atomic/3.
refinement(inter).
cube_size(1).
% END FIXED PREAMBLE
"""

}


text:
<?php
/*
 You will need your own sql_login.php file that includes $db_username, $db_password, $db_hostname, and $db_database.
*/
require_once 'sql_login.php';

$reqIndex = 0;
if (isset($_GET['index'])) {
	if (is_numeric($_GET['index'])) {
		$reqIndex = $_GET['index'];
	}
}

try {
        // Establish a connection to the SQL database
        $server = new PDO("mysql:host=$db_hostname;dbname=$db_database;charset=utf8", "$db_username", "$db_password");
        $server->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
        $error = "Failed to connect to the database.";
}

$stmt = $server->query("SELECT * FROM messages ORDER BY date ASC");
$rows = $stmt->fetchAll();
$rowCount = $stmt->rowCount();
if ($reqIndex < $rowCount && $reqIndex >= 1) {
	$index = $reqIndex;
} else {
	$index = $rowCount;
}

// This is the format of the message that msnger.ino understands when parsing messages
echo "%^" . $index . "/" . $rowCount . "^" . $rows[$index-1][1] . ":" . $rows[$index-1][0] . "%";

$server = null;
?>


text:
local Gamestate = require 'vendor/gamestate'
local anim8 = require 'vendor/anim8'
local window = require 'window'
local fonts = require 'fonts'
local timer = require 'vendor/timer'
local Prompt = require 'prompt'
local Dialog = require 'dialog'
local camera = require 'camera'
local state = Gamestate.new()
local sound = require 'vendor/TEsound'
local cardutils = require 'cardutils'

function state:init()
    math.randomseed( os.time() )

    self.table = love.graphics.newImage( 'images/cards/card_table_poker.png' )

    self.cardSprite = love.graphics.newImage('images/cards/cards.png' )
    self.card_width = 38
    self.card_height = 55
    self.cardbacks = 6

    self.chipSprite = love.graphics.newImage('images/cards/chips.png' )
    self.chip_width = 13
    self.chip_height = 13
    self.chips = {
        -- black ( $100 )
        love.graphics.newQuad( self.chip_width, self.chip_height, self.chip_width, self.chip_height, self.chipSprite:getWidth(), self.chipSprite:getHeight() ),
        -- green ( $25 )
        love.graphics.newQuad( 0, self.chip_height * 2, self.chip_width, self.chip_height, self.chipSprite:getWidth(), self.chipSprite:getHeight() ),
        -- blue ( $10 )
        love.graphics.newQuad( 0, self.chip_height, self.chip_width, self.chip_height, self.chipSprite:getWidth(), self.chipSprite:getHeight() ),
        -- red ( $5 )
        love.graphics.newQuad( 0, 0, self.chip_width, self.chip_height, self.chipSprite:getWidth(), self.chipSprite:getHeight() ),
        -- white ( $1 )
        love.graphics.newQuad( self.chip_width, 0, self.chip_width, self.chip_height, self.chipSprite:getWidth(), self.chipSprite:getHeight() )
    }

    self.card_queue = {}

    self.max_card_room = 227
    self.width_per_card = 45

    -- to avoid crazy poker hands
    self.decks_to_use = 1

    self.card_speed = 0.5

    self.options_arrow = love.graphics.newImage( 'images/menu/tiny_arrow.png' )

    self.options = {
        { name = 'DRAW', action = 'poker_draw' },
        { name = 'DEAL', action = 'deal_hand' },
        { name = 'BET +', action = function() if self.bet < self.player.money then self.bet = self.bet + 1 end end },
        { name = 'BET -', action = function() if self.bet > 1 then self.bet = self.bet - 1 end end },
        { name = 'QUIT', action = 'quit', active = true },
    }
    self.selection = 2

    self.bet = 2

    self.horizontal_selection = 0
end

function state:enter(previous, player, screenshot)
    sound.playMusic( "tavern" )

    fonts.set( 'big' )

    self.previous = previous
    self.screenshot = screenshot

    self.prompt = nil

    self.player = player

    self:init_table()
    self:deal_menu()

    self.cardback_idx = math.random( self.cardbacks ) - 1

    self.cardback = love.graphics.newQuad( self.cardback_idx * self.card_width, self.card_height * 4, self.card_width, self.card_height, self.cardSprite:getWidth(), self.cardSprite:getHeight() )

    self.chip_x = 138+36 + camera.x
    self.chip_y = 208+33 + camera.y

    self.center_x = ( window.width / 2 ) + camera.x
    self.center_y = ( window.height / 2 ) +  camera.y
    self.dealer_stack_x = 356+36 + camera.x
    self.dealer_stack_y = 37+33 + camera.y

    self.options_x = 360+36 + camera.x
    self.options_y = 135+33 + camera.y
    self.selection = 2

    self.bet = 2

    self.horizontal_selection = 0
end

function state:leave()
end

function state:keypressed( button, player )
    if self.prompt then
        self.prompt:keypressed( button )
    else

        if button == 'JUMP' and self.options[self.selection + 1].name == 'QUIT' then
            self.prompt = Prompt.new("Are you sure you want to exit?", function(result)
                if result == 'Yes' then
                    Gamestate.switch(self.previous)
                else
                    self.prompt = nil
                end
            end )
            return
        end

        if button == 'JUMP' then
            if(self.horizontal_selection == 0) then
                local action = self.options[self.selection + 1].action
                if(type(action) == 'string') then
                    self[action](self)
                else --function
                    action()
                end
            else
                self.player_cards[self.horizontal_selection].raised = not self.player_cards[self.horizontal_selection].raised
            end
        end

        if self.options[1].active then
            if button == 'LEFT' then
                self.horizontal_selection = (self.horizontal_selection + 1) % 6
            elseif button == 'RIGHT' then
                self.horizontal_selection = (self.horizontal_selection - 1) % 6
            end
        end

        if button == 'UP' then
            repeat
                self.selection = (self.selection - 1) % #self.options
            until self.options[ self.selection + 1 ].active
        elseif button == 'DOWN' then
            repeat
                self.selection = (self.selection + 1) % #self.options
            until self.options[ self.selection + 1 ].active
        end

    end
end

function state:game_menu()
        -- fix the menu
        self.selection = 0
        self.options[ 1 ].active = true
        self.options[ 2 ].active = false
        self.options[ 3 ].active = false
        self.options[ 4 ].active = false
        self.horizontal_selection = 1
end

function state:deal_menu()
        -- fix the menu
        self.selection = 1
        self.options[ 1 ].active = false
        self.options[ 2 ].active = true
        self.options[ 3 ].active = true
        self.options[ 4 ].active = true
        self.horizontal_selection = 0
end

function state:no_menu()
        -- fix the menu
        self.selection = 4
        self.options[ 1 ].active = false
        self.options[ 2 ].active = false
        self.options[ 3 ].active = false
        self.options[ 4 ].active = false
        self.horizontal_selection = 0
end

function state:update(dt)
    timer.update(dt)
    if self.prompt then self.prompt:update(dt) end
    self.cards_moving = self:update_cards(dt)
end

function state:update_cards(dt)
    if(#self.card_queue > 0 and self.card_queue.asynchronous) then
        moves = {}
        for i = 1, #self.card_queue do
            table.insert(moves, self:move_card( self.card_queue[i], dt ))
        end
        for i = #self.card_queue, 1 do
            if(not moves[i]) then
                table.remove(moves, i)
            end
        end
    elseif(#self.card_queue > 0) then
        if not self:move_card( self.card_queue[1], dt ) then
            table.remove(self.card_queue, 1)
        end
    else
        if self.card_complete_callback then
            self.card_complete_callback()
        end
    end
end

function state:move_card( card, dt )
    moved = false
    if card.move_idx < self.card_speed then
        moved = true
        card.move_idx = card.move_idx + dt
    else
        card.move_idx = self.card_speed
    end

    if card.face_up then
        if card.flip_idx < self.card_speed then
            moved = true
            card.flip_idx = card.flip_idx + dt
        else
            card.flip_idx = self.card_speed
        end
    end
    return moved
end

function state:init_table()
    -- clear everyones cards
    self.dealer_cards = {}
    self.player_cards = {}
    self.dealer_hand = nil
    self.player_hand = nil

    self.card_queue.asynchronous = false

    -- make a new deck
    self.deck = cardutils.newDeck( self.decks_to_use )

    self.outcome = nil
end

function state:deal_hand()
    self:init_table()

    self:no_menu()

    self.card_complete_callback = function()
        self.card_complete_callback = nil
        self:game_menu()
        pick_to_trade(self.dealer_cards)
    end

    -- deal first 5 cards
    self:deal_card( 'player' )
    self:deal_card( 'dealer' )
    self:deal_card( 'player' )
    self:deal_card( 'dealer' )
    self:deal_card( 'player' )
    self:deal_card( 'dealer' )
    self:deal_card( 'player' )
    self:deal_card( 'dealer' )
    self:deal_card( 'player' )
    self:deal_card( 'dealer' )

end

function state:poker_draw()
    self:no_menu()

    self.card_complete_callback = function()
        self.card_complete_callback = nil
        self:deal_menu()
        for _, card in pairs(self.dealer_cards) do
            card.face_up = true
            table.insert(self.card_queue, card)
            self.card_queue.asynchronous = true
        end
        self.player_hand = evaluate_hand(self.player_cards)
        self.dealer_hand = evaluate_hand(self.dealer_cards)

        local comp = compare_hands(self.player_hand, self.dealer_hand)
        if(comp == -1) then
            self.outcome = "You Win!"
            self.player.money = self.player.money + self.bet
        elseif(comp == 1) then
            self.outcome = "Dealer Wins!"
            self.player.money = self.player.money - self.bet
        else
            self.outcome = "Tie!"
        end
        if self.player.money == 0 then
            self:game_over()
        end

        if self.player.money < self.bet then
            self.bet = self.player.money
        end
    end

    for i = 1, 5 do
        if self.player_cards[i].raised then
            self.player_cards[i] = nil
            self:deal_card('player')
        end
    end
    for i = 1, 5 do
        if self.dealer_cards[i].raised then
            self.dealer_cards[i] = nil
            self:deal_card('dealer')
        end
    end

end

function state:deal_card( to )
    deal_card = table.remove( self.deck, 1 )
    x = 266+33 + camera.x
    face_up = true
    tbl = self.player_cards
    y = 140+33 + camera.y
    if to == 'dealer' then
        -- second card is not shown
       face_up = false
        tbl = self.dealer_cards
        y = 37+33 + camera.y
    end
    index = get_first_nil(tbl)
    tbl[index] = {
        card = deal_card.card,
        suit = deal_card.suit,
        x = x - ( self.width_per_card * (index - 1) ),
        y = y,
        move_idx = 0,
        flip_idx = 0,
        face_up = face_up
    }
    -- adjust widths when we've run out of room
    if #tbl * self.width_per_card >= self.max_card_room then
        new_width = self.max_card_room / #tbl
        for i,n in pairs( tbl ) do
            -- no idea why I need this hocus pocus, but it seems to work
            n.x = x - math.floor( ( new_width - 2 ) * ( i - 1 ) )
        end
    end
    table.insert(self.card_queue, tbl[index])
end

function state:game_over()
    self.prompt = Dialog.new("Game Over.", function(result)
        Gamestate.switch(self.previous)
    end )
end

function state:draw()
    if self.screenshot then
        love.graphics.draw( self.screenshot, camera.x, camera.y, 0, window.width / love.graphics:getWidth(), window.height / love.graphics:getHeight() )
    else
        love.graphics.setColor( 0, 0, 0, 255 )
        love.graphics.rectangle( 'fill', 0, 0, love.graphics:getWidth(), love.graphics:getHeight() )
        love.graphics.setColor( 255, 255, 255, 255 )
    end

    love.graphics.draw( self.table, self.center_x - ( self.table:getWidth() / 2 ), self.center_y - ( self.table:getHeight() / 2 ) )

    --dealer stack
    love.graphics.drawq( self.cardSprite, self.cardback, self.dealer_stack_x, self.dealer_stack_y )

    if self.dealer_cards then
        for i,n in pairs( self.dealer_cards ) do
            self:draw_card(
                n.card, n.suit,                                                    -- card / suit
                map( n.flip_idx, 0, self.card_speed, 0, 100 ),                     -- flip
                map( n.move_idx, 0, self.card_speed, self.dealer_stack_x, n.x ),   -- x
                map( n.move_idx, 0, self.card_speed, self.dealer_stack_y, n.y ),   -- y
                0
            )
        end
    end

    if self.player_cards then
        for i,n in pairs( self.player_cards ) do
            self:draw_card(
                n.card, n.suit,                                                    -- card / suit
                map( n.flip_idx, 0, self.card_speed, 0, 100 ),                     -- flip
                map( n.move_idx, 0, self.card_speed, self.dealer_stack_x, n.x ),   -- x
                map( n.move_idx, 0, self.card_speed, self.dealer_stack_y, n.y ),    -- y
                n.raised and -10 or 0,
                i == self.horizontal_selection
            )
        end
    end

    for i,n in pairs( self.options ) do
        local x = self.options_x
        local y = self.options_y + ( i * 15 )
        co = 0 -- color offset
        if not n.active then co = 180 end
        if i == self.selection + 1 and self.horizontal_selection == 0 then
            love.graphics.setColor( 255, 255, 255, 255 )
            love.graphics.draw( self.options_arrow, x - 5, y + 4 )
            co = 255
        end
        love.graphics.setColor( 255 - co, 255 - co, 255 - co )
        love.graphics.print( n.name, x + 3, y + 3, 0, 0.5 )
    end
    love.graphics.setColor( 255, 255, 255, 255 )

    cx = 0 -- chip offset x
    for color,count in pairs( cardutils.getChipCounts( self.player.money ) ) do
        cy = 0 -- chip offset y ( start at top )
        -- draw full stacks first
        for s = 1, math.floor( count / 5 ), 1 do
            --print( color, s, s % 2 == 0 )
            for i = 0, 4, 1 do
                love.graphics.drawq( self.chipSprite, self.chips[ color ], self.chip_x + cx - i, self.chip_y + cy - i )
            end
            -- change the coords
            if s % 2 == 0 then --even
                cy = 0 --top
                cx = cx + self.chip_width --shift over
            else --odd
                cy = self.chip_height --bottom
            end
        end
        for i = 0, count % 5 - 1, 1 do
             love.graphics.drawq( self.chipSprite, self.chips[ color ], self.chip_x + cx - i, self.chip_y + cy - i )
        end
        -- shift the drawpoint left for the next stack
        if count > 0 then -- something was actually drawn
            if count % 5 == 0 and cy == 0 then
                cx = cx + 4
            else
                cx = cx + self.chip_width + 4
            end
        end
    end

    if self.outcome then
        love.graphics.print( self.outcome, 200+36+camera.x, 112+33+camera.y, 0, 0.5 )
    end

    if(self.player_hand and self.dealer_hand) then
        x = 80+36 + camera.x
        love.graphics.print( self.dealer_hand.hand.friendly_name, x, 97+33+camera.y, 0, 0.5)
        love.graphics.print( self.player_hand.hand.friendly_name, x, 128+33+camera.y, 0, 0.5 )
    end

    if self.prompt then
        self.prompt:draw( self.center_x, self.center_y )
    end

    love.graphics.print( 'On Hand\n $ ' .. self.player.money, 80+36 + camera.x, 213+33+camera.y, 0, 0.5 )

    love.graphics.print( 'Bet $ ' .. self.bet , 315+36+camera.x, 112+33+camera.y, 0, 0.5 )

    love.graphics.setColor( 255, 255, 255, 255 )
end

function state:draw_card( card, suit, flip, x, y, offset, overlay )
    -- flip is a number from 0 to 100, where 0 is completely face down, and 100 is completely face up
    local w = self.card_width   -- card width
    local h = self.card_height  -- card height
    local st = 0.2              -- stretched top
    local sh = h * ( 1 + st )   -- stretched height
    local limit
    if flip > 50 then
        limit = 100
        _card = love.graphics.newQuad( ( card - 1 ) * w, ( suit - 1 ) * h, w, h, self.cardSprite:getWidth(), self.cardSprite:getHeight() )
    else
        limit = 0
        _card = self.cardback
    end
    darkness = map( flip, 50, limit, 100, 255 )
    if(overlay) then
        darkness = 150
    end
    love.graphics.setColor( darkness, darkness, darkness )
    love.graphics.drawq(
        self.cardSprite, _card,                             -- image, quad
        x + map( flip, 50, limit, w / 2, 0 ),               -- offset for flip
        map( flip, 50, limit, y - ( ( sh - h ) / 2 ), y ) + offset,  -- height offset
        0,                                                  -- no rotation
        map( flip, 50, limit, 0, 1 ),                       -- scale width for flip
        map( flip, 50, limit , 1 + st, 1 )                  -- scale height for flip
    )

    love.graphics.setColor( 255, 255, 255, 255 )
end

function get_first_nil(t)
    for i = 1, #t do
        if(t[i] == nil) then
            return i
        end
    end
    return #t + 1
end

function evaluate_hand(hand)

    card_to_text = {
        {'Ace', 'Aces'},
        {'Two', 'Twos'},
        {'Three', 'Threes'},
        {'Four', 'Fours'},
        {'Five', 'Fives'},
        {'Six', 'Sixes'},
        {'Seven', 'Sevens'},
        {'Eight', 'Eights'},
        {'Nine', 'Nines'},
        {'Ten', 'Tens'},
        {'Jack', 'Jacks'},
        {'Queen', 'Queens'},
        {'King', 'Kings'},
        {'Ace', 'Aces'}
    }

    HIGH_CARD = {value = 0, name = "High Card", format_string = "High Card: %s"}
    PAIR = {value = 1, name = "Pair", format_string = "Pair of %s"}
    TWO_PAIR = {value = 2, name = "Two Pair", format_string = "Two Pair: %s and %s"}
    THREE_OF_A_KIND = {value = 3, name = "Three of a Kind", format_string = "Three %s"}
    STRAIGHT = {value = 4, name = "Straight", format_string = "%s High Straight"}
    FLUSH = {value = 5, name = "Flush", friendly_name = "Flush"}
    FULL_HOUSE = {value = 6, name = "Full House", format_string = "%s Full of %s"}
    FOUR_OF_A_KIND = {value = 7, name = "Four of a Kind", format_string = "Four %s"}
    STRAIGHT_FLUSH = {value = 8, name = "Straight Flush", format_string = "%s High Straight Flush"}
    ROYAL_FLUSH = {value = 9, name = "Royal Flush", friendly_name = "Royal Flush"}

    suits = nil
    values = {}
    straight = true
    flush = true
    return_value = {}
    sorted_hand = {}
    min = 1
    max = 14
    has_ace = false
    local suit = nil
    for _, card in pairs(hand) do
        if(not suit) then
            suit = card.suit
        elseif(suit ~= card.suit) then
            flush = false
        end

        values[card.card] = (values[card.card] or 0) + 1
        if(values[card.card] > 1) then
            straight = false
        end

        table.insert(sorted_hand, card.card == 1 and 14 or card.card)

        if card.card == 1 then
            has_ace = true
        elseif straight then
            if card.card <= max and card.card >= min then
                min = card.card - 4 >= min and card.card - 4 or min
                max = card.card + 4 <= max and card.card + 4 or max
            else
                straight = false
            end
        end
    end

    if straight and has_ace and  (not (min == 1 or max == 14)) then
        straight = false
    end

    table.reverse_sort(sorted_hand)

    if straight then
        return_value.straight = true
        return_value[1] = max

        if flush and return_value[1] == 14 then --royal flush
            return_value.hand = ROYAL_FLUSH
        elseif flush then --straight flush
            return_value.hand = STRAIGHT_FLUSH
            return_value.hand.friendly_name = string.format(return_value.hand.format_string, card_to_text[return_value[1]][1])
        else
            return_value.hand = STRAIGHT
            return_value.hand.friendly_name = string.format(return_value.hand.format_string, card_to_text[return_value[1]][1])
        end
    elseif flush then
        return_value.hand = FLUSH
        return_value[1] = sorted_hand
    else -- handle pairs
        pair_index = {}
        for i = 0, 4 do
            pair_index[i] = {}
        end
        for card, count in pairs(values) do
            if card == 1 then
                card = 14
            end
            table.insert(pair_index[count], card)
        end
        -- Sort in reverse for later comparisons
        for i = 1, 4 do
            table.reverse_sort(pair_index[i])
        end

        if #pair_index[4] == 1 then
            return_value.hand = FOUR_OF_A_KIND
            return_value[1] = pair_index[4]
            return_value[2] = pair_index[1]
            return_value.hand.friendly_name = string.format(return_value.hand.format_string, card_to_text[pair_index[4][1]][2])
        elseif #pair_index[3] == 1 and #pair_index[2] == 1 then
            return_value.hand = FULL_HOUSE
            return_value[1] = pair_index[3]
            return_value[2] = pair_index[2]
            return_value.hand.friendly_name = string.format(return_value.hand.format_string, card_to_text[pair_index[3][1]][2], card_to_text[pair_index[2][1]][2])
        elseif #pair_index[3] == 1 then
            return_value.hand = THREE_OF_A_KIND
            return_value[1] = pair_index[3]
            return_value[2] = pair_index[1]
            return_value.hand.friendly_name = string.format(return_value.hand.format_string, card_to_text[pair_index[3][1]][2])
        elseif #pair_index[2] == 2 then
            return_value.hand = TWO_PAIR
            return_value[1] = pair_index[2]
            return_value[2] = pair_index[1]
            return_value.hand.friendly_name = string.format(return_value.hand.format_string, card_to_text[pair_index[2][1]][2], card_to_text[pair_index[2][2]][2])
        elseif #pair_index[2] == 1 then
            return_value.hand = PAIR
            return_value[1] = pair_index[2]
            return_value[2] = pair_index[1]
            return_value.hand.friendly_name = string.format(return_value.hand.format_string, card_to_text[pair_index[2][1]][2])
        else
            return_value.hand = HIGH_CARD
            return_value[1] = sorted_hand
            return_value.hand.friendly_name = string.format(return_value.hand.format_string, card_to_text[sorted_hand[1]][1])
        end
        return_value.ones = pair_index[1]
    end

    return return_value
end

function pick_to_trade(hand)
    value = evaluate_hand(hand)
    if(value.hand.value > 3) then
        return
    elseif(value.hand.value > 0) then
        for _, card in pairs(hand) do
            if(table.contains(value.ones, card.card)) then
                card.raised = true
            end
        end
    else
        -- probably need to test for 1 offs here
        for _, card in pairs(hand) do
            if card.card ~= value[1][1] and card.card ~= 1 then -- trick for ruling out aces (in the hand as 1, in thte value array as 14)
                card.raised = true
            end
        end
    end
end

function compare_hands(a,b)
    if(a.hand.value > b.hand.value) then
        return -1
    elseif(a.hand.value < b.hand.value) then
        return 1
    else
        local i = 1
        while a[i] and b[i] do
            local ret = compare(a[i], b[i])
            if(ret ~= 0) then
                return ret
            end
        end
    end
    return 0
end

function compare(a,b)
    if(type(a) == 'table' and type(b) == 'table') then
        for k,v in pairs(a) do
            local ret = compare(a[k], b[k])
            if(ret ~= 0) then
                return ret
            end
        end
    elseif(type(a) == 'number' and type(b) == 'number') then
        if(a == b) then
            return 0
        elseif(a > b) then
            return -1
        else
            return 1
        end
    else
        return nil
    end
end

return state


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Socket_model extends MY_model{
	private $tableName = "socketRegisterQueue";
	public function __construct(){
		parent::__construct();
	}
	public function getRegCode($userId){

		$code = parent::generateId($this->tableName);
		$this->db->insert(
			$this->tableName,
			[
				"code"    => $code,
				"userId"  => $userId,
				"time"    => time(),
				"notUsed" => 1
			]
		);
		return $code;
	}
	public function checkCode($code){
		$oneHour = 3600;
		$oneHourAgo = time()-$oneHour;
		$res = $this->db->select("userId,id")
			->from($this->tableName)
			->where("code",$code)
			->where("notUsed",1)
			->where("time >=",$oneHourAgo)
			->get()
			->row();
		if(!$res){
			return false;
		}
		$this->db->where("id",$res->id)->update($this->tableName,["notUsed"=>0]);
		return $res->userId;
	}
}


text:
#pragma once

#include <QObject>
#include <QMap>
#include <QMultiMap>
#include <QQueue>

#include "OpenGLFunctions.h"

class QImage;
class QFileSystemWatcher;
class Painter;

/** ToDo: does not work for multiple contexts yet...
	ToDo: remove "singletoness"
	ToDo: allow removal of textures...
*/

class FileAssociatedTexture : public QObject
{
public:
	static GLuint getOrCreate2D(
		const QString & fileName
    ,   OpenGLFunctions & gl
    ,	const GLenum wrap_s = GL_CLAMP_TO_EDGE
    ,	const GLenum wrap_t = GL_CLAMP_TO_EDGE
	,	const GLenum mag_filter = GL_LINEAR
    ,   const GLenum min_filter = GL_LINEAR);

	/** filePaths should contain a questionmark '?' that is replaced
		by cubemap extensions 'px', 'nx', 'py', etc.
		e.g. "resources/starmap?.png" points to "resources/starmap_px.png" etc.
	*/
	static GLuint getOrCreateCube(
        const QString & fileNames
    ,   OpenGLFunctions & gl
    ,	const GLenum mag_filter = GL_LINEAR
    ,   const GLenum min_filter = GL_LINEAR
	);

	static void process(OpenGLFunctions & gl);
	static QImage image(const QString & filePath);

protected:
	static FileAssociatedTexture * instance();

protected slots:
    void fileChanged(const QString & path);

protected:
    static QImage getOrCreateImage(
        const QString & filePath
    ,   bool forceReload = false);

    static GLuint loadTexture2D(
		GLuint texture
	,	const QImage & image
	,	OpenGLFunctions & gl);
	static GLuint loadTexture2D(
		GLuint texture
	,	const GLenum wrap_s
	,	const GLenum wrap_t
	,	const GLenum mag_filter
	,	const GLenum min_filter
	,	const QImage & image
	,	OpenGLFunctions & gl);

	static GLuint loadTextureCube(
		GLuint texture
    ,   const QMap<GLenum, QImage> & images
    ,   OpenGLFunctions & gl);
    static GLuint loadTextureCube(
        GLuint texture
    ,   const GLenum mag_filter
    ,   const GLenum min_filter
    ,   const QMap<GLenum, QImage> & images
	,	OpenGLFunctions & gl);

private:
	FileAssociatedTexture();
	virtual ~FileAssociatedTexture();

protected:
    static QMap<QString, QImage> s_imagesByFilePath;
	static QMap<QString, GLuint> s_texturesByFilePath;

    struct CubeFaceOfTexture
    {
        GLuint texture;
        GLenum face;
    };
    static QMultiMap<QString, CubeFaceOfTexture> s_cubefacesByFilePath;

	static QQueue<QString> s_queue;

	QFileSystemWatcher * m_fileSystemWatcher;

	static FileAssociatedTexture * s_instance;
};


text:
import CollectionRoute from '../../components/collection-route';

import CharacterModel from '../../../models/character';
import CharacterView from '../../views/list-item/character';

class GameServerCharactersIndexRoute extends CollectionRoute {

  static get modelClass() {
    return CharacterModel;
  }

  static get viewClass() {
    return CharacterView;
  }

}

export default GameServerCharactersIndexRoute;


text:
'use strict';

/* Edits by Thomas  */

angular.module('app.home')
    .directive('boxGridEffects', function () {
        return {
            restrict: 'A',
            scope: {
                boxGridEffects: '@'
            },
            link: function (scope, element) {
                element.on('mouseenter', function() {
                    element.addClass(scope.boxGridEffects);
                });
                element.on('mouseleave', function() {
                    element.removeClass(scope.boxGridEffects);
                });
            }
        };
    });