text:
package vn.cybersoft.obs.andriod.batterystats2.service;

import vn.cybersoft.obs.andriod.batterystats2.util.Recycler;
import vn.cybersoft.obs.andriod.batterystats2.util.SystemInfo;
import android.util.SparseArray;

/* Class that encloses physical hardware power data as well as estimated power
 * data for each uid that contributes a non-negligable amount of power for this
 * component.
 */
public class IterationData {
  private static Recycler<IterationData> recycler =
      new Recycler<IterationData>();

  private SparseArray<PowerData> uidPower;

  public static IterationData obtain() {
    IterationData result = recycler.obtain();
    if(result != null) return result;
    return new IterationData();
  }

  private IterationData() {
    uidPower = new SparseArray<PowerData>();
  }

  /* Initialize the members of this structure.  Remember that this class may not
   * have just been instantiated and may have been used in past iterations.
   */
  public void init() {
    uidPower.clear();
  }

  /* Allow this class to be recycled and to recycle all of the PowerData
   * PowerData elements contained within it.
   */
  public void recycle() {
    for(int i = 0; i < uidPower.size(); i++) {
      uidPower.valueAt(i).recycle();
    }
    uidPower.clear();
    recycler.recycle(this);
  }

  public void setPowerData(PowerData power) {
    addUidPowerData(SystemInfo.AID_ALL, power);
  }

  public void addUidPowerData(int uid, PowerData power) {
    uidPower.put(uid, power);
  }

  public SparseArray<PowerData> getUidPowerData() {
    return uidPower;
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<type language="gradle" name="org.gradle.api.plugins.jetty.JettyRun" version="3.0" superType="org.gradle.api.plugins.jetty.AbstractJettyRunTask" documented="true">
    <description>
Deploys an exploded web application to an embedded Jetty web container. Does not require that the web application
 be assembled into a war, saving time during the development cycle.

Once started, the web container can be configured to run continuously, scanning for changes in the project and
 automatically performing a hot redeploy when necessary. This allows the developer to concentrate on coding changes to
 the project using their IDE of choice and have those changes immediately and transparently reflected in the running
 web container, eliminating development time that is wasted on rebuilding, reassembling and redeploying.

 @deprecated The Jetty plugin has been deprecated

</description>
    <method name="applyJettyXml" returnType="void"/>
    <method name="configureScanner" returnType="void"/>
    <method name="configureWebApplication" returnType="void"/>
    <method name="createServer" returnType="org.gradle.api.plugins.jetty.internal.JettyPluginServer"/>
    <method name="filesChanged" returnType="void">
        <parameter type="java.util.List" name="changes"/>
    </method>
    <method name="finishConfigurationBeforeStart" returnType="void"/>
    <method name="getClassPathFiles" returnType="java.util.List"/>
    <method name="getClasspath" returnType="org.gradle.api.file.FileCollection">
        <description> Returns the classpath for the web application.

</description>
    </method>
    <method name="getConfiguredContextHandlers" returnType="org.mortbay.jetty.handler.ContextHandler"/>
    <method name="getExtraScanTargets" returnType="java.util.Set"/>
    <method name="getJettyEnvXml" returnType="java.io.File"/>
    <method name="getJettyEnvXmlFile" returnType="java.io.File"/>
    <method name="getScanTargetPatterns" returnType="org.gradle.api.plugins.jetty.ScanTargetPattern"/>
    <method name="getScanTargets" returnType="java.io.File"/>
    <method name="getWebAppSourceDirectory" returnType="java.io.File">
        <description> Returns the directory containing the web application source files.

</description>
    </method>
    <method name="getWebXml" returnType="java.io.File">
        <description> Returns the web.xml file to use. When null, no web.xml file is used.

</description>
    </method>
    <method name="restartWebApp" returnType="void">
        <parameter type="boolean" name="reconfigureScanner"/>
    </method>
    <method name="setClassPathFiles" returnType="void">
        <parameter type="java.util.List" name="classPathFiles"/>
    </method>
    <method name="setClasspath" returnType="void">
        <description> Set the classpath for the web application.

</description>
        <parameter type="org.gradle.api.file.FileCollection" name="classpath"/>
    </method>
    <method name="setContextHandlers" returnType="void">
        <parameter type="org.mortbay.jetty.handler.ContextHandler" name="contextHandlers"/>
    </method>
    <method name="setExtraScanTargets" returnType="void">
        <parameter type="java.lang.Iterable" name="extraScanTargets"/>
    </method>
    <method name="setJettyEnvXml" returnType="void">
        <parameter type="java.io.File" name="jettyEnvXml"/>
    </method>
    <method name="setJettyEnvXmlFile" returnType="void">
        <parameter type="java.io.File" name="jettyEnvXmlFile"/>
    </method>
    <method name="setScanTargetPatterns" returnType="void">
        <parameter type="org.gradle.api.plugins.jetty.ScanTargetPattern" name="scanTargetPatterns"/>
    </method>
    <method name="setScanTargets" returnType="void">
        <parameter type="java.io.File" name="scanTargets"/>
    </method>
    <method name="setWebAppSourceDirectory" returnType="void">
        <parameter type="java.io.File" name="webAppSourceDirectory"/>
    </method>
    <method name="setWebXml" returnType="void">
        <parameter type="java.io.File" name="webXml"/>
    </method>
    <method name="validateConfiguration" returnType="void"/>
    <property name="classPathFiles" type="java.util.List"/>
    <property name="classpath" type="org.gradle.api.file.FileCollection" documented="true">
        <description> Returns the classpath for the web application.

</description>
    </property>
    <property name="configuredContextHandlers" type="org.mortbay.jetty.handler.ContextHandler"/>
    <property name="contextHandlers" type="org.mortbay.jetty.handler.ContextHandler"/>
    <property name="extraScanTargets" type="java.util.Set"/>
    <property name="jettyEnvXml" type="java.io.File"/>
    <property name="jettyEnvXmlFile" type="java.io.File"/>
    <property name="scanTargetPatterns" type="org.gradle.api.plugins.jetty.ScanTargetPattern"/>
    <property name="scanTargets" type="java.io.File"/>
    <property name="webAppSourceDirectory" type="java.io.File" documented="true">
        <description> Returns the directory containing the web application source files.

</description>
    </property>
    <property name="webXml" type="java.io.File" documented="true">
        <description> Returns the web.xml file to use. When null, no web.xml file is used.

</description>
    </property>
</type>


text:
import re
from pathlib import Path

def test_build_dependencies():
    # Check that library requirements are pinned exactly the same across different setup files.
    # TODO: correct checks for numpy rather than ignoring
    libs_ignore_requirements = [
        "numpy",
        "pytest",
        "pytest-timeout",
        "mock",
        "flake8",
    ]
    # ignore language-specific packages that shouldn't be installed by all
    libs_ignore_setup = [
        "numpy",
        "fugashi",
        "natto-py",
        "pythainlp",
        "sudachipy",
        "sudachidict_core",
        "spacy-pkuseg",
    ]

    # check requirements.txt
    req_dict = {}

    root_dir = Path(__file__).parent
    req_file = root_dir / "requirements.txt"
    with req_file.open() as f:
        lines = f.readlines()
        for line in lines:
            line = line.strip()
            if not line.startswith("#"):
                lib, v = _parse_req(line)
                if lib and lib not in libs_ignore_requirements:
                    req_dict[lib] = v
    # check setup.cfg and compare to requirements.txt
    # also fails when there are missing or additional libs
    setup_file = root_dir / "setup.cfg"
    with setup_file.open() as f:
        lines = f.readlines()

    setup_keys = set()
    for line in lines:
        line = line.strip()
        if not line.startswith("#"):
            lib, v = _parse_req(line)
            if lib and not lib.startswith("cupy") and lib not in libs_ignore_setup:
                req_v = req_dict.get(lib, None)
                assert (
                    req_v is not None
                ), "{} in setup.cfg but not in requirements.txt".format(lib)
                assert (lib + v) == (lib + req_v), (
                    "{} has different version in setup.cfg and in requirements.txt: "
                    "{} and {} respectively".format(lib, v, req_v)
                )
                setup_keys.add(lib)
    assert sorted(setup_keys) == sorted(
        req_dict.keys()
    )  # if fail: requirements.txt contains a lib not in setup.cfg

    # check pyproject.toml and compare the versions of the libs to requirements.txt
    # does not fail when there are missing or additional libs
    toml_file = root_dir / "pyproject.toml"
    with toml_file.open() as f:
        lines = f.readlines()
    for line in lines:
        line = line.strip().strip(",").strip('"')
        if not line.startswith("#"):
            lib, v = _parse_req(line)
            if lib and lib not in libs_ignore_requirements:
                req_v = req_dict.get(lib, None)
                assert (lib + v) == (lib + req_v), (
                    "{} has different version in pyproject.toml and in requirements.txt: "
                    "{} and {} respectively".format(lib, v, req_v)
                )

def _parse_req(line):
    lib = re.match(r"^[a-z0-9\-]*", line).group(0)
    v = line.replace(lib, "").strip()
    if not re.match(r"^[<>=][<>=].*", v):
        return None, None
    return lib, v


text:
"use strict";

var fs              = require("fs");
var pkg             = require("./package.json");
var headerTemplate  = fs.readFileSync("header.txt");
var headerVars      = {
    name            : "LoadingOverlay",
    author          : "Gaspare Sganga",
    description     : pkg.description,
    version         : pkg.version,
    license         : pkg.license,
    documentation   : pkg.homepage
};

var paths = {
    src     : "src/",
    dest    : "dist/"
}

var gulp        = require("gulp");
var del         = require("del");
var inquirer    = require("inquirer");
var rename      = require("gulp-rename");
var replace     = require("gulp-replace");
var header      = require("gulp-header");
var sourcemaps  = require("gulp-sourcemaps");
var uglify      = require("gulp-uglify");

function src_headers(){
    return gulp.src([paths.src + "*.js", paths.src + "*.css"])
        .pipe(replace(/^\/\*{99}[^*]+\*{99}\/(\r\n|\r|\n)/, ""))
        .pipe(header(headerTemplate, headerVars))
        .pipe(gulp.dest(paths.src));
}

function dist_clean(){
    return del([paths.dest + "*"]);
}

function dist_js(){
    return gulp.src(paths.src + "*.js")
        .pipe(gulp.dest(paths.dest))
        .pipe(sourcemaps.init())
        .pipe(uglify())
        .pipe(header(headerTemplate, headerVars))
        .pipe(rename({
            extname : ".min.js"
        }))
        .pipe(sourcemaps.write("./", {
            addComment : false
        }))
        .pipe(gulp.dest(paths.dest));
}

gulp.task("default", function(){
    return inquirer.prompt([{
        type        : "list",
        name        : "task",
        message     : "Select the task to run",
        choices     : [
            {
                name    : "Update source headers",
                value   : "src"
            },
            {
                name    : "Update dist",
                value   : "dist"
            },
            {
                name    : "Exit",
                value   : "exit"
            }
        ],
        pageSize    : "3"
    }]).then(function(ret){
        switch (ret.task) {
            case "src":
                gulp.parallel(src_headers)();
                break;

            case "dist":
                gulp.series(dist_clean, dist_js)();
                break;

            default:
                console.log("\nNothing done\n");
        }
    });
});


text:
<?php
namespace Kartenmacherei\RestFramework;

class EnsureException extends \Exception
{

}


text:
import logging
import six
import os
from itertools import chain, product
from collections import defaultdict, namedtuple
from xml.etree import ElementTree
from six.moves import zip, map
from operator import attrgetter

logger = logging.getLogger(__name__)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
logger.addHandler(ch)
logger.setLevel(logging.INFO)

__all__ = ['TiledElement',
           'TiledMap',
           'TiledTileset',
           'TiledTileLayer',
           'TiledObject',
           'TiledObjectGroup',
           'TiledImageLayer',
           'TileFlags',
           'convert_to_bool',
           'parse_properties']

# internal flags
TRANS_FLIPX = 1
TRANS_FLIPY = 2
TRANS_ROT = 4

# Tiled gid flags
GID_TRANS_FLIPX = 1 << 31
GID_TRANS_FLIPY = 1 << 30
GID_TRANS_ROT = 1 << 29

# error message format strings go here
duplicate_name_fmt = 'Cannot set user {} property on {} "{}"; Tiled property already exists.'

flag_names = (
    'flipped_horizontally',
    'flipped_vertically',
    'flipped_diagonally',)

TileFlags = namedtuple('TileFlags', flag_names)

def default_image_loader(filename, flags, **kwargs):
    """This default image loader just returns filename, rect, and any flags
    """
    def load(rect=None, flags=None):
        return filename, rect, flags

    return load

def decode_gid(raw_gid):
    """Decode a GID from TMX data

    as of 0.7.0 it determines if the tile should be flipped when rendered
    as of 0.8.0 bit 30 determines if GID is rotated

    :param raw_gid: 32-bit number from TMX layer data
    :return: gid, flags
    """
    flags = TileFlags(
        raw_gid & GID_TRANS_FLIPX == GID_TRANS_FLIPX,
        raw_gid & GID_TRANS_FLIPY == GID_TRANS_FLIPY,
        raw_gid & GID_TRANS_ROT == GID_TRANS_ROT)
    gid = raw_gid & ~(GID_TRANS_FLIPX | GID_TRANS_FLIPY | GID_TRANS_ROT)
    return gid, flags

def convert_to_bool(text):
    # properly convert strings to a bool
    try:
        return bool(int(text))
    except:
        pass

    text = str(text).lower()
    if text == "true":
        return True
    if text == "yes":
        return True
    if text == "false":
        return False
    if text == "no":
        return False

    raise ValueError

# used to change the unicode string returned from xml to
# proper python variable types.
types = defaultdict(lambda: str)
types.update({
    "version": float,
    "orientation": str,
    "width": int,
    "height": int,
    "tilewidth": int,
    "tileheight": int,
    "firstgid": int,
    "source": str,
    "name": str,
    "spacing": int,
    "margin": int,
    "trans": str,
    "id": int,
    "opacity": float,
    "visible": convert_to_bool,
    "encoding": str,
    "compression": str,
    "gid": int,
    "type": str,
    "x": float,
    "y": float,
    "value": str,
    "rotation": float,
})

def parse_properties(node):
    """parse a node and return a dict that represents a tiled "property"

    the "properties" from tiled's tmx have an annoying quality that "name"
    and "value" is included. here we mangle it to get that junk out.
    """
    d = dict()
    for child in node.findall('properties'):
        for subnode in child.findall('property'):
            d[subnode.get('name')] = subnode.get('value')
    return d

class TiledElement(object):
    allow_duplicate_names = False

    def __init__(self):
        self.properties = dict()

    @classmethod
    def from_xml_string(cls, xml_string):
        """Return a TileElement object from a xml string

        :param xml_string: string containing xml data
        :rtype: TiledElement instance
        """
        return cls().parse_xml(ElementTree.fromstring(xml_string))

    def cast_and_set_attributes_from_node_items(self, items):
        for key, value in items:
            casted_value = types[key](value)
            setattr(self, key, casted_value)

    def contains_invalid_property_name(self, items):
        if self.allow_duplicate_names:
            return False

        for k, v in items:
            if hasattr(self, k):
                msg = duplicate_name_fmt.format(k, self.__class__.__name__, self.name)
                logger.error(msg)
                return True
        return False

    def log_property_error_message(self):
        msg = 'Some name are reserved for {0} objects and cannot be used.'
        logger.error(msg)

    def set_properties(self, node):
        """
        read the xml attributes and tiled "properties" from a xml node and fill
        in the values into the object's dictionary.  Names will be checked to
        make sure that they do not conflict with reserved names.
        """
        self.cast_and_set_attributes_from_node_items(node.items())
        properties = parse_properties(node)
        if (not self.allow_duplicate_names and
                self.contains_invalid_property_name(properties.items())):
            self.log_property_error_message()
            raise ValueError

        self.properties = properties

    def __getattr__(self, item):
        try:
            return self.properties[item]
        except KeyError:
            raise AttributeError

    def __repr__(self):
        return '<{0}: "{1}">'.format(self.__class__.__name__, self.name)

class TiledMap(TiledElement):
    """Contains the layers, objects, and images from a Tiled TMX map

    This class is meant to handle most of the work you need to do to use a map.
    """

    def __init__(self, filename=None, image_loader=default_image_loader,
                 **kwargs):
        """
        :param image_loader: function that will load images (see below)
        :param optional_gids: load specific tile image GID, even if never used
        :param load_all_tiles: load all tile images, even if never used
        :param allow_duplicate_names: allow duplicates in objects' metatdata
        :param filename: filename of tiled map to load

        image_loader:
          this must be a reference to a function that will accept a tuple:
          (filename of image, bounding rect of tile in image, flags)
          the function must return a reference to to the tile.
        """
        TiledElement.__init__(self)
        self.filename = filename
        self.image_loader = image_loader

        # optional keyword arguments checked here
        self.optional_gids = kwargs.get('optional_gids', set())
        self.load_all_tiles = kwargs.get('load_all', False)
        self.invert_y = kwargs.get('invert_y', True)

        # epic hack here
        TiledElement.allow_duplicate_names = \
            kwargs.get('allow_duplicate_names', False)

        self.layers = list()           # all layers in proper order
        self.tilesets = list()         # TiledTileset objects
        self.tile_properties = dict()  # tiles that have metadata
        self.layernames = dict()

        # only used tiles are actually loaded, so there will be a difference
        # between the GIDs in the Tiled map data (tmx) and the data in this
        # object and the layers.  This dictionary keeps track of that.
        self.gidmap = defaultdict(list)
        self.imagemap = dict()     # mapping of gid and trans flags to real gids
        self.tiledgidmap = dict()  # mapping of tiledgid to pytmx gid
        self.maxgid = 1

        # should be filled in by a loader function
        self.images = list()

        # defaults from the TMX specification
        self.version = 0.0
        self.orientation = None
        self.width = 0       # width of map in tiles
        self.height = 0      # height of map in tiles
        self.tilewidth = 0   # width of a tile in pixels
        self.tileheight = 0  # height of a tile in pixels
        self.background_color = None

        # initialize the gid mapping
        self.imagemap[(0, 0)] = 0

        if filename:
            self.parse_xml(ElementTree.parse(self.filename).getroot())

    def __repr__(self):
        return '<{0}: "{1}">'.format(self.__class__.__name__, self.filename)

    # iterate over layers and objects in map
    def __iter__(self):
        return chain(self.layers, self.objects)

    def parse_xml(self, node):
        """Parse a map from ElementTree xml node

        :param node: ElementTree xml node
        :return: self
        """
        self.set_properties(node)
        self.background_color = node.get('backgroundcolor',
                                         self.background_color)

        # ***         do not change this load order!         *** #
        # ***    gid mapping errors will occur if changed    *** #
        for subnode in node.findall('layer'):
            self.add_layer(TiledTileLayer(self, subnode))

        for subnode in node.findall('imagelayer'):
            self.add_layer(TiledImageLayer(self, subnode))

        for subnode in node.findall('objectgroup'):
            self.add_layer(TiledObjectGroup(self, subnode))

        for subnode in node.findall('tileset'):
            self.add_tileset(TiledTileset(self, subnode))

        # "tile objects", objects with a GID, have need to have their attributes
        # set after the tileset is loaded, so this step must be performed last
        # also, this step is performed for objects to load there tiles.
        # height and width will automatically be set according to the tileset
        # that the image is from

        # tiled stores the origin of GID objects by the lower right corner
        # this is different for all other types, so i just adjust it here
        # so all types loaded with pytmx are uniform.

        # iterate through tile objects and handle the image
        for o in [o for o in self.objects if o.gid]:

            # gids might also have properties assigned to them
            # in that case, assign the gid properties to the object as well
            p = self.get_tile_properties_by_gid(o.gid)
            if p:
                o.properties.update(p)

            try:
                tileset = self.get_tileset_from_gid(o.gid)
            except ValueError:
                msg = 'attempted to lookup invalid gid %s in object %s'
                logger.error(msg, o.gid, o)
            else:
                if self.invert_y:
                    o.y -= tileset.tileheight
                o.height = tileset.tileheight
                o.width = tileset.tilewidth

        self.reload_images()
        return self

    def reload_images(self):
        """Load the map images from disk

        This method will use the image loader passed in the constructor
        to do the loading or will use a generic default, in which case no
        images will be loaded.

        :return: None
        """
        self.images = [None] * self.maxgid

        # iterate through tilesets to get source images
        for ts in self.tilesets:

            # skip tilesets without a source
            if ts.source is None:
                continue

            path = os.path.join(os.path.dirname(self.filename), ts.source)
            colorkey = getattr(ts, 'trans', None)
            loader = self.image_loader(path, colorkey)

            p = product(range(ts.margin,
                              ts.height + ts.margin - ts.tileheight + 1,
                              ts.tileheight + ts.spacing),
                        range(ts.margin,
                              ts.width + ts.margin - ts.tilewidth + 1,
                              ts.tilewidth + ts.spacing))

            # iterate through the tiles
            for real_gid, (y, x) in enumerate(p, ts.firstgid):
                rect = (x, y, ts.tilewidth, ts.tileheight)
                gids = self.map_gid(real_gid)

                # gids is None if the tile is never used
                # but give another chance to load the gid anyway
                if gids is None:
                    if self.load_all_tiles or real_gid in self.optional_gids:
                        # TODO: handle flags? - might never be an issue, though
                        gids = [self.register_gid(real_gid, flags=0)]

                if gids:
                    # flags might rotate/flip the image, so let the loader
                    # handle that here
                    for gid, flags in gids:
                        self.images[gid] = loader(rect, flags)

        # load image layer images
        for layer in (i for i in self.layers if isinstance(i, TiledImageLayer)):
            source = getattr(layer, 'source', None)
            if source:
                colorkey = getattr(layer, 'trans', None)
                real_gid = len(self.images)
                gid = self.register_gid(real_gid)
                layer.gid = gid
                path = os.path.join(os.path.dirname(self.filename), source)
                loader = self.image_loader(path, colorkey)
                image = loader()
                self.images.append(image)

        # load images in tiles.
        # instead of making a new gid, replace the reference to the tile that
        # was loaded from the tileset
        for real_gid, props in self.tile_properties.items():
            source = props.get('source', None)
            if source:
                colorkey = props.get('trans', None)
                path = os.path.join(os.path.dirname(self.filename), source)
                loader = self.image_loader(path, colorkey)
                image = loader()
                self.images[real_gid] = image

    def get_tile_image(self, x, y, layer):
        """Return the tile image for this location

        :param x: x coordinate
        :param y: y coordinate
        :param layer: layer number
        :rtype: surface if found, otherwise 0
        """
        try:
            assert (x >= 0 and y >= 0)
        except AssertionError:
            raise ValueError

        try:
            layer = self.layers[layer]
        except IndexError:
            raise ValueError

        assert (isinstance(layer, TiledTileLayer))

        try:
            gid = layer.data[y][x]
        except (IndexError, ValueError):
            raise ValueError
        except TypeError:
            msg = "Tiles must be specified in integers."
            logger.debug(msg)
            raise TypeError

        else:
            return self.get_tile_image_by_gid(gid)

    def get_tile_image_by_gid(self, gid):
        """Return the tile image for this location

        :param gid: GID of image
        :rtype: surface if found, otherwise ValueError
        """
        try:
            assert (int(gid) >= 0)
            return self.images[gid]
        except TypeError:
            msg = "GIDs must be expressed as a number.  Got: {0}"
            logger.debug(msg.format(gid))
            raise TypeError
        except (AssertionError, IndexError):
            msg = "Coords: ({0},{1}) in layer {2} has invalid GID: {3}"
            logger.debug(msg.format(gid))
            raise ValueError

    def get_tile_gid(self, x, y, layer):
        """Return the tile image GID for this location

        :param x: x coordinate
        :param y: y coordinate
        :param layer: layer number
        :rtype: surface if found, otherwise ValueError
        """
        try:
            assert (x >= 0 and y >= 0 and layer >= 0)
        except AssertionError:
            raise ValueError

        try:
            return self.layers[int(layer)].data[int(y)][int(x)]
        except (IndexError, ValueError):
            msg = "Coords: ({0},{1}) in layer {2} is invalid"
            logger.debug(msg, (x, y, layer))
            raise ValueError

    def get_tile_properties(self, x, y, layer):
        """Return the tile image GID for this location

        :param x: x coordinate
        :param y: y coordinate
        :param layer: layer number
        :rtype: python dict if found, otherwise None
        """
        try:
            assert (x >= 0 and y >= 0 and layer >= 0)
        except AssertionError:
            raise ValueError

        try:
            gid = self.layers[int(layer)].data[int(y)][int(x)]
        except (IndexError, ValueError):
            msg = "Coords: ({0},{1}) in layer {2} is invalid."
            logger.debug(msg.format(x, y, layer))
            raise Exception

        else:
            try:
                return self.tile_properties[gid]
            except (IndexError, ValueError):
                msg = "Coords: ({0},{1}) in layer {2} has invalid GID: {3}"
                logger.debug(msg.format(x, y, layer, gid))
                raise Exception
            except KeyError:
                return None

    def get_tile_locations_by_gid(self, gid):
        """Search map for tile locations by the GID

        Note: Not a fast operation

        :param gid: GID to be searched for
        :rtype: generator of tile locations
        """

        # use this func to make sure GID is valid
        self.get_tile_image_by_gid(gid)

        p = product(range(self.width),
                    range(self.height),
                    range(len(self.layers)))

        return ((x, y, l) for (x, y, l) in p if
                self.layers[l].data[y][x] == gid)

    def get_tile_properties_by_gid(self, gid):
        """Get the tile properties of a tile GID

        :param gid: GID
        :rtype: python dict if found, otherwise None
        """
        try:
            return self.tile_properties[gid]
        except KeyError:
            return None

    def set_tile_properties(self, gid, properties):
        """Set the tile properties of a tile GID

        :param gid: GID
        :param properties: python dict of properties for GID
        """
        self.tile_properties[gid] = properties

    def get_tile_properties_by_layer(self, layer):
        """Get the tile properties of each GID in layer

        :param layer: layer number
        :rtype: iterator of (gid, properties) tuples
        """
        try:
            assert (int(layer) >= 0)
            layer = int(layer)
        except (TypeError, AssertionError):
            msg = "Layer must be a positive integer.  Got {0} instead."
            logger.debug(msg.format(type(layer)))
            raise ValueError

        p = product(range(self.width), range(self.height))
        layergids = set(self.layers[layer].data[y][x] for x, y in p)

        for gid in layergids:
            try:
                yield gid, self.tile_properties[gid]
            except KeyError:
                continue

    def add_layer(self, layer):
        """Add a layer (TileTileLayer, TiledImageLayer, or TiledObjectGroup)

        :param layer: TileTileLayer, TiledImageLayer, TiledObjectGroup object
        """
        assert (
            isinstance(layer,
                       (TiledTileLayer, TiledImageLayer, TiledObjectGroup)))

        self.layers.append(layer)
        self.layernames[layer.name] = layer

    def add_tileset(self, tileset):
        """ Add a tileset to the map

        :param tileset: TiledTileset
        """
        assert (isinstance(tileset, TiledTileset))
        self.tilesets.append(tileset)

    def get_layer_by_name(self, name):
        """Return a layer by name

        :param name: Name of layer.  Case-sensitive.
        :rtype: Layer object if found, otherwise ValueError
        """
        try:
            return self.layernames[name]
        except KeyError:
            msg = 'Layer "{0}" not found.'
            logger.debug(msg.format(name))
            raise ValueError

    def get_object_by_name(self, name):
        """Find an object

        :param name: Name of object.  Case-sensitive.
        :rtype: Object if found, otherwise ValueError
        """
        for obj in self.objects:
            if obj.name == name:
                return obj
        raise ValueError

    def get_tileset_from_gid(self, gid):
        """Return tileset that owns the gid

        Note: this is a slow operation, so if you are expecting to do this \
              often, it would be worthwhile to cache the results of this.

        :param gid: gid of tile image
        :rtype: TiledTileset if found, otherwise ValueError
        """
        try:
            tiled_gid = self.tiledgidmap[gid]
        except KeyError:
            raise ValueError

        for tileset in sorted(self.tilesets, key=attrgetter('firstgid'),
                              reverse=True):
            if tiled_gid >= tileset.firstgid:
                return tileset

        raise ValueError

    @property
    def objectgroups(self):
        """Return iterator of all object groups

        :rtype: Iterator
        """
        return (layer for layer in self.layers
                if isinstance(layer, TiledObjectGroup))

    @property
    def objects(self):
        """Return iterator of all the objects associated with this map

        :rtype: Iterator
        """
        return chain(*self.objectgroups)

    @property
    def visible_layers(self):
        """Return iterator of Layer objects that are set 'visible'

        :rtype: Iterator
        """
        return (l for l in self.layers if l.visible)

    @property
    def visible_tile_layers(self):
        """Return iterator of layer indexes that are set 'visible'

        :rtype: Iterator
        """
        return (i for (i, l) in enumerate(self.layers)
                if l.visible and isinstance(l, TiledTileLayer))

    @property
    def visible_object_groups(self):
        """Return iterator of object group indexes that are set 'visible'

        :rtype: Iterator
        """
        return (i for (i, l) in enumerate(self.layers)
                if l.visible and isinstance(l, TiledObjectGroup))

    def register_gid(self, tiled_gid, flags=None):
        """Used to manage the mapping of GIDs between the tmx and pytmx

        :param tiled_gid: GID that is found in TMX data
        :rtype: GID that pytmx uses for the the GID passed
        """
        if flags is None:
            flags = TileFlags(0, 0, 0)

        if tiled_gid:
            try:
                return self.imagemap[(tiled_gid, flags)][0]
            except KeyError:
                gid = self.maxgid
                self.maxgid += 1
                self.imagemap[(tiled_gid, flags)] = (gid, flags)
                self.gidmap[tiled_gid].append((gid, flags))
                self.tiledgidmap[gid] = tiled_gid
                return gid

        else:
            return 0

    def map_gid(self, tiled_gid):
        """Used to lookup a GID read from a TMX file's data

        :param tiled_gid: GID that is found in TMX data
        :rtype: (GID, flags) for the the GID passed, None if not found
        """
        try:
            return self.gidmap[int(tiled_gid)]
        except KeyError:
            return None
        except TypeError:
            msg = "GIDs must be an integer"
            logger.debug(msg)
            raise TypeError

class TiledTileset(TiledElement):
    """ Represents a Tiled Tileset

    External tilesets are supported.  GID/ID's from Tiled are not guaranteed to
    be the same after loaded.
    """

    def __init__(self, parent, node):
        TiledElement.__init__(self)
        self.parent = parent
        self.offset = (0, 0)

        # defaults from the specification
        self.firstgid = 0
        self.source = None
        self.name = None
        self.tilewidth = 0
        self.tileheight = 0
        self.spacing = 0
        self.margin = 0
        self.trans = None
        self.width = 0
        self.height = 0

        self.parse_xml(node)

    def parse_xml(self, node):
        """Parse a Tileset from ElementTree xml node

        A bit of mangling is done here so that tilesets that have external
        TSX files appear the same as those that don't

        :param node: ElementTree xml node
        :return: self
        """
        import os

        # if true, then node references an external tileset
        source = node.get('source', None)
        if source:
            if source[-4:].lower() == ".tsx":

                # external tilesets don't save this, store it for later
                self.firstgid = int(node.get('firstgid'))

                # we need to mangle the path - tiled stores relative paths
                dirname = os.path.dirname(self.parent.filename)
                path = os.path.abspath(os.path.join(dirname, source))
                try:
                    node = ElementTree.parse(path).getroot()
                except IOError:
                    msg = "Cannot load external tileset: {0}"
                    logger.error(msg.format(path))
                    raise Exception

            else:
                msg = "Found external tileset, but cannot handle type: {0}"
                logger.error(msg.format(self.source))
                raise Exception

        self.set_properties(node)

        # since tile objects [probably] don't have a lot of metadata,
        # we store it separately in the parent (a TiledMap instance)
        for child in node.getiterator('tile'):
            tiled_gid = int(child.get("id"))
            p = parse_properties(child)

            # handle tiles that have their own image
            image = child.find('image')
            if image is None:
                p['width'] = self.tilewidth
                p['height'] = self.tileheight
            else:
                p['source'] = image.get('source')
                p['trans'] = image.get('trans', None)
                p['width'] = image.get('width')
                p['height'] = image.get('height')

            for gid, flags in self.parent.map_gid(tiled_gid + self.firstgid):
                self.parent.set_tile_properties(gid, p)

        # handle the optional 'tileoffset' node
        self.offset = node.find('tileoffset')
        if self.offset is None:
            self.offset = (0, 0)
        else:
            self.offset = (self.offset.get('x', 0), self.offset.get('y', 0))

        image_node = node.find('image')
        if image_node is not None:
            self.source = image_node.get('source')
            self.trans = image_node.get('trans', None)
            self.width = int(image_node.get('width'))
            self.height = int(image_node.get('height'))

        return self

class TiledTileLayer(TiledElement):
    """Represents a TileLayer

    To just get the tiles, use TiledTileLayer.tiles()
    """

    def __init__(self, parent, node):
        TiledElement.__init__(self)
        self.parent = parent
        self.data = list()

        # defaults from the specification
        self.name = None
        self.opacity = 1.0
        self.visible = True
        self.height = 0
        self.width = 0

        self.parse_xml(node)

    def __iter__(self):
        return self.iter_data()

    def iter_data(self):
        for y, x in product(range(self.height), range(self.width)):
            yield x, y, self.data[y][x]

    def tiles(self):
        """Quickly iterate over tile images of this layer

        This is an optimised generator function that returns
        (tile_x, tile_y, tile_image) tuples,

        :rtype: Generator
        :return: (x, y, image) tuples
        """
        images = self.parent.images
        data = self.data
        for y, row in enumerate(data):
            for x, gid in enumerate(row):
                if gid:
                    yield x, y, images[gid]

    def parse_xml(self, node):
        """Parse a Tile Layer from ElementTree xml node

        :param node: ElementTree xml node
        :return: self
        """
        import struct
        import array

        self.set_properties(node)
        data = None
        next_gid = None
        data_node = node.find('data')

        encoding = data_node.get('encoding', None)
        if encoding == 'base64':
            from base64 import b64decode

            data = b64decode(data_node.text.strip())

        elif encoding == 'csv':
            next_gid = map(int, "".join(
                line.strip() for line in data_node.text.strip()
            ).split(","))

        elif encoding:
            msg = 'TMX encoding type: {0} is not supported.'
            logger.error(msg.format(encoding))
            raise Exception

        compression = data_node.get('compression', None)
        if compression == 'gzip':
            import gzip

            with gzip.GzipFile(fileobj=six.BytesIO(data)) as fh:
                data = fh.read()

        elif compression == 'zlib':
            import zlib

            data = zlib.decompress(data)

        elif compression:
            msg = 'TMX compression type: {0} is not supported.'
            logger.error(msg.format(compression))
            raise Exception

        # if data is None, then it was not decoded or decompressed, so
        # we assume here that it is going to be a bunch of tile elements
        # TODO: this will/should raise an exception if there are no tiles
        if encoding == next_gid is None:
            def get_children(parent):
                for child in parent.findall('tile'):
                    yield int(child.get('gid'))

            next_gid = get_children(data_node)

        elif data:
            if type(data) == bytes:
                fmt = struct.Struct('<L')
                iterator = (data[i:i + 4] for i in range(0, len(data), 4))
                next_gid = (fmt.unpack(i)[0] for i in iterator)
            else:
                msg = 'layer data not in expected format ({})'
                logger.error(msg.format(type(data)))
                raise Exception

        init = lambda: [0] * self.width
        reg = self.parent.register_gid

        # H (16-bit) may be a limitation for very detailed maps
        self.data = tuple(array.array('H', init()) for i in range(self.height))
        for (y, x) in product(range(self.height), range(self.width)):
            self.data[y][x] = reg(*decode_gid(next(next_gid)))

        return self

class TiledObject(TiledElement):
    """ Represents a any Tiled Object

    Supported types: Box, Ellipse, Tile Object, Polyline, Polygon
    """

    def __init__(self, parent, node):
        TiledElement.__init__(self)
        self.parent = parent

        # defaults from the specification
        self.name = None
        self.type = None
        self.x = 0
        self.y = 0
        self.width = 0
        self.height = 0
        self.rotation = 0
        self.gid = 0
        self.visible = 1

        self.parse_xml(node)

    @property
    def image(self):
        if self.gid:
            return self.parent.images[self.gid]
        return None

    def parse_xml(self, node):
        """Parse an Object from ElementTree xml node

        :param node: ElementTree xml node
        :return: self
        """

        def read_points(text):
            """parse a text string of float tuples and return [(x,...),...]
            """
            return tuple(tuple(map(float, i.split(','))) for i in text.split())

        self.set_properties(node)

        # correctly handle "tile objects" (object with gid set)
        if self.gid:
            self.gid = self.parent.register_gid(self.gid)

        points = None
        polygon = node.find('polygon')
        if polygon is not None:
            points = read_points(polygon.get('points'))
            self.closed = True

        polyline = node.find('polyline')
        if polyline is not None:
            points = read_points(polyline.get('points'))
            self.closed = False

        if points:
            x1 = x2 = y1 = y2 = 0
            for x, y in points:
                if x < x1: x1 = x
                if x > x2: x2 = x
                if y < y1: y1 = y
                if y > y2: y2 = y
            self.width = abs(x1) + abs(x2)
            self.height = abs(y1) + abs(y2)
            self.points = tuple(
                [(i[0] + self.x, i[1] + self.y) for i in points])

        return self

class TiledObjectGroup(TiledElement, list):
    """ Represents a Tiled ObjectGroup

    Supports any operation of a normal list.
    """

    def __init__(self, parent, node):
        TiledElement.__init__(self)
        self.parent = parent

        # defaults from the specification
        self.name = None
        self.color = None
        self.opacity = 1
        self.visible = 1

        self.parse_xml(node)

    def parse_xml(self, node):
        """Parse an Object Group from ElementTree xml node

        :param node: ElementTree xml node
        :return: self
        """
        self.set_properties(node)
        self.extend(TiledObject(self.parent, child)
                    for child in node.findall('object'))

        return self

class TiledImageLayer(TiledElement):
    """ Represents Tiled Image Layer

    The image associated with this layer will be loaded and assigned a GID.
    """

    def __init__(self, parent, node):
        TiledElement.__init__(self)
        self.parent = parent
        self.source = None
        self.trans = None
        self.gid = 0

        # defaults from the specification
        self.name = None
        self.opacity = 1
        self.visible = 1

        self.parse_xml(node)

    @property
    def image(self):
        if self.gid:
            return self.parent.images[self.gid]
        return None

    def parse_xml(self, node):
        """Parse an Image Layer from ElementTree xml node

        :param node: ElementTree xml node
        :return: self
        """
        self.set_properties(node)
        self.name = node.get('name', None)
        self.opacity = node.get('opacity', self.opacity)
        self.visible = node.get('visible', self.visible)
        image_node = node.find('image')
        self.source = image_node.get('source')
        self.trans = image_node.get('trans', None)
        return self


text:
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_BoardColumn(object):
    def setupUi(self, column_button, column_number):
        column_button.setObjectName('column_{0}'.format(column_number))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(column_button.sizePolicy().hasHeightForWidth())
        column_button.setSizePolicy(sizePolicy)
        column_button.setFocusPolicy(QtCore.Qt.NoFocus)
        column_button.setStyleSheet("background-image: url(:/fields/empty_column.png);")
        column_button.setText("")
        column_button.setFlat(False)

        self.field_column = QtWidgets.QFrame(column_button)
        self.field_column.setGeometry(QtCore.QRect(0, 0, 64, 302))
        self.field_column.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.field_column.setFrameShadow(QtWidgets.QFrame.Raised)
        self.field_column.setObjectName("field_column_{0}".format(column_number))

        self.verticalLayout = QtWidgets.QVBoxLayout(self.field_column)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setSpacing(0)
        self.verticalLayout.setObjectName("field_column_layout{0}".format(column_number))

        QtCore.QMetaObject.connectSlotsByName(column_button)


text:
from __future__ import annotations

from typing import Callable

import os
from distutils.dir_util import copy_tree
from pathlib import Path

from autosklearn.automl_common.common.utils.backend import Backend, create
from autosklearn.data.xy_data_manager import XYDataManager

from pytest import fixture

HERE = Path(__file__).parent.resolve()
DATAPATH = HERE.parent / "data"

def copy_backend(old: Backend | Path | str, new: Backend | Path | str) -> Backend:
    """Transfers a backend to a new path

    Parameters
    ----------
    old_backend: Backend | Path | str
        The backend to transfer from

    new_path: Backend | Path | str
        Where to place the new backend

    Returns
    -------
    Backend
        The new backend with the contents of the old
    """
    if isinstance(new, str):
        new_backend = create(
            temporary_directory=new,
            output_directory=None,
            prefix="auto-sklearn",
        )
    elif isinstance(new, Path):
        new_backend = create(
            temporary_directory=str(new),
            output_directory=None,
            prefix="auto-sklearn",
        )
    else:
        new_backend = new

    dst = new_backend.temporary_directory

    if isinstance(old, str):
        src = old
    elif isinstance(old, Path):
        src = str(old)
    else:
        src = old.temporary_directory

    copy_tree(src, dst)

    return new_backend

# TODO Update to return path once everything can use a path
@fixture
def tmp_dir(tmp_path: Path) -> str:
    """
    Fixtures
    --------
    tmp_path : Path
        Built in pytest fixture

    Returns
    -------
    str
        The directory as a str
    """
    return str(tmp_path)

@fixture
def make_backend(tmp_path: Path) -> Callable[..., Backend]:
    """Make a backend

    Parameters
    ----------
    path: Union[str, Path]
        The path to place the backend at

    template: Optional[Path] = None
        Setup with a pre-existing layout if not None

    Returns
    -------
    Backend
        The created backend object
    """
    # TODO redo once things use paths
    def _make(
        path: str | Path | None = None,
        template: Path | Backend | None = None,
        datamanager: XYDataManager | None = None,
    ) -> Backend:
        if template is not None and datamanager is not None:
            raise ValueError("Does not support template and datamanager")

        if path is None:
            _path = Path(tmp_path) / "backend"
        elif isinstance(path, str):
            _path = Path(path)
        else:
            _path = path

        assert not _path.exists(), "Path exists, Try passing path / 'backend'"

        if template is not None:
            backend = copy_backend(old=template, new=_path)
        else:
            backend = create(
                temporary_directory=str(_path),
                output_directory=None,
                prefix="auto-sklearn",
            )

            if datamanager is not None:
                backend.save_datamanager(datamanager)

        return backend

    return _make

@fixture(scope="function")
def backend(tmp_dir: str, make_backend: Callable) -> Backend:
    """A backend object

    Fixtures
    --------
    tmp_dir : str
        A directory to place the backend at

    make_backend : Callable
        Factory to make a backend

    Returns
    -------
    Backend
        A backend object
    """
    backend_path = os.path.join(tmp_dir, "backend")
    return make_backend(path=backend_path)


text:
namespace sisyfox.sisycol.request
{

using global::System;
using global::FlatBuffers;

public struct GetDmxDeviceChannelRange : IFlatbufferObject
{
  private Table __p;
  public ByteBuffer ByteBuffer { get { return __p.bb; } }
  public static GetDmxDeviceChannelRange GetRootAsGetDmxDeviceChannelRange(ByteBuffer _bb) { return GetRootAsGetDmxDeviceChannelRange(_bb, new GetDmxDeviceChannelRange()); }
  public static GetDmxDeviceChannelRange GetRootAsGetDmxDeviceChannelRange(ByteBuffer _bb, GetDmxDeviceChannelRange obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
  public void __init(int _i, ByteBuffer _bb) { __p.bb_pos = _i; __p.bb = _bb; }
  public GetDmxDeviceChannelRange __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }

  public uint DeviceId { get { int o = __p.__offset(4); return o != 0 ? __p.bb.GetUint(o + __p.bb_pos) : (uint)0; } }
  public uint ChannelId { get { int o = __p.__offset(6); return o != 0 ? __p.bb.GetUint(o + __p.bb_pos) : (uint)0; } }
  public byte Range { get { int o = __p.__offset(8); return o != 0 ? __p.bb.Get(o + __p.bb_pos) : (byte)0; } }

  public static Offset<GetDmxDeviceChannelRange> CreateGetDmxDeviceChannelRange(FlatBufferBuilder builder,
      uint deviceId = 0,
      uint channelId = 0,
      byte range = 0) {
    builder.StartObject(3);
    GetDmxDeviceChannelRange.AddChannelId(builder, channelId);
    GetDmxDeviceChannelRange.AddDeviceId(builder, deviceId);
    GetDmxDeviceChannelRange.AddRange(builder, range);
    return GetDmxDeviceChannelRange.EndGetDmxDeviceChannelRange(builder);
  }

  public static void StartGetDmxDeviceChannelRange(FlatBufferBuilder builder) { builder.StartObject(3); }
  public static void AddDeviceId(FlatBufferBuilder builder, uint deviceId) { builder.AddUint(0, deviceId, 0); }
  public static void AddChannelId(FlatBufferBuilder builder, uint channelId) { builder.AddUint(1, channelId, 0); }
  public static void AddRange(FlatBufferBuilder builder, byte range) { builder.AddByte(2, range, 0); }
  public static Offset<GetDmxDeviceChannelRange> EndGetDmxDeviceChannelRange(FlatBufferBuilder builder) {
    int o = builder.EndObject();
    return new Offset<GetDmxDeviceChannelRange>(o);
  }
};

}


text:
require "spec_helper"

describe InventoryState do
  let(:period) { FactoryGirl.create :period }
  let(:plan) { FactoryGirl.create :plan_with_assignments, period: period }
  let(:classroom) { plan.classroom }
  let(:assignments) { plan.assignments }
  subject { FactoryGirl.create :inventory_state, period: period }

  before do
    plan
  end

  describe '#deletable?' do
    it "is true when there exists a closed, most recent plan" do
      expect(subject).to be_deletable
    end

    it "is false when there is an active plan" do
      new_period = create :period, classroom: classroom
      create :plan_with_assignments, period: new_period
      expect(subject).not_to be_deletable
    end
  end

  describe "#plan" do
    it "returns a Plan" do
      expect(subject.plan).to eq plan
    end
  end

  describe "#assignments" do
    it "returns several assignments persisted to the db" do
      assignments = FactoryGirl.create_list :assignment, 2
      subject.assignments += assignments
      expect(subject.reload.assignments).to eq assignments
    end
  end

  describe "#sorted_assignments" do
    it "displays in alpha descending ascending order by global id" do
      assns = FactoryGirl.create_list(:assignment, 2)
      assns.first.book_bag.update_attributes global_id: "10"
      assns.last.book_bag.update_attributes global_id: "2"
      subject.assignments = assns
      # expect 1, 10
      expect(subject.sorted_assignments).to eq assns.reverse
    end

    it "attaches assignments that are still out on loan at the end" do
    end
  end

  describe ".new_from_plan" do
    let(:subject) { described_class.new_from_plan(plan) }

    it "copies over the assignments from the classroom" do
      expect(subject.assignments).to match_array(classroom.assignments)
    end

    it "copies over all the classroom assignments, even those out on loan" do
      another_plan = FactoryGirl.create :plan_with_assignments, classroom: classroom
      other_assignments = another_plan.assignments
      expect(subject.assignments).to match_array(assignments + other_assignments)
    end

    it "copies over the period" do
      expect(subject.period).to eq plan.period
    end

    it "does not save the object" do
      expect(subject).to_not be_persisted
    end
  end
end


text:
package org.apache.hadoop.yarn.server.resourcemanager.scheduler;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager;
import org.apache.hadoop.yarn.util.resource.Resources;

/**
 * Resource Usage by Labels for following fields by label - AM resource (to
 * enforce max-am-resource-by-label after YARN-2637) - Used resource (includes
 * AM resource usage) - Reserved resource - Pending resource - Headroom
 *
 * This class can be used to track resource usage in queue/user/app.
 *
 * And it is thread-safe
 */
public class ResourceUsage {
  private ReadLock readLock;
  private WriteLock writeLock;
  private Map<String, UsageByLabel> usages;
  // short for no-label :)
  private static final String NL = CommonNodeLabelsManager.NO_LABEL;

  public ResourceUsage() {
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    readLock = lock.readLock();
    writeLock = lock.writeLock();

    usages = new HashMap<String, UsageByLabel>();
    usages.put(NL, new UsageByLabel(NL));
  }

  // Usage enum here to make implement cleaner
  private enum ResourceType {
    //CACHED_USED and CACHED_PENDING may be read by anyone, but must only
    //be written by ordering policies
    USED(0), PENDING(1), AMUSED(2), RESERVED(3), CACHED_USED(4),
      CACHED_PENDING(5);

    private int idx;

    private ResourceType(int value) {
      this.idx = value;
    }
  }

  private static class UsageByLabel {
    // usage by label, contains all UsageType
    private Resource[] resArr;

    public UsageByLabel(String label) {
      resArr = new Resource[ResourceType.values().length];
      for (int i = 0; i < resArr.length; i++) {
        resArr[i] = Resource.newInstance(0, 0);
      };
    }

    public Resource getUsed() {
      return resArr[ResourceType.USED.idx];
    }

    @Override
    public String toString() {
      StringBuilder sb = new StringBuilder();
      sb.append("{used=" + resArr[0] + "%, ");
      sb.append("pending=" + resArr[1] + "%, ");
      sb.append("am_used=" + resArr[2] + "%, ");
      sb.append("reserved=" + resArr[3] + "%}");
      return sb.toString();
    }
  }

  /*
   * Used
   */
  public Resource getUsed() {
    return getUsed(NL);
  }

  public Resource getUsed(String label) {
    return _get(label, ResourceType.USED);
  }

  public Resource getCachedUsed(String label) {
    return _get(label, ResourceType.CACHED_USED);
  }

  public Resource getCachedPending(String label) {
    return _get(label, ResourceType.CACHED_PENDING);
  }

  public void incUsed(String label, Resource res) {
    _inc(label, ResourceType.USED, res);
  }

  public void incUsed(Resource res) {
    incUsed(NL, res);
  }

  public void decUsed(Resource res) {
    decUsed(NL, res);
  }

  public void decUsed(String label, Resource res) {
    _dec(label, ResourceType.USED, res);
  }

  public void setUsed(Resource res) {
    setUsed(NL, res);
  }

  public void copyAllUsed(ResourceUsage other) {
    try {
      writeLock.lock();
      for (Entry<String, UsageByLabel> entry : other.usages.entrySet()) {
        setUsed(entry.getKey(), Resources.clone(entry.getValue().getUsed()));
      }
    } finally {
      writeLock.unlock();
    }
  }

  public void setUsed(String label, Resource res) {
    _set(label, ResourceType.USED, res);
  }

  public void setCachedUsed(String label, Resource res) {
    _set(label, ResourceType.CACHED_USED, res);
  }

  public void setCachedPending(String label, Resource res) {
    _set(label, ResourceType.CACHED_PENDING, res);
  }

  /*
   * Pending
   */
  public Resource getPending() {
    return getPending(NL);
  }

  public Resource getPending(String label) {
    return _get(label, ResourceType.PENDING);
  }

  public void incPending(String label, Resource res) {
    _inc(label, ResourceType.PENDING, res);
  }

  public void incPending(Resource res) {
    incPending(NL, res);
  }

  public void decPending(Resource res) {
    decPending(NL, res);
  }

  public void decPending(String label, Resource res) {
    _dec(label, ResourceType.PENDING, res);
  }

  public void setPending(Resource res) {
    setPending(NL, res);
  }

  public void setPending(String label, Resource res) {
    _set(label, ResourceType.PENDING, res);
  }

  /*
   * Reserved
   */
  public Resource getReserved() {
    return getReserved(NL);
  }

  public Resource getReserved(String label) {
    return _get(label, ResourceType.RESERVED);
  }

  public void incReserved(String label, Resource res) {
    _inc(label, ResourceType.RESERVED, res);
  }

  public void incReserved(Resource res) {
    incReserved(NL, res);
  }

  public void decReserved(Resource res) {
    decReserved(NL, res);
  }

  public void decReserved(String label, Resource res) {
    _dec(label, ResourceType.RESERVED, res);
  }

  public void setReserved(Resource res) {
    setReserved(NL, res);
  }

  public void setReserved(String label, Resource res) {
    _set(label, ResourceType.RESERVED, res);
  }

  /*
   * AM-Used
   */
  public Resource getAMUsed() {
    return getAMUsed(NL);
  }

  public Resource getAMUsed(String label) {
    return _get(label, ResourceType.AMUSED);
  }

  public void incAMUsed(String label, Resource res) {
    _inc(label, ResourceType.AMUSED, res);
  }

  public void incAMUsed(Resource res) {
    incAMUsed(NL, res);
  }

  public void decAMUsed(Resource res) {
    decAMUsed(NL, res);
  }

  public void decAMUsed(String label, Resource res) {
    _dec(label, ResourceType.AMUSED, res);
  }

  public void setAMUsed(Resource res) {
    setAMUsed(NL, res);
  }

  public void setAMUsed(String label, Resource res) {
    _set(label, ResourceType.AMUSED, res);
  }

  private static Resource normalize(Resource res) {
    if (res == null) {
      return Resources.none();
    }
    return res;
  }

  private Resource _get(String label, ResourceType type) {
    if (label == null) {
      label = RMNodeLabelsManager.NO_LABEL;
    }

    try {
      readLock.lock();
      UsageByLabel usage = usages.get(label);
      if (null == usage) {
        return Resources.none();
      }
      return normalize(usage.resArr[type.idx]);
    } finally {
      readLock.unlock();
    }
  }

  private Resource _getAll(ResourceType type) {
    try {
      readLock.lock();
      Resource allOfType = Resources.createResource(0);
      for (Map.Entry<String, UsageByLabel> usageEntry : usages.entrySet()) {
        //all usages types are initialized
        Resources.addTo(allOfType, usageEntry.getValue().resArr[type.idx]);
      }
      return allOfType;
    } finally {
      readLock.unlock();
    }
  }

  public Resource getAllPending() {
    return _getAll(ResourceType.PENDING);
  }

  public Resource getAllUsed() {
    return _getAll(ResourceType.USED);
  }

  private UsageByLabel getAndAddIfMissing(String label) {
    if (label == null) {
      label = RMNodeLabelsManager.NO_LABEL;
    }
    if (!usages.containsKey(label)) {
      UsageByLabel u = new UsageByLabel(label);
      usages.put(label, u);
      return u;
    }

    return usages.get(label);
  }

  private void _set(String label, ResourceType type, Resource res) {
    try {
      writeLock.lock();
      UsageByLabel usage = getAndAddIfMissing(label);
      usage.resArr[type.idx] = res;
    } finally {
      writeLock.unlock();
    }
  }

  private void _inc(String label, ResourceType type, Resource res) {
    try {
      writeLock.lock();
      UsageByLabel usage = getAndAddIfMissing(label);
      Resources.addTo(usage.resArr[type.idx], res);
    } finally {
      writeLock.unlock();
    }
  }

  private void _dec(String label, ResourceType type, Resource res) {
    try {
      writeLock.lock();
      UsageByLabel usage = getAndAddIfMissing(label);
      Resources.subtractFrom(usage.resArr[type.idx], res);
    } finally {
      writeLock.unlock();
    }
  }

  public Resource getCachedDemand(String label) {
    try {
      readLock.lock();
      Resource demand = Resources.createResource(0);
      Resources.addTo(demand, getCachedUsed(label));
      Resources.addTo(demand, getCachedPending(label));
      return demand;
    } finally {
      readLock.unlock();
    }
  }

  @Override
  public String toString() {
    try {
      readLock.lock();
      return usages.toString();
    } finally {
      readLock.unlock();
    }
  }

  public Set<String> getNodePartitionsSet() {
    try {
      readLock.lock();
      return usages.keySet();
    } finally {
      readLock.unlock();
    }
  }
}


text:
"use strict";

exports.index = function (req, res) {
  if (req.user && req.user.isDeveloper) {
    res.redirect('/dashboard/');
  } else {
    res.render('index');
  }
};

exports.about = function (req, res) {
  res.render('about', {
    menu: 'about'
  });
};

exports.blog = function (req, res) {
  res.render('blog', {
    menu: 'blog'
  });
};

exports.notFound = function(req, res) {
  res.status(404);
  res.render('404');
};

exports.safari = function(req, res) {
  res.render('safari');
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingTranslation,UnusedResources,InconsistentArrays">
    <string name="twitter_authority">org.mtransit.android.debug.ca_toronto_ttc_light_rail.news.twitter</string>
</resources>


text:
package com.darkhouse.gdefence.Model.Level;

import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.darkhouse.gdefence.GDefence;
import com.darkhouse.gdefence.Helpers.AssetLoader;
import com.darkhouse.gdefence.Screens.LevelMap;

import java.math.BigDecimal;

public class NextWaveTimer extends Label{
    private float time;

    public float getTime() {
        return time;
    }

    public NextWaveTimer() {
        super("", GDefence.getInstance().assetLoader.getTimerSkin());
    }

    @Override
    public void act(float delta) {
        if(delta > 30) return;
        super.act(delta);
        time = LevelMap.getLevel().getTimerTime();
        time = new BigDecimal(time).setScale(2, BigDecimal.ROUND_UP).floatValue();

        setText(Float.toString(time));
    }

//    @Override
//    public void draw(Batch batch, float parentAlpha) {
//        if(time > 0) {
//            super.draw(batch, parentAlpha);
//        }
//    }
}


text:
package org.batfish.datamodel;

import static org.batfish.common.bdd.BDDMatchers.isOne;
import static org.batfish.datamodel.FlowToBDD.flowHeadersToBdd;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;

import net.sf.javabdd.BDD;
import org.batfish.common.bdd.BDDPacket;
import org.junit.Test;

public class FlowToBDDTest {
  private static final Flow BASE_FLOW =
      Flow.builder()
          .setIngressNode("node")
          .setSrcIp(Ip.FIRST_CLASS_A_PRIVATE_IP)
          .setDstIp(Ip.FIRST_CLASS_B_PRIVATE_IP)
          .setIpProtocol(IpProtocol.OSPF)
          .setDscp(5)
          .setEcn(3)
          .setFragmentOffset(4)
          .setPacketLength(71)
          .build();
  private final BDDPacket _packet = new BDDPacket();

  /** Test that BASE_FLOW is converted to BDD correctly. */
  @Test
  public void testFlowHeadersToBddOspf() {
    BDD headerBdd = flowHeadersToBdd(BASE_FLOW, _packet);
    assertThat(
        headerBdd.imp(_packet.getSrcIp().value(Ip.FIRST_CLASS_A_PRIVATE_IP.asLong())), isOne());
    assertThat(
        headerBdd.imp(_packet.getDstIp().value(Ip.FIRST_CLASS_B_PRIVATE_IP.asLong())), isOne());
    assertThat(headerBdd.imp(_packet.getIpProtocol().value(IpProtocol.OSPF)), isOne());
    assertThat(headerBdd.imp(_packet.getDscp().value(5)), isOne());
    assertThat(headerBdd.imp(_packet.getEcn().value(3)), isOne());
    assertThat(headerBdd.imp(_packet.getFragmentOffset().value(4)), isOne());
    assertThat(headerBdd.imp(_packet.getPacketLength().value(71)), isOne());
    // Protocol-specific values are not constrained.
    assertFalse(headerBdd.testsVars(_packet.getSrcPort().getVars()));
    assertFalse(headerBdd.testsVars(_packet.getDstPort().getVars()));
    assertFalse(headerBdd.testsVars(_packet.getIcmpCode().getBDDInteger().getVars()));
    assertFalse(headerBdd.testsVars(_packet.getIcmpType().getBDDInteger().getVars()));
    assertFalse(headerBdd.testsVars(_packet.getTcpAck()));
    assertFalse(headerBdd.testsVars(_packet.getTcpCwr()));
    assertFalse(headerBdd.testsVars(_packet.getTcpEce()));
    assertFalse(headerBdd.testsVars(_packet.getTcpFin()));
    assertFalse(headerBdd.testsVars(_packet.getTcpPsh()));
    assertFalse(headerBdd.testsVars(_packet.getTcpRst()));
    assertFalse(headerBdd.testsVars(_packet.getTcpSyn()));
    assertFalse(headerBdd.testsVars(_packet.getTcpUrg()));
  }

  /** Test that ICMP packets are converted correctly. */
  @Test
  public void testFlowHeadersToBddIcmp() {
    Flow flow =
        BASE_FLOW.toBuilder().setIpProtocol(IpProtocol.ICMP).setIcmpCode(5).setIcmpType(7).build();
    BDD headerBdd = flowHeadersToBdd(flow, _packet);
    assertThat(headerBdd.imp(_packet.getIpProtocol().value(IpProtocol.ICMP)), isOne());
    assertThat(headerBdd.imp(_packet.getIcmpCode().value(5)), isOne());
    assertThat(headerBdd.imp(_packet.getIcmpType().value(7)), isOne());
    // TCP/UDP fields are not constrained
    assertFalse(headerBdd.testsVars(_packet.getSrcPort().getVars()));
    assertFalse(headerBdd.testsVars(_packet.getDstPort().getVars()));
    assertFalse(headerBdd.testsVars(_packet.getTcpAck()));
    assertFalse(headerBdd.testsVars(_packet.getTcpCwr()));
    assertFalse(headerBdd.testsVars(_packet.getTcpEce()));
    assertFalse(headerBdd.testsVars(_packet.getTcpFin()));
    assertFalse(headerBdd.testsVars(_packet.getTcpPsh()));
    assertFalse(headerBdd.testsVars(_packet.getTcpRst()));
    assertFalse(headerBdd.testsVars(_packet.getTcpSyn()));
    assertFalse(headerBdd.testsVars(_packet.getTcpUrg()));
  }

  @Test
  public void testFlowHeadersToBddTcp() {
    Flow flow =
        BASE_FLOW.toBuilder()
            .setIpProtocol(IpProtocol.TCP)
            .setSrcPort(22)
            .setDstPort(55)
            .setTcpFlags(TcpFlags.builder().setAck(true).setSyn(true).build())
            .build();
    BDD headerBdd = flowHeadersToBdd(flow, _packet);
    assertThat(headerBdd.imp(_packet.getIpProtocol().value(IpProtocol.TCP)), isOne());
    assertThat(headerBdd.imp(_packet.getSrcPort().value(22)), isOne());
    assertThat(headerBdd.imp(_packet.getDstPort().value(55)), isOne());
    assertThat(headerBdd.imp(_packet.getTcpAck()), isOne());
    assertThat(headerBdd.imp(_packet.getTcpCwr().not()), isOne());
    assertThat(headerBdd.imp(_packet.getTcpEce().not()), isOne());
    assertThat(headerBdd.imp(_packet.getTcpFin().not()), isOne());
    assertThat(headerBdd.imp(_packet.getTcpPsh().not()), isOne());
    assertThat(headerBdd.imp(_packet.getTcpRst().not()), isOne());
    assertThat(headerBdd.imp(_packet.getTcpSyn()), isOne());
    assertThat(headerBdd.imp(_packet.getTcpUrg().not()), isOne());
    // ICMP code and type are not constrained
    assertFalse(headerBdd.testsVars(_packet.getIcmpCode().getBDDInteger().getVars()));
    assertFalse(headerBdd.testsVars(_packet.getIcmpType().getBDDInteger().getVars()));
  }

  @Test
  public void testFlowHeadersToBddUdp() {
    Flow flow =
        BASE_FLOW.toBuilder().setIpProtocol(IpProtocol.UDP).setSrcPort(22).setDstPort(55).build();
    BDD headerBdd = flowHeadersToBdd(flow, _packet);
    assertThat(headerBdd.imp(_packet.getIpProtocol().value(IpProtocol.UDP)), isOne());
    assertThat(headerBdd.imp(_packet.getSrcPort().value(22)), isOne());
    assertThat(headerBdd.imp(_packet.getDstPort().value(55)), isOne());
    // ICMP code and type, TCP flags are not constrained
    assertFalse(headerBdd.testsVars(_packet.getIcmpCode().getBDDInteger().getVars()));
    assertFalse(headerBdd.testsVars(_packet.getIcmpType().getBDDInteger().getVars()));
    assertFalse(headerBdd.testsVars(_packet.getTcpAck()));
    assertFalse(headerBdd.testsVars(_packet.getTcpCwr()));
    assertFalse(headerBdd.testsVars(_packet.getTcpEce()));
    assertFalse(headerBdd.testsVars(_packet.getTcpFin()));
    assertFalse(headerBdd.testsVars(_packet.getTcpPsh()));
    assertFalse(headerBdd.testsVars(_packet.getTcpRst()));
    assertFalse(headerBdd.testsVars(_packet.getTcpSyn()));
    assertFalse(headerBdd.testsVars(_packet.getTcpUrg()));
  }
}


text:
select
	case
		when d.datname is not null then true
		else false
	end as database_exists
from (select 1) a
left outer join pg_database d on d.datname = ''{0}'';


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html401/loose.dtd"><meta name="GENERATOR" content="Mole: The Scheme Source Code Digger"><title>API documentation for SSAX-SXML</title><meta name='keywords' content=''>

API documentation for SSAX-SXML

On the index page, the primary high-level API functions are presented:

Obtaining the SXML document from XML (HTML) by URI

f:  sxml:document

High-level functions called by `sxml:document'

f:  ssax:xml->sxml

f:  html->sxml

f:  open-input-resource

SXPath: XPath for SXML

f:  txpath

f:  sxpath

SXML Transformations

STX: Scheme-enabled XSLT Processor

f:  stx:make-stx-stylesheet

f:  stx:transform-dynamic

Pre-post-order transformations

f:  pre-post-order

XPathLink: a Query Language with XLink support

f:  xlink:documents

f:  sxpath/c

SXML modifications

f:  sxml:modify

f:  sxml:modify!

DDO SXPath: the Polynomial-Time XPath Implementation

f:  ddo:sxpath

Lazy SXML processing

f:  lazy:xml->sxml

f:  lazy:sxpath

Lower-level infrastructure for lazy SXML processing

f:  lazy:result->list

f:  lazy:node->sxml

SXML Serialization

f:  srl:sxml->xml

f:  srl:sxml->xml-noindent

f:  srl:sxml->html

f:  srl:sxml->html-noindent

Parameterizing the SXML serializer

f:  srl:parameterizable

Obtaining the SXML document from XML (HTML) by URI

sxml:document

(define (sxml:document req-uri . namespace-prefix-assig)
 ... Full Code ... )

 procedure sxml:document :: REQ-URI [NAMESPACE-PREFIX-ASSIG] ->
                             -> SXML-TREE

 Obtain a [possibly, remote] document by its URI
 Supported URI formats:  local file and HTTP schema
 Supported document formats:  XML and HTML

 REQ-URI - a string that contains the URI of the requested document
 NAMESPACE-PREFIX-ASSIG - is passed as-is to the SSAX parser: there it is
  used for assigning certain user prefixes to certain namespaces.
  NAMESPACE-PREFIX-ASSIG is an optional argument and has an effect for an
  XML resource only. For an HTML resource requested, NAMESPACE-PREFIX-ASSIG
  is silently ignored.

 Result: the SXML representation for the requested document

High-level functions called by `sxml:document'

ssax:xml->sxml

(define (ssax:xml->sxml port namespace-prefix-assig)
 ... Full Code ... )

html->sxml

(define html->sxml
 ... Full Code ... )

open-input-resource

(define (open-input-resource req-uri)
 ... Full Code ... )

 Opens an input port for a resource
  REQ-URI - a string representing a URI of the resource
 An input port is returned if there were no errors. In case of an error,
 the function returns #f and displays an error message as a side effect.
 Doesn't raise any exceptions.

SXPath: XPath for SXML

txpath

(define txpath
 ... Full Code ... )

  xpath-string - an XPath location path (a string)
  ns-binding - declared namespace prefixes (an optional argument)
  ns-binding = (list  (prefix . uri)
                      (prefix . uri)
                      ...)
  prefix - a symbol
  uri - a string

 The returned result:   (lambda (node . var-binding) ...)
                   or   #f
  #f - signals of a parse error (error message is printed as a side effect
 during parsing)
  (lambda (node . var-binding) ...)  - an SXPath function
  node - a node (or a node-set) of the SXML document
  var-binding - XPath variable bindings (an optional argument)
  var-binding = (list  (var-name . value)
                       (var-name . value)
                       ...)
  var-name - (a symbol) a name of a variable
  value - its value. The value can have the following type: boolean, number,
 string, nodeset. NOTE: a node must be represented as a singleton nodeset

 Administrative SXPath variables:
  *root* - if presented in the 'var-binding', its value (a node or a nodeset)
 specifies the root of the SXML document

sxpath

(define (sxpath path . ns-binding)
 ... Full Code ... )

 Evaluate an abbreviated SXPath
	sxpath:: AbbrPath -> Converter, or
	sxpath:: AbbrPath -> Node|Nodeset -> Nodeset
 AbbrPath is a list. It is translated to the full SXPath according
 to the following rewriting rules
 (sxpath '()) -> (node-join)
 (sxpath '(path-component ...)) ->
		(node-join (sxpath1 path-component) (sxpath '(...)))
 (sxpath1 '//) -> (sxml:descendant-or-self sxml:node?)
 (sxpath1 '(equal? x)) -> (select-kids (node-equal? x))
 (sxpath1 '(eq? x))    -> (select-kids (node-eq? x))
 (sxpath1 '(*or* ...))  -> (select-kids (ntype-names??
                                          (cdr '(*or* ...))))
 (sxpath1 '(*not* ...)) -> (select-kids (sxml:complement
                                         (ntype-names??
                                          (cdr '(*not* ...)))))
 (sxpath1 '(ns-id:* x)) -> (select-kids
                                      (ntype-namespace-id?? x))
 (sxpath1 ?symbol)     -> (select-kids (ntype?? ?symbol))
 (sxpath1 ?string)     -> (txpath ?string)
 (sxpath1 procedure)   -> procedure
 (sxpath1 '(?symbol ...)) -> (sxpath1 '((?symbol) ...))
 (sxpath1 '(path reducer ...)) ->
		(node-reduce (sxpath path) (sxpathr reducer) ...)
 (sxpathr number)      -> (node-pos number)
 (sxpathr path-filter) -> (filter (sxpath path-filter))

SXML Transformations

STX: Scheme-enabled XSLT Processor

stx:make-stx-stylesheet

(define (stx:make-stx-stylesheet stx-tree)
 ... Full Code ... )

 Generates an stx:stylesheet from a stylesheet represented as <stx-tree>
 in SXML format

stx:transform-dynamic

(define (stx:transform-dynamic doc sst-sxml)
 ... Full Code ... )

 transformate given SXML document <doc> using stylesheet <sst> in SXML
 format

Pre-post-order transformations

pre-post-order

(define (pre-post-order tree bindings)
 ... Full Code ... )

 procedure: pre-post-order TREE BINDINGS

	          Traversal of an SXML tree or a grove:
			a <Node> or a <Nodelist>

 A <Node> and a <Nodelist> are mutually-recursive datatypes that
 underlie the SXML tree:
	<Node> ::= (name . <Nodelist>) | "text string"
 An (ordered) set of nodes is just a list of the constituent nodes:
 	<Nodelist> ::= (<Node> ...)
 Nodelists, and Nodes other than text strings are both lists. A
 <Nodelist> however is either an empty list, or a list whose head is
 not a symbol (an atom in general). A symbol at the head of a node is
 either an XML name (in which case it's a tag of an XML element), or
 an administrative name such as '@'.
 See SXPath.scm and SSAX.scm for more information on SXML.

 Pre-Post-order traversal of a tree and creation of a new tree:
	pre-post-order:: <tree> x <bindings> -> <new-tree>
 where
 <bindings> ::= (<binding> ...)
 <binding> ::= (<trigger-symbol> *preorder* . <handler>) |
               (<trigger-symbol> *macro* . <handler>) |
		(<trigger-symbol> <new-bindings> . <handler>) |
		(<trigger-symbol> . <handler>)
 <trigger-symbol> ::= XMLname | *text* | *default*
 <handler> :: <trigger-symbol> x [<tree>] -> <new-tree>

 The pre-post-order function visits the nodes and nodelists
 pre-post-order (depth-first).  For each <Node> of the form (name
 <Node> ...) it looks up an association with the given 'name' among
 its <bindings>. If failed, pre-post-order tries to locate a
 *default* binding. It's an error if the latter attempt fails as
 well.  Having found a binding, the pre-post-order function first
 checks to see if the binding is of the form
	(<trigger-symbol> *preorder* . <handler>)
 If it is, the handler is 'applied' to the current node. Otherwise,
 the pre-post-order function first calls itself recursively for each
 child of the current node, with <new-bindings> prepended to the
 <bindings> in effect. The result of these calls is passed to the
 <handler> (along with the head of the current <Node>). To be more
 precise, the handler is _applied_ to the head of the current node
 and its processed children. The result of the handler, which should
 also be a <tree>, replaces the current <Node>. If the current <Node>
 is a text string or other atom, a special binding with a symbol
 *text* is looked up.

 A binding can also be of a form
	(<trigger-symbol> *macro* . <handler>)
 This is equivalent to *preorder* described above. However, the result
 is re-processed again, with the current stylesheet.

XPathLink: a Query Language with XLink support

xlink:documents

(define xlink:documents
 ... Full Code ... )

 procedure xlink:documents :: {REQ-URI}+  -> (listof SXML-TREE)
 procedure xlink:documents-embed :: {REQ-URI}+  -> (listof SXML-TREE)

 Both `xlink:documents' and `xlink:documents-embed' accept one or more
 strings as their arguments. Each string supplied denotes the URI of the
 requested document to be loaded. The requested document(s) are loaded
 and are represented in SXML. All XLink links declared in these document(s)
 are represented as a set of SXLink arcs. If any XLink links refer to XLink
 linkbases [<a href="http://www.w3.org/TR/xlink/#xlg">XLink</a>],
 these linkbases are additionally loaded, for additional SXLink arcs
 declared there.

 The starting resource for each SXLink arc is determined:
 1. For each SXML document loaded, the function `xlink:document' adds all
    SXLink arcs whose starting resource is located within this document, to
    the auxiliary list of its document node (*TOP*).
 2. The function 'xlink:documents-embed' embeds each SXLink arc into its
    starting resource-node, via auxiliary list of that node. For text nodes
    serving for starting resources, their SXLink arcs are stored in the
    auxiliary list of the document node (*TOP*), since SXML text nodes do
    not support their own auxiliary lists.

 Supported URI formats:
  + local file
  + http:// schema

 Supported document formats: XML and HTML. In the case of HTML,
 <A> hyperlinks are considered as XLink simple links.

 Result: (listof SXML-TREE)
 A particular SXML document can be located in this list using the
 function `xlink:find-doc'.

sxpath/c

(define sxpath/c
 ... Full Code ... )

 xpath-string - an XPath location path (a string)
 ns+na - can contain 'ns-binding' and/or 'num-ancestors' and/or none of them
 ns-binding - declared namespace prefixes (an optional argument)
  ns-binding ::= (listof (prefix . uri))
  prefix - a symbol
  uri - a string
 num-ancestors - number of ancestors required for resulting nodeset. Can
  generally be omitted and is than defaulted to 0, which denotes a _usual_
  nodeset. If a negative number, this signals that all ancestors should be
  remembered in the context

 Returns: (lambda (nodeset position+size var-binding) ...)
 position+size - the same to what was called 'context' in TXPath-1
 var-binding - XPath variable bindings (an optional argument)
  var-binding = (listof (var-name . value))
  var-name - (a symbol) a name of a variable
  value - its value. The value can have the following type: boolean, number,
  string, nodeset. NOTE: a node must be represented as a singleton nodeset

SXML modifications

sxml:modify

(define (sxml:modify . update-specifiers)
 ... Full Code ... )

 update-specifiers ::= (listof  update-specifier)
 update-specifier ::= (list  xpath-location-path  action  [action-parametes])
 xpath-location-path - addresses the node(s) to be transformed, in the form of
  XPath location path. If the location path is absolute, it addresses the
  node(s) with respect to the root of the document being transformed. If the
  location path is relative, it addresses the node(s) with respect to the
  node selected by the previous update-specifier. The location path in the
  first update-specifier always addresses the node(s) with respect to the
  root of the document. We'll further refer to the node with respect of which
  the location path is evaluated as to the base-node for this location path.
 action - specifies the modification to be made over each of the node(s)
  addressed by the location path. Possible actions are described below.
 action-parameters - additional parameters supplied for the action. The number
  of parameters and their semantics depend on the definite action.

 action ::= 'delete | 'delete-undeep |
            'insert-into | 'insert-following | 'insert-preceding |
            'replace |
            'move-into | 'move-following | 'move-preceding |
            handler
 'delete - deletes the node. Expects no action-parameters
 'delete-undeep - deletes the node, but keeps all its content (which thus
   moves to one level upwards in the document tree). Expects no
   action-parameters
 'insert-into - inserts the new node(s) as the last children of the given
   node. The new node(s) are specified in SXML as action-parameters
 'insert-following, 'insert-preceding - inserts the new node(s) after (before)
   the given node. Action-parameters are the same as for 'insert-into
 'replace - replaces the given node with the new node(s). Action-parameters
   are the same as for 'insert-into
 'rename - renames the given node. The node to be renamed must be a pair (i.e.
   not a text node). A single action-parameter is expected, which is to be
   a Scheme symbol to specify the new name of the given node
 'move-into - moves the given node to a new location. The single
   action-parameter is the location path, which addresses the new location
   with respect to the given node as the base node. The given node becomes
   the last child of the node selected by the parameter location path.
 'move-following, 'move-preceding - the given node is moved to the location
   respectively after (before) the node selected by the parameter location
   path
 handler ::= (lambda (node context base-node) ...)
 handler - specifies the required transformation. It is an arbitrary lambda
  that consumes the node and its context (the latter can be used for addressing
  the other node of the source document relative to the given node). The hander
  can return one of the following 2 things: a node or a nodeset.
   1. If a node is returned, than it replaces the source node in the result
  document
   2. If a nodeset is returned, than the source node is replaced by (multiple)
  nodes from this nodeset, in the same order in which they appear in the
  nodeset. In particular, if the empty nodeset is returned by the handler, the
  source node is removed from the result document and nothing is inserted
  instead.

  Returns either (lambda (doc) ...) or #f
  The latter signals of an error, an the error message is printed into stderr
  as a side effect. In the former case, the lambda can be applied to an SXML
  document and produces the new SXML document being the result of the
  modification specified.

sxml:modify!

(define (sxml:modify! . update-specifiers)
 ... Full Code ... )

 A highest-level function

DDO SXPath: the Polynomial-Time XPath Implementation

ddo:sxpath

(define ddo:sxpath
 ... Full Code ... )

 procedure ddo:sxpath :: query [ns-binding] [num-ancestors] ->
                          -> node-or-nodeset [var-binding] -> nodeset
 procedure ddo:txpath :: location-path [ns-binding] [num-ancestors] ->
                          -> node-or-nodeset [var-binding] -> nodeset

 Polynomial-time XPath implementation with distinct document order support.

 The API is identical to the API of a context-based SXPath (here we even use
 API helpers from "xpath-context.scm"). For convenience, below we repeat
 comments for the API (borrowed from "xpath-context.scm").

 query - a query in SXPath native syntax
 location-path - XPath location path represented as a string
 ns-binding - declared namespace prefixes (an optional argument)
  ns-binding ::= (listof (prefix . uri))
  prefix - a symbol
  uri - a string
 num-ancestors - number of ancestors required for resulting nodeset. Can
  generally be omitted and is than defaulted to 0, which denotes a
  _conventional_  nodeset. If a negative number, this signals that all
  ancestors should be remembered in the context.

 Returns: (lambda (node-or-nodeset . var-binding) ...)
 var-binding - XPath variable bindings (an optional argument)
  var-binding = (listof (var-name . value))
  var-name - (a symbol) a name of a variable
  value - its value. The value can have the following type: boolean, number,
  string, nodeset. NOTE: a node must be represented as a singleton nodeset.

 The result of applying the latter lambda to an SXML node or nodeset is the
 result of evaluating the query / location-path for that node / nodeset.

Lazy SXML processing

lazy:xml->sxml

(define (lazy:xml->sxml port namespace-prefix-assig)
 ... Full Code ... )

 Produces a lazy SXML document, which corresponds to reading a source
 document in a stream-wise fashion

lazy:sxpath

(define lazy:sxpath
 ... Full Code ... )

 Support for native sxpath syntax

Lower-level infrastructure for lazy SXML processing

lazy:result->list

(define (lazy:result->list nodeset)
 ... Full Code ... )

 Converts the lazy result into a list, by forcing all the promises one by one

lazy:node->sxml

(define (lazy:node->sxml node)
 ... Full Code ... )

 Converts the lazy node to SXML, by forcing all of its descendants
 The node itself is not a promise

SXML Serialization

srl:sxml->xml

(define (srl:sxml->xml sxml-obj . port-or-filename)
 ... Full Code ... )

 procedure srl:sxml->xml :: SXML-OBJ [PORT-OR-FILENAME] -> STRING|unspecified

 Serializes the `sxml-obj' into XML, with indentation to facilitate
 readability by a human.

 sxml-obj - an SXML object (a node or a nodeset) to be serialized
 port-or-filename - an output port or an output file name, an optional
  argument
 If `port-or-filename' is not supplied, the functions return a string that
 contains the serialized representation of the `sxml-obj'.
 If `port-or-filename' is supplied and is a port, the functions write the
 serialized representation of `sxml-obj' to this port and return an
 unspecified result.
 If `port-or-filename' is supplied and is a string, this string is treated as
 an output filename, the serialized representation of `sxml-obj' is written to
 that filename and an unspecified result is returned. If a file with the given
 name already exists, the effect is unspecified.

srl:sxml->xml-noindent

(define (srl:sxml->xml-noindent sxml-obj . port-or-filename)
 ... Full Code ... )

 procedure srl:sxml->xml-noindent :: SXML-OBJ [PORT-OR-FILENAME] ->
                                      -> STRING|unspecified

 Serializes the `sxml-obj' into XML, without indentation.

srl:sxml->html

(define (srl:sxml->html sxml-obj . port-or-filename)
 ... Full Code ... )

 procedure srl:sxml->html :: SXML-OBJ [PORT-OR-FILENAME] -> STRING|unspecified

 Serializes the `sxml-obj' into HTML, with indentation to facilitate
 readability by a human.

 sxml-obj - an SXML object (a node or a nodeset) to be serialized
 port-or-filename - an output port or an output file name, an optional
  argument
 If `port-or-filename' is not supplied, the functions return a string that
 contains the serialized representation of the `sxml-obj'.
 If `port-or-filename' is supplied and is a port, the functions write the
 serialized representation of `sxml-obj' to this port and return an
 unspecified result.
 If `port-or-filename' is supplied and is a string, this string is treated as
 an output filename, the serialized representation of `sxml-obj' is written to
 that filename and an unspecified result is returned. If a file with the given
 name already exists, the effect is unspecified.

srl:sxml->html-noindent

(define (srl:sxml->html-noindent sxml-obj . port-or-filename)
 ... Full Code ... )

 procedure srl:sxml->html-noindent :: SXML-OBJ [PORT-OR-FILENAME] ->
                                       -> STRING|unspecified

 Serializes the `sxml-obj' into HTML, without indentation.

Parameterizing the SXML serializer

srl:parameterizable

(define (srl:parameterizable sxml-obj . port-or-filename+params)
 ... Full Code ... )

 procedure srl:parameterizable :: SXML-OBJ [PORT] {PARAM}* ->
                                    -> STRING|unspecified
 sxml-obj - an SXML object to serialize
 param ::= (cons param-name param-value)
 param-name ::= symbol

 1. cdata-section-elements
 value ::= (listof sxml-elem-name)
 sxml-elem-name ::= symbol

 2. indent
 value ::= 'yes | #t | 'no | #f | whitespace-string

 3. method
 value ::= 'xml | 'html

 4. ns-prefix-assig
 value ::= (listof (cons prefix namespace-uri))
 prefix ::= symbol
 namespace-uri ::= string

 5. omit-xml-declaration?
 value ::= 'yes | #t | 'no | #f

 6. standalone
 value ::= 'yes | #t | 'no | #f | 'omit

 7. version
 value ::= string | number

 ATTENTION: If a parameter name is unexpected or a parameter value is
 ill-formed, the parameter is silently ignored. Probably, a warning message
 in such a case would be more appropriate.

 Example:
 (srl:parameterizable
   '(tag (@ (attr "value")) (nested "text node") (empty))
   (current-output-port)
   '(method . xml)  ; XML output method is used by default
   '(indent . "\t")  ; use a single tabulation to indent nested elements
   '(omit-xml-declaration . #f)  ; add XML declaration
   '(standalone . yes)  ; denote a standalone XML document
   '(version . "1.0"))  ; XML version


text:
/*
 * Directive [sticky]
 *
 * use in:    HTML tags
 * effect:    on scroll the tagged dom element will recieve css-class 'position-fixed' while beyond the upper viewport border
*/

import {
    Directive,
    ElementRef,
    EventEmitter,
    HostListener,
    Output
} from "@angular/core";

@Directive({
    selector: '[sticky]',
    host: { '(window:scroll)': 'track($event)' }
})
export class StickyScrollDirective {

    constructor(
        private _element: ElementRef
    ) {

    }

    @HostListener('window:scroll', ['$event'])
    handleScrollEvent(e) {
        if (window.pageYOffset > this._element.nativeElement.offsetTop) {
            this._element.nativeElement.classList.add('position-fixed');
        } else {
            this._element.nativeElement.classList.remove('position-fixed');
        }
    }
}


text:
package org.apache.geronimo.gshell.artifact;

import java.io.File;
import java.io.Serializable;

/**
 * Defines an artifact (groupId, artifactId, version, etc).
 *
 * @version $Rev$ $Date$
 */
public class Artifact
    implements Serializable, Cloneable
{
    private static final long serialVersionUID = 1;

    public static final String DEFAULT_TYPE = "jar";

    private String group;

    private String name;

    private String classifier;

    private String type;

    private String version;

    private File file;

    public String toString() {
        return getId();
    }

    public String getGroup() {
        return group;
    }

    public void setGroup(final String group) {
        this.group = group;
    }

    public String getName() {
        return name;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public String getClassifier() {
        return classifier;
    }

    public void setClassifier(final String classifier) {
        this.classifier = classifier;
    }

    public String getType() {
        if (type == null) {
            return DEFAULT_TYPE;
        }
        return type;
    }

    public void setType(final String type) {
        this.type = type;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(final String version) {
        this.version = version;
    }

    public File getFile() {
        return file;
    }

    public void setFile(final File file) {
        this.file = file;
    }

    public String getId() {
        if (getClassifier() != null) {
            return getGroup() + ":" + getName() + ":" + getClassifier() + ":" + getVersion() + ":" + getType();
        }
        else {
            return getGroup() + ":" + getName() + ":" + getVersion() + ":" + getType();
        }
    }

    @Override
    protected Object clone() {
        try {
            return super.clone();
        }
        catch (CloneNotSupportedException e) {
            throw new InternalError();
        }
    }
}


text:
package io.inkstand.scribble.rules;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assume.assumeTrue;

import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runners.model.Statement;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

/**
 * Created by Gerald Muecke on 18.11.2015.
 */
@RunWith(MockitoJUnitRunner.class)
public class SystemPropertiesTest  {

    public static final String A_TEST_PROPERTY = "a_test_property";
    /**
     * The class under test
     */
    @InjectMocks
    private SystemProperties subject;

    @Mock
    private Description description;

    @Test
    public void testApply() throws Throwable {

        //prepare
        assumeTrue(System.getProperty(A_TEST_PROPERTY) == null);
        Statement stmt = new Statement() {

            @Override
            public void evaluate() throws Throwable {
                System.setProperty(A_TEST_PROPERTY, "someValue");
                assertEquals("someValue", System.getProperty(A_TEST_PROPERTY) );
            }
        };

        //act
        subject.apply(stmt, description).evaluate();

        //assert
        assertNull(System.getProperty(A_TEST_PROPERTY));
    }
}


text:
using System;
using System.Linq;
using System.Net;
using EnsureThat;
using MyCouch.Net;

namespace MyCouch
{
    public class DbConnectionInfo : ConnectionInfo
    {
        public string DbName { get; }

        public DbConnectionInfo(string serverAddress, string dbName) : this(new Uri(serverAddress), dbName) { }
        public DbConnectionInfo(Uri serverAddress, string dbName) : base(UriMagic.Abracadabra(serverAddress.OriginalString, dbName))
        {
            Ensure.String.IsNotNullOrWhiteSpace(dbName, nameof(dbName));

            DbName = dbName.Trim(' ', '/');
        }
    }

    public class ServerConnectionInfo : ConnectionInfo
    {
        public ServerConnectionInfo(string serverAddress) : this(new Uri(serverAddress)) { }
        public ServerConnectionInfo(Uri serverAddress) : base(serverAddress) { }
    }

    public abstract class ConnectionInfo
    {
        public Uri Address { get; }
        public TimeSpan? Timeout { get; set; }
        public BasicAuthString BasicAuth { get; set; }
        public bool AllowAutoRedirect { get; set; } = false;
        public bool ExpectContinue { get; set; } = false;
        public bool UseProxy { get; set; } = true;
        public IWebProxy Proxy { get; set; } = null;

        protected ConnectionInfo(Uri address)
        {
            Ensure.Any.IsNotNull(address, nameof(address));

            Address = RemoveUserInfoFrom(address);

            if (!string.IsNullOrWhiteSpace(address.UserInfo))
            {
                var userInfoParts = ExtractUserInfoPartsFrom(address);
                BasicAuth = new BasicAuthString(userInfoParts[0], userInfoParts[1]);
            }
        }

        private Uri RemoveUserInfoFrom(Uri address)
        {
            return new Uri(address.GetComponents(UriComponents.AbsoluteUri & ~UriComponents.UserInfo, UriFormat.UriEscaped));
        }

        private string[] ExtractUserInfoPartsFrom(Uri address)
        {
            return address.UserInfo
                .Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries)
                .Select(Uri.UnescapeDataString)
                .ToArray();
        }
    }
}