text:
package net.iturrioz.marranita.domain;

import android.support.annotation.Nullable;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Jokalarie {

    private final String JSON_ID = "id";
    private final String JSON_PUNTUK = "puntuk";
    private final String JSON_KARTAK = "kartak";
    private final String JSON_ESKATUTAKOK = "eskatutakok";
    private final String JSON_BAZAK = "bazak";
    private final String JSON_JOKATUTAKOA = "jokatutakoa";

    final String id;

    private int puntuk;
    private Karta[] kartak = new Karta[0];
    private int eskatutakok = -1;
    private int bazak = 0;
    private Karta jokatutakoa;

    public Jokalarie(final String id, final int puntuk) {
        this.id = id;
        this.puntuk = puntuk;
    }

    public Jokalarie(final String json) throws JSONException {
        final JSONObject obj = new JSONObject(json);
        this.id = obj.getString(JSON_ID);
        puntuk = obj.getInt(JSON_PUNTUK);
        final JSONArray jsonArray = obj.getJSONArray(JSON_KARTAK);
        final Karta[] kartak = new Karta[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            kartak[i] = new Karta(jsonArray.getString(i));
        }
        this.kartak = kartak;
        eskatutakok = obj.getInt(JSON_ESKATUTAKOK);
        bazak = obj.getInt(JSON_BAZAK);
        final String jokatutakoaJson = obj.optString(JSON_JOKATUTAKOA, null);
        jokatutakoa = jokatutakoaJson != null ? new Karta(jokatutakoaJson) : null;
    }

    public String getJsonString() throws JSONException {
        final JSONObject retVal = new JSONObject();
        retVal.put(JSON_ID, id);
        retVal.put(JSON_PUNTUK, puntuk);
        final List<String> kartakJson = new ArrayList<String>();
        for (Karta karta : kartak) {
            kartakJson.add(karta.getJsonString());
        }
        final JSONArray jsonArray = new JSONArray(kartakJson);
        retVal.put(JSON_KARTAK, jsonArray);
        retVal.put(JSON_ESKATUTAKOK, eskatutakok);
        retVal.put(JSON_BAZAK, bazak);
        retVal.put(JSON_JOKATUTAKOA, jokatutakoa != null ? jokatutakoa.getJsonString() : null);
        return retVal.toString();
    }

    public int getPuntuk() {
        return puntuk;
    }

    public String getId() {
        return id;
    }

    public Karta[] getKartak() {
        return kartak;
    }

    public void setKartak(Karta[] kartak) {
        this.kartak = kartak;
        bazak = 0;
        eskatutakok = -1;
        jokatutakoa = null;
    }

    public Karta getJokatutakoa() {
        return jokatutakoa;
    }

    public int getEskatutakok() {
        return eskatutakok;
    }

    public void setEskatutakok(final int eskatutakok) {
        this.eskatutakok = eskatutakok;
    }

    public void kartaJokatu(final int KartaIndex) {
        final Karta jokatutakoKarta = kartak[KartaIndex];
        jokatutakoa = jokatutakoKarta;

        kartak = Collections2.filter(Arrays.asList(kartak), new Predicate<Karta>() {
            @Override
            public boolean apply(@Nullable final Karta karta) {
                return !jokatutakoKarta.equals(karta);
            }
        }).toArray(new Karta[0]);
    }

    public void bazaGehitu() {
        this.bazak += 1;
    }

    public void jokatutakoaKendu () {
        jokatutakoa = null;
    }

    public void puntukGehitu(final boolean isUrrek) {
        final int puntuk;
        if (bazak == eskatutakok) {
            puntuk = 10 + eskatutakok * 5;
        } else {
            puntuk = -5 * Math.abs(eskatutakok - bazak);
        }
        this.puntuk += puntuk * (isUrrek ? 2 : 1);
    }

    public String getBazaTextue() {
        return eskatutakok == -1 ? "" : bazak + " / " + eskatutakok;
    }

    @Override
    public boolean equals(final Object o) {
        return o instanceof Jokalarie && equals((Jokalarie)o);
    }

    public boolean equals(final Jokalarie jokalarie) {
        return jokalarie != null &&
               puntuk == jokalarie.puntuk &&
               Arrays.equals(kartak, jokalarie.kartak) &&
               eskatutakok == jokalarie.eskatutakok &&
               bazak == jokalarie.bazak &&
               ((jokatutakoa != null && jokatutakoa.equals(jokalarie.jokatutakoa)) ||
                       (jokatutakoa == null && jokatutakoa == jokalarie.jokatutakoa));
    }
}


text:
from __future__ import annotations

import numpy as np

from progressivis.core.module import Module, ReturnRunStep
from progressivis.core.slot import SlotDescriptor
from progressivis.core.bitmap import bitmap
from progressivis.core.utils import indices_len
from ..io import Variable
from ..stats import Min, Max
from ..utils.psdict import PsDict
from . import BaseTable, Table, TableSelectedView
from .module import TableModule
from .hist_index import HistogramIndex

# from .mod_impl import ModuleImpl

from typing import Optional, Any, cast, Iterable

# def _get_physical_table(t):
#     return t if t.base is None else _get_physical_table(t.base)

class _Selection:
    def __init__(self, values: Optional[bitmap] = None):
        self._values = bitmap([]) if values is None else values

    def update(self, values: Iterable[int]) -> None:
        self._values.update(values)

    def remove(self, values: Iterable[int]) -> None:
        self._values = self._values - bitmap(values)

    def assign(self, values: Iterable[int]) -> None:
        self._values = bitmap(values)

    def add(self, values: Iterable[int]) -> None:
        self._values |= bitmap(values)

class RangeQueryImpl:  # (ModuleImpl):
    def __init__(self, column: list[str], approximate: bool):
        super(RangeQueryImpl, self).__init__()
        self._table: Optional[BaseTable] = None
        self._column = column
        # self.bins = None
        # self._hist_index = hist_index
        self._approximate = approximate
        self.result: Optional[_Selection] = None
        self.is_started = False

    def resume(
        self,
        hist_index: HistogramIndex,
        lower: float,
        upper: float,
        limit_changed: bool,
        created: Optional[bitmap] = None,
        updated: Optional[bitmap] = None,
        deleted: Optional[bitmap] = None,
    ) -> None:
        assert self.result
        if limit_changed:
            new_sel = hist_index.range_query(
                lower, upper, approximate=self._approximate
            )
            self.result.assign(new_sel)
            return
        if updated:
            self.result.remove(updated)
            # res = self._eval_to_ids(limit, updated)
            res = hist_index.restricted_range_query(
                lower, upper, only_locs=updated, approximate=self._approximate
            )
            self.result.add(res)
        if created:
            res = hist_index.restricted_range_query(
                lower, upper, only_locs=created, approximate=self._approximate
            )
            self.result.update(res)
        if deleted:
            self.result.remove(deleted)

    def start(
        self,
        table: BaseTable,
        hist_index: HistogramIndex,
        lower: float,
        upper: float,
        limit_changed: bool,
        created: Optional[bitmap] = None,
        updated: Optional[bitmap] = None,
        deleted: Optional[bitmap] = None,
    ) -> None:
        self._table = table
        self.result = _Selection()
        self.is_started = True
        self.resume(hist_index, lower, upper, limit_changed, created, updated, deleted)

class RangeQuery(TableModule):
    """ """

    parameters = [
        ("column", np.dtype(object), "unknown"),
        ("watched_key_lower", np.dtype(object), ""),
        ("watched_key_upper", np.dtype(object), ""),
        # ('hist_index', object, None) # to improve ...
    ]
    inputs = [
        SlotDescriptor("table", type=Table, required=True),
        SlotDescriptor("lower", type=Table, required=False),
        SlotDescriptor("upper", type=Table, required=False),
        SlotDescriptor("min", type=PsDict, required=False),
        SlotDescriptor("max", type=PsDict, required=False),
        SlotDescriptor("hist", type=Table, required=True),
    ]
    outputs = [
        SlotDescriptor("min", type=Table, required=False),
        SlotDescriptor("max", type=Table, required=False),
    ]

    def __init__(
        self,
        # hist_index: Optional[HistogramIndex] = None,
        approximate: bool = False,
        **kwds: Any
    ) -> None:
        super(RangeQuery, self).__init__(**kwds)
        self._impl: RangeQueryImpl = RangeQueryImpl(self.params.column, approximate)
        # self._hist_index: Optional[HistogramIndex] = hist_index
        self._approximate = approximate
        self.default_step_size = 1000
        self.input_module: Optional[Module] = None
        self._min_table: Optional[PsDict] = None
        self._max_table: Optional[PsDict] = None
        self.hist_index: Optional[HistogramIndex] = None

    # @property
    # def hist_index(self) -> Optional[HistogramIndex]:
    #     return self._hist_index

    # @hist_index.setter
    # def hist_index(self, hi: HistogramIndex) -> None:
    #     self._hist_index = hi
    #     self._impl = RangeQueryImpl(self._column, hi, approximate=self._approximate)
    @property
    def column(self) -> str:
        return str(self.params.column)

    @property
    def watched_key_lower(self) -> str:
        return self.params.watched_key_lower or self.column

    @property
    def watched_key_upper(self) -> str:
        return self.params.watched_key_upper or self.column

    def create_dependent_modules(
        self,
        input_module: Module,
        input_slot: str,
        min_: Optional[Module] = None,
        max_: Optional[Module] = None,
        min_value: Optional[Module] = None,
        max_value: Optional[Module] = None,
        hist_index: Optional[HistogramIndex] = None,
        **kwds: Any
    ) -> RangeQuery:
        if self.input_module is not None:  # test if already called
            return self
        scheduler = self.scheduler()
        params = self.params
        self.input_module = input_module
        self.input_slot = input_slot
        with scheduler:
            if hist_index is None:
                hist_index = HistogramIndex(
                    column=params.column, group=self.name, scheduler=scheduler
                )
            hist_index.input.table = input_module.output[input_slot]
            if min_ is None:
                min_ = Min(group=self.name, columns=[self.column], scheduler=scheduler)
                min_.input.table = hist_index.output.min_out
            if max_ is None:
                max_ = Max(group=self.name, columns=[self.column], scheduler=scheduler)
                max_.input.table = hist_index.output.max_out
            if min_value is None:
                min_value = Variable(group=self.name, scheduler=scheduler)
                min_value.input.like = min_.output.result

            if max_value is None:
                max_value = Variable(group=self.name, scheduler=scheduler)
                max_value.input.like = max_.output.result

            range_query = self
            range_query.hist_index = hist_index
            range_query.input.hist = hist_index.output.result
            range_query.input.table = input_module.output[input_slot]
            if min_value:
                range_query.input.lower = min_value.output.result
            if max_value:
                range_query.input.upper = max_value.output.result
            range_query.input.min = min_.output.result
            range_query.input.max = max_.output.result

        self.min = min_
        self.max = max_
        self.min_value = min_value
        self.max_value = max_value
        return range_query

    def _create_min_max(self) -> None:
        if self._min_table is None:
            self._min_table = PsDict({self.column: np.inf})
        if self._max_table is None:
            self._max_table = PsDict({self.column: -np.inf})

    def _set_minmax_out(self, attr_: str, val: float) -> None:
        d = {self.column: val}
        if getattr(self, attr_) is None:
            setattr(self, attr_, PsDict(d))
        else:
            getattr(self, attr_).update(d)

    def _set_min_out(self, val: float) -> None:
        return self._set_minmax_out("_min_table", val)

    def _set_max_out(self, val: float) -> None:
        return self._set_minmax_out("_max_table", val)

    def get_data(self, name: str) -> Any:
        if name == "min":
            return self._min_table
        if name == "max":
            return self._max_table
        return super(RangeQuery, self).get_data(name)

    def run_step(
        self, run_number: int, step_size: int, howlong: float
    ) -> ReturnRunStep:
        input_slot = self.get_input_slot("table")
        self._create_min_max()
        #
        # lower/upper
        #
        lower_slot = self.get_input_slot("lower")
        # lower_slot.update(run_number)
        upper_slot = self.get_input_slot("upper")
        limit_changed = False
        if lower_slot.deleted.any():
            lower_slot.deleted.next()
        if lower_slot.updated.any():
            lower_slot.updated.next()
            limit_changed = True
        if lower_slot.created.any():
            lower_slot.created.next()
            limit_changed = True
        if not (lower_slot is upper_slot):
            # upper_slot.update(run_number)
            if upper_slot.deleted.any():
                upper_slot.deleted.next()
            if upper_slot.updated.any():
                upper_slot.updated.next()
                limit_changed = True
            if upper_slot.created.any():
                upper_slot.created.next()
                limit_changed = True
        #
        # min/max
        #
        min_slot = self.get_input_slot("min")
        min_slot.clear_buffers()
        # min_slot.update(run_number)
        # min_slot.created.next()
        # min_slot.updated.next()
        # min_slot.deleted.next()
        max_slot = self.get_input_slot("max")
        max_slot.clear_buffers()
        # max_slot.update(run_number)
        # max_slot.created.next()
        # max_slot.updated.next()
        # max_slot.deleted.next()
        if (
            lower_slot.data() is None
            or upper_slot.data() is None
            or len(lower_slot.data()) == 0
            or len(upper_slot.data()) == 0
        ):
            return self._return_run_step(self.state_blocked, steps_run=0)
        lower_value = lower_slot.data().get(self.watched_key_lower)
        upper_value = upper_slot.data().get(self.watched_key_upper)
        if (
            lower_slot.data() is None
            or upper_slot.data() is None
            or min_slot.data() is None
            or max_slot.data() is None
            or len(min_slot.data()) == 0
            or len(max_slot.data()) == 0
        ):
            return self._return_run_step(self.state_blocked, steps_run=0)
        minv = min_slot.data().get(self.watched_key_lower)
        maxv = max_slot.data().get(self.watched_key_upper)
        if lower_value == "*":
            lower_value = minv
        elif (
            lower_value is None
            or np.isnan(lower_value)
            or lower_value < minv
            or lower_value >= maxv
        ):
            lower_value = minv
            limit_changed = True
        if upper_value == "*":
            upper_value = maxv
        elif (
            upper_value is None
            or np.isnan(upper_value)
            or upper_value > maxv
            or upper_value <= minv
            or upper_value <= lower_value
        ):
            upper_value = maxv
            limit_changed = True
        self._set_min_out(lower_value)
        self._set_max_out(upper_value)
        # input_slot.update(run_number)
        if not input_slot.has_buffered() and not limit_changed:
            return self._return_run_step(self.state_blocked, steps_run=0)
        # ...
        steps = 0
        deleted: Optional[bitmap] = None
        if input_slot.deleted.any():
            deleted = input_slot.deleted.next(length=step_size, as_slice=False)
            steps += indices_len(deleted)
        created: Optional[bitmap] = None
        if input_slot.created.any():
            created = input_slot.created.next(length=step_size, as_slice=False)
            steps += indices_len(created)
        updated: Optional[bitmap] = None
        if input_slot.updated.any():
            updated = input_slot.updated.next(length=step_size, as_slice=False)
            steps += indices_len(updated)
        input_table = input_slot.data()
        if self.result is None:
            self.result = TableSelectedView(input_table, bitmap([]))
        assert self._impl
        hist_slot = self.get_input_slot("hist")
        hist_slot.clear_buffers()
        if not self._impl.is_started:
            self._impl.start(
                input_table,
                cast(HistogramIndex, hist_slot.output_module),
                lower_value,
                upper_value,
                limit_changed,
                created=created,
                updated=updated,
                deleted=deleted,
            )
        else:
            self._impl.resume(
                cast(HistogramIndex, hist_slot.output_module),
                lower_value,
                upper_value,
                limit_changed,
                created=created,
                updated=updated,
                deleted=deleted,
            )
        assert self._impl.result
        self.selected.selection = self._impl.result._values
        return self._return_run_step(self.next_state(input_slot), steps)

redpajama_set_name: RedPajamaGithub


text:
"""Create a new admin user able to view the /reports endpoint."""
from getpass import getpass
import sys

from app import app, bcrypt

def main():
    """Main entry point for script."""
    password = sys.argv[1]

    return bcrypt.generate_password_hash(password)

if __name__ == '__main__':
    sys.exit(main())


text:
#include "cl_helper.h"
#include <stdio.h>
#include <stdlib.h>

const char* cl_err_code(cl_int err_in)
{
    switch (err_in) {
        case CL_SUCCESS:
            return "CL_SUCCESS";
        case CL_DEVICE_NOT_FOUND:
            return "CL_DEVICE_NOT_FOUND";
        case CL_DEVICE_NOT_AVAILABLE:
            return "CL_DEVICE_NOT_AVAILABLE";
        case CL_COMPILER_NOT_AVAILABLE:
            return "CL_COMPILER_NOT_AVAILABLE";
        case CL_MEM_OBJECT_ALLOCATION_FAILURE:
            return "CL_MEM_OBJECT_ALLOCATION_FAILURE";
        case CL_OUT_OF_RESOURCES:
            return "CL_OUT_OF_RESOURCES";
        case CL_OUT_OF_HOST_MEMORY:
            return "CL_OUT_OF_HOST_MEMORY";
        case CL_PROFILING_INFO_NOT_AVAILABLE:
            return "CL_PROFILING_INFO_NOT_AVAILABLE";
        case CL_MEM_COPY_OVERLAP:
            return "CL_MEM_COPY_OVERLAP";
        case CL_IMAGE_FORMAT_MISMATCH:
            return "CL_IMAGE_FORMAT_MISMATCH";
        case CL_IMAGE_FORMAT_NOT_SUPPORTED:
            return "CL_IMAGE_FORMAT_NOT_SUPPORTED";
        case CL_BUILD_PROGRAM_FAILURE:
            return "CL_BUILD_PROGRAM_FAILURE";
        case CL_MAP_FAILURE:
            return "CL_MAP_FAILURE";
        case CL_MISALIGNED_SUB_BUFFER_OFFSET:
            return "CL_MISALIGNED_SUB_BUFFER_OFFSET";
        case CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST:
            return "CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST";
        case CL_INVALID_VALUE:
            return "CL_INVALID_VALUE";
        case CL_INVALID_DEVICE_TYPE:
            return "CL_INVALID_DEVICE_TYPE";
        case CL_INVALID_PLATFORM:
            return "CL_INVALID_PLATFORM";
        case CL_INVALID_DEVICE:
            return "CL_INVALID_DEVICE";
        case CL_INVALID_CONTEXT:
            return "CL_INVALID_CONTEXT";
        case CL_INVALID_QUEUE_PROPERTIES:
            return "CL_INVALID_QUEUE_PROPERTIES";
        case CL_INVALID_COMMAND_QUEUE:
            return "CL_INVALID_COMMAND_QUEUE";
        case CL_INVALID_HOST_PTR:
            return "CL_INVALID_HOST_PTR";
        case CL_INVALID_MEM_OBJECT:
            return "CL_INVALID_MEM_OBJECT";
        case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR:
            return "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR";
        case CL_INVALID_IMAGE_SIZE:
            return "CL_INVALID_IMAGE_SIZE";
        case CL_INVALID_SAMPLER:
            return "CL_INVALID_SAMPLER";
        case CL_INVALID_BINARY:
            return "CL_INVALID_BINARY";
        case CL_INVALID_BUILD_OPTIONS:
            return "CL_INVALID_BUILD_OPTIONS";
        case CL_INVALID_PROGRAM:
            return "CL_INVALID_PROGRAM";
        case CL_INVALID_PROGRAM_EXECUTABLE:
            return "CL_INVALID_PROGRAM_EXECUTABLE";
        case CL_INVALID_KERNEL_NAME:
            return "CL_INVALID_KERNEL_NAME";
        case CL_INVALID_KERNEL_DEFINITION:
            return "CL_INVALID_KERNEL_DEFINITION";
        case CL_INVALID_KERNEL:
            return "CL_INVALID_KERNEL";
        case CL_INVALID_ARG_INDEX:
            return "CL_INVALID_ARG_INDEX";
        case CL_INVALID_ARG_VALUE:
            return "CL_INVALID_ARG_VALUE";
        case CL_INVALID_ARG_SIZE:
            return "CL_INVALID_ARG_SIZE";
        case CL_INVALID_KERNEL_ARGS:
            return "CL_INVALID_KERNEL_ARGS";
        case CL_INVALID_WORK_DIMENSION:
            return "CL_INVALID_WORK_DIMENSION";
        case CL_INVALID_WORK_GROUP_SIZE:
            return "CL_INVALID_WORK_GROUP_SIZE";
        case CL_INVALID_WORK_ITEM_SIZE:
            return "CL_INVALID_WORK_ITEM_SIZE";
        case CL_INVALID_GLOBAL_OFFSET:
            return "CL_INVALID_GLOBAL_OFFSET";
        case CL_INVALID_EVENT_WAIT_LIST:
            return "CL_INVALID_EVENT_WAIT_LIST";
        case CL_INVALID_EVENT:
            return "CL_INVALID_EVENT";
        case CL_INVALID_OPERATION:
            return "CL_INVALID_OPERATION";
        case CL_INVALID_GL_OBJECT:
            return "CL_INVALID_GL_OBJECT";
        case CL_INVALID_BUFFER_SIZE:
            return "CL_INVALID_BUFFER_SIZE";
        case CL_INVALID_MIP_LEVEL:
            return "CL_INVALID_MIP_LEVEL";
        case CL_INVALID_GLOBAL_WORK_SIZE:
            return "CL_INVALID_GLOBAL_WORK_SIZE";
        case CL_INVALID_PROPERTY:
            return "CL_INVALID_PROPERTY";
        default:
            return "UNKNOWN ERROR";
    }
}

void cl_print_prog_build_info_log(cl_program prog, cl_device_id did)
{
    /* Query info buffer length */
    size_t blen = 0;
    clGetProgramBuildInfo(prog, did, CL_PROGRAM_BUILD_LOG, 0, 0, &blen);
    /* Allocate needed buffer and query contents */
    char* buf = calloc(blen, 1);
    clGetProgramBuildInfo(prog, did, CL_PROGRAM_BUILD_LOG, blen, buf, 0);
    /* Print buffer and free it */
    printf("Build Log:\n%s\n", buf);
    free(buf);
}

int cl_choose_platform_and_device(cl_platform_id* plat_id, cl_device_id* dev_id)
{
    int found_id_pair = 0;
    /* Query available platform id count */
    cl_uint platform_id_cnt = 0;
    clGetPlatformIDs(0, 0, &platform_id_cnt);
    printf("Found %d platforms\n", platform_id_cnt);

    /* Allocate buffer to hold platform ids and fill it */
    cl_platform_id* platform_ids = calloc(platform_id_cnt, sizeof(cl_platform_id));
    clGetPlatformIDs(platform_id_cnt, platform_ids, 0);

    /* For each platform */
    for (size_t i = 0; i < platform_id_cnt; ++i) {
        cl_platform_id pid = platform_ids[i];
        /* Query available devices id count */
        cl_uint device_id_cnt = 0;
        clGetDeviceIDs(pid, CL_DEVICE_TYPE_ALL, 0, 0, &device_id_cnt);
        /* Show platform info */
        char plat_buf[256];
        clGetPlatformInfo(pid, CL_PLATFORM_VENDOR, sizeof(plat_buf), plat_buf, 0);
        printf("Platform %s (%d devices)\n", plat_buf, device_id_cnt);
        /* Allocate buffer to hold device ids and fill it */
        cl_device_id* device_ids = calloc(device_id_cnt, sizeof(cl_device_id));
        clGetDeviceIDs(pid, CL_DEVICE_TYPE_ALL, device_id_cnt, device_ids, 0);
        /* For each device */
        for (size_t j = 0; j < device_id_cnt; ++j) {
            cl_device_id did = device_ids[j];
            /* Get first pair */
            if (!found_id_pair) {
                *plat_id = pid;
                *dev_id = did;
                found_id_pair = 1;
            }
            /* Show device info */
            char dev_name_buf[256];
            clGetDeviceInfo(did, CL_DEVICE_NAME, sizeof(dev_name_buf), dev_name_buf, 0);
            char dev_type_buf[256];
            clGetDeviceInfo(did, CL_DEVICE_TYPE, sizeof(dev_type_buf), dev_type_buf, 0);
            printf("  Device %s (Type: %s)\n", dev_name_buf, dev_type_buf);
        }
        free(device_ids);
    }
    free(platform_ids);
    return found_id_pair;
}

void _cl_check_error(cl_int err, const char* operation, char* filename, int line)
{
    if (err != CL_SUCCESS) {
        fprintf(stderr, "Error during operation '%s', ", operation);
        fprintf(stderr, "in '%s' on line %d\n", filename, line);
        fprintf(stderr, "Error code was \"%s\" (%d)\n", cl_err_code(err), err);
        exit(EXIT_FAILURE);
    }
}


text:
require 'test_helper'

class LineItemsControllerTest < ActionDispatch::IntegrationTest
  # test "the truth" do
  #   assert true
  # end
end


text:
package com.mongodb;

import com.mongodb.util.TestCase;
import org.bson.BSONDecoder;
import org.bson.BasicBSONDecoder;
import org.bson.io.BasicOutputBuffer;
import org.bson.io.OutputBuffer;
import org.bson.types.ObjectId;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

public class DBRefTest extends TestCase {

    @Test
    public void testEqualsAndHashCode() {
       DBRef ref = new DBRef(getDatabase(), "foo.bar", 4);
       DBRef other = new DBRef(getDatabase(), "foo.bar", 4);
       assertEquals(ref, ref);
       assertEquals(ref, other);
       assertNotEquals(ref, new DBRefBase(getDatabase(), "foo.bar", 4));
       assertEquals(ref.hashCode(), other.hashCode());
    }

    @Test
    public void testDBRefBaseToString(){

        ObjectId id = new ObjectId("123456789012345678901234");
        DBRefBase ref = new DBRefBase(getDatabase(), "foo.bar", id);

        assertEquals("{ \"$ref\" : \"foo.bar\", \"$id\" : \"123456789012345678901234\" }", ref.toString());
    }

    @Test
    public void testDBRef(){

        DBRef ref = new DBRef(getDatabase(), "hello", "world");
        DBObject o = new BasicDBObject("!", ref);

        DBEncoder encoder = DefaultDBEncoder.FACTORY.create();
        OutputBuffer buf = new BasicOutputBuffer();

        encoder.writeObject(buf, o);

        DefaultDBCallback cb = new DefaultDBCallback( null );
        BSONDecoder decoder = new BasicBSONDecoder();
        decoder.decode( buf.toByteArray() , cb );
        DBObject read = cb.dbget();

        assertEquals("{\"!\":{\"$ref\":\"hello\",\"$id\":\"world\"}}", read.toString().replaceAll( " +" , "" ));
    }

    @Test
    public void testDBRefFetches(){
        DBCollection coll = collection;
        BasicDBObject obj = new BasicDBObject("_id", 321325243);
        coll.save(obj);

        DBRef ref = new DBRef(getDatabase(), coll.getName(), 321325243);
        DBObject deref = ref.fetch();

        assertTrue(deref != null);
        assertEquals(321325243, ((Number)deref.get("_id")).intValue());

        DBObject refobj = BasicDBObjectBuilder.start().add("$ref", coll.getName()).add("$id", 321325243).get();
        deref = DBRef.fetch(getDatabase(), refobj);

        assertTrue(deref != null);
        assertEquals(321325243, ((Number)deref.get("_id")).intValue());
    }

    @SuppressWarnings("unchecked")
	@Test
    public void testRefListRoundTrip(){
        DBCollection a = collection;
        List<DBRef> refs = new ArrayList<DBRef>();
        refs.add(new DBRef(getDatabase(), "other", 12));
        refs.add(new DBRef(getDatabase(), "other", 14));
        refs.add(new DBRef(getDatabase(), "other", 16));
        a.save( BasicDBObjectBuilder.start( "refs" , refs).get() );

        DBObject loaded = a.findOne();
        assertNotNull( loaded );
        List<DBRef> refsLoaded = (List<DBRef>) loaded.get("refs");
        assertNotNull( refsLoaded );
        assertEquals(3, refsLoaded.size());
        assertEquals(DBRef.class, refsLoaded.get(0).getClass());
        assertEquals(12, refsLoaded.get(0).getId());
        assertEquals(14, refsLoaded.get(1).getId());
        assertEquals(16, refsLoaded.get(2).getId());

    }

    @Test
    public void testRoundTrip(){
        DBCollection a = getDatabase().getCollection( collection.getName() + ".refroundtripa" );
        DBCollection b = getDatabase().getCollection( collection.getName() + ".refroundtripb" );
        a.drop();
        b.drop();

        a.save( BasicDBObjectBuilder.start( "_id" , 17 ).add( "n" , 111 ).get() );
        b.save( BasicDBObjectBuilder.start( "n" , 12 ).add( "l" , new DBRef( getDatabase() , a.getName() , 17 ) ).get() );

        assertEquals( 12 , b.findOne().get( "n" ) );
        assertEquals( DBRef.class , b.findOne().get( "l" ).getClass() );
        assertEquals( 111 , ((DBRef)(b.findOne().get( "l" ))).fetch().get( "n" ) );

    }

    @Test
    public void testFindByDBRef(){
        DBCollection b = getDatabase().getCollection( "b" );
        b.drop();
        DBRef ref = new DBRef( getDatabase() , "fake" , 17 );

        b.save( BasicDBObjectBuilder.start( "n" , 12 ).add( "l" , ref ).get() );

        assertEquals( 12 , b.findOne().get( "n" ) );
        assertEquals( DBRef.class , b.findOne().get( "l" ).getClass() );

        DBObject loaded = b.findOne(BasicDBObjectBuilder.start( "l" , ref ).get() );
        assertEquals( 12 , loaded.get( "n" ) );
        assertEquals( DBRef.class , loaded.get( "l" ).getClass() );
        assertEquals( ref.getId(), ((DBRef)loaded.get( "l" )).getId());
        assertEquals( ref.getRef(), ((DBRef)loaded.get( "l" )).getRef());
        assertEquals( ref.getDB(), ((DBRef)loaded.get( "l" )).getDB());
    }

    @Test
    public void testGetEntityWithSingleDBRefWithCompoundId() {
        DBCollection a = getDatabase().getCollection("a");
        a.drop();

        BasicDBObject compoundId = new BasicDBObject("name", "someName").append("email", "test@example.com");
        BasicDBObject entity = new BasicDBObject("_id", "testId").append("ref", new DBRef(getDatabase(), "fake", compoundId));
        a.save(entity);

        DBObject fetched = a.findOne(new BasicDBObject("_id", "testId"));

        assertNotNull(fetched);
        assertFalse(fetched.containsField("$id"));
        assertEquals(fetched, entity);
    }

    @Test
    public void testGetEntityWithArrayOfDBRefsWithCompoundIds() {
        DBCollection a = getDatabase().getCollection("a");
        a.drop();

        BasicDBObject compoundId1 = new BasicDBObject("name", "someName").append("email", "test@example.com");
        BasicDBObject compoundId2 = new BasicDBObject("name", "someName2").append("email", "test2@example.com");
        BasicDBList listOfRefs = new BasicDBList();
        listOfRefs.add(new DBRef(getDatabase(), "fake", compoundId1));
        listOfRefs.add(new DBRef(getDatabase(), "fake", compoundId2));
        BasicDBObject entity = new BasicDBObject("_id", "testId").append("refs", listOfRefs);
        a.save(entity);

        DBObject fetched = a.findOne(new BasicDBObject("_id", "testId"));

        assertNotNull(fetched);
        assertEquals(fetched, entity);
    }

    @Test
    public void testGetEntityWithMapOfDBRefsWithCompoundIds() {
        DBCollection base = getDatabase().getCollection("basecollection");
        base.drop();

        BasicDBObject compoundId1 = new BasicDBObject("name", "someName").append("email", "test@example.com");
        BasicDBObject compoundId2 = new BasicDBObject("name", "someName2").append("email", "test2@example.com");
        BasicDBObject mapOfRefs = new BasicDBObject()
                .append("someName", new DBRef(getDatabase(), "compoundkeys", compoundId1))
                .append("someName2", new DBRef(getDatabase(), "compoundkeys", compoundId2));
        BasicDBObject entity = new BasicDBObject("_id", "testId").append("refs", mapOfRefs);
        base.save(entity);

        DBObject fetched = base.findOne(new BasicDBObject("_id", "testId"));

        assertNotNull(fetched);
        DBObject fetchedRefs = (DBObject) fetched.get("refs");
        assertFalse(fetchedRefs.keySet().contains("$id"));
        assertEquals(fetched, entity);
    }
}


text:
constexpr double cr=100;
class BoxShapeFactoty;

//2D図形
class BoxShape
{

    friend class BoxShapeFactoty;
public:
    ~BoxShape()
    {
        if(gitem.unique()==true){
            world->DestroyBody(body);
            scene->removeItem(gitem.get());
        }
    }
    //表示データの更新
    void update(){
        auto toDegree=[](double rad){
            constexpr double pi=3.141592653589793;
            double degree =(rad*180.0)/pi;
            return degree;
        };
        b2Vec2 position=body->GetPosition();
        const double rad=body->GetAngle();
        const double deg=toDegree(rad);
        if(gitem){
            gitem->setPos(RaCov.mulForce(position.x),RaCov.mulForce(position.y));
            gitem->setRotation(deg);
        }
    }

    b2Body* GetBody(){return body;}
    std::shared_ptr<QGraphicsItem> GetGitem(){return gitem;}
private:
    QGraphicsScene *scene=nullptr;
    b2World *world=nullptr;
    b2Body *body=nullptr;
    std::shared_ptr<QGraphicsItem> gitem;
    RangeConvert RaCov;
    //プライベートコンストラクタ
    BoxShape(){;}
    //シリアライズ処理
    //表示テータ生成

    std::shared_ptr<QGraphicsPolygonItem> GenGitem(QGraphicsScene *scene,QPolygonF &poly)
    {
        //表示データの生成
        auto out=std::shared_ptr<QGraphicsPolygonItem>(new QGraphicsPolygonItem(poly,nullptr));
        gitem=out;
        //アイテムデータの設定
        scene->addItem(gitem.get());
        return out;
    }
    //図形の定義
    void DefBody(b2BodyType btype,b2Vec2 velcocity=b2Vec2(0,0))
    {
        if(gitem&&(world!=nullptr)){
            b2BodyDef bodyDef;
            auto itempos=gitem->pos();
            bodyDef.type = btype;
            bodyDef.position.Set(RaCov.divForce(itempos.x()),RaCov.divForce(itempos.y()));
            bodyDef.linearVelocity=velcocity;;
            body=world->CreateBody(&bodyDef);
        }
    }
    //box2d図形データの生成
    b2PolygonShape GenShape(QPolygonF &poly)
    {
        b2PolygonShape dynamicBox;
        QVector<b2Vec2> vect=ConvertB2Vec2(poly,RaCov);
        dynamicBox.Set(vect.data(),vect.count());
        return dynamicBox;
    }

    //座標の変換
    QVector<b2Vec2> ConvertB2Vec2(QPolygonF &poly,RangeConvert &r){
        QVector<b2Vec2> vect(poly.count());
        for(const int i:SmartCountor(poly.count())){
            vect[i].x=r.divForce(poly[i].x());
            vect[i].y=r.divForce(poly[i].y());
        }
        return vect;
    }
};

#endif // BOXSHAPE_H


text:
package main

import (
	"bufio"
	"bytes"
	"fmt"
	"net"
	"os/exec"
)

// realServerAddress returns an intercepted connection's original destination.
func realServerAddress(conn net.Conn) (net.Addr, error) {
	// If the connection was intercepted with an IPFW fwd rule,
	// its LocalAddr will be the original destination.
	addr := conn.LocalAddr()
	if !isLocalAddress(addr) {
		return addr, nil
	}

	// If the connection was intercepted with a PF rdr rule,
	// we need to examine the state table to find the original address.
	pfctl := exec.Command("pfctl", "-ss")
	stdout, err := pfctl.StdoutPipe()
	if err != nil {
		return nil, fmt.Errorf("error getting output of pfctl -ss: %v", err)
	}
	if err := pfctl.Start(); err != nil {
		return nil, fmt.Errorf("error running pfctl -ss: %v", err)
	}

	defer pfctl.Wait()

	// Search for redirected connections matching the remote host and port.
	// The lines look like this:
	// all tcp 10.1.10.1:6502 (199.27.79.143:80) <- 10.1.10.203:62586       ESTABLISHED:ESTABLISHED
	//         dest. of rdr    real server addr     remote address
	remote := append([]byte(") <- "), conn.RemoteAddr().String()...)
	scanner := bufio.NewScanner(stdout)
	for scanner.Scan() {
		line := scanner.Bytes()
		if !bytes.HasPrefix(line, []byte("all tcp ")) {
			continue
		}
		loc := bytes.Index(line, remote)
		if loc == -1 {
			continue
		}
		openParen := bytes.LastIndex(line[:loc], []byte{'('})
		if openParen == -1 {
			continue
		}
		as := string(line[openParen+1 : loc])
		a, err := net.ResolveTCPAddr("tcp", as)
		if err != nil {
			return nil, fmt.Errorf("error parsing address %q: %v", as, err)
		}
		return a, nil
	}
	if err := scanner.Err(); err != nil {
		return nil, fmt.Errorf("error reading output of pfctl -ss: %v", err)
	}

	return addr, nil
}


text:
'use strict';

var Reader = require('../src/js/reader');

describe('Test gesture reader - flick case', function() {
    var reader, event, pointList;

    beforeEach(function() {
        var i = 0;

        pointList = [];
        reader = new Reader({
            type: 'flick'
        });
        event = {};
        event.start = new Date() - 1000;
        event.end = new Date() - 1;

        for (; i < 200; i += 1) {
            pointList.push({
                x: 10 + (i + i),
                y: i
            });
        }
        event.list = pointList;
    });

    it('reader.flick is created', function() {
        expect(reader.type).toBe('flick');
    });

    describe('test cardinal Points', function() {
        it('figure out cardinal points, SE', function() {
            var first = {
                x: 10,
                y: 10
            };
            var final = {
                x: 60,
                y: 30
            };
            var cardinalPoints = reader.getCardinalPoints(first, final);

            expect(cardinalPoints).toBe('SE');
        });

        it('figure out cardinal points, NW', function() {
            var first = {
                x: 60,
                y: 100
            };
            var final = {
                x: 10,
                y: 30
            };
            var cardinalPoints = reader.getCardinalPoints(first, final);

            expect(cardinalPoints).toBe('NW');
        });

        it('figure out cardinal points, N', function() {
            var first = {
                x: 60,
                y: 100
            };
            var final = {
                x: 60,
                y: 30
            };
            var cardinalPoints = reader.getCardinalPoints(first, final);

            expect(cardinalPoints).toBe('N');
        });

        it('figure out cardinal points, E', function() {
            var first = {
                x: 30,
                y: 100
            };
            var final = {
                x: 100,
                y: 100
            };
            var cardinalPoints = reader.getCardinalPoints(first, final);

            expect(cardinalPoints).toBe('E');
        });

        it('figure out nearest four points(W,E,S,N)', function() {
            var first = {
                x: 30,
                y: 100
            };
            var final = {
                x: 100,
                y: 250
            };
            var cardinalPoint = reader.getCardinalPoints(first, final);
            var nearestPoint = reader.getCloseCardinal(first, final, cardinalPoint);

            expect(nearestPoint).toBe('S');
        });

        it('figure out nearest four points(W,E,S,N)', function() {
            var first = {
                x: 250,
                y: 0
            };
            var final = {
                x: 10,
                y: 150
            };
            var cardinalPoint = reader.getCardinalPoints(first, final);
            var nearestPoint = reader.getCloseCardinal(first, final, cardinalPoint);

            expect(nearestPoint).toBe('W');
        });

        it('figure out nearest four points(W,E,S,N)', function() {
            var first = {
                x: 10,
                y: 250
            };
            var final = {
                x: 100,
                y: 100
            };
            var cardinalPoint = reader.getCardinalPoints(first, final);
            var nearestPoint = reader.getCloseCardinal(first, final, cardinalPoint);

            expect(nearestPoint).toBe('N');
        });

        it('figure out nearest four point(W,E,S,N), use get direction.', function() {
            var result = reader.getDirection(pointList);
            expect(result).toBe('E');
        });
    });

    describe('test event type', function() {
        it('flick event uprise.', function() {
            expect(reader.isFlick(event)).toBe(true);
        });

        it('flick event uprise.', function() {
            event.start = 1000;
            event.end = 1005;
            expect(reader.isFlick(event)).toBe(true);
        });

        it('ignore event(return none)', function() {
            event.start = 10000;
            event.end = 11000;
            event.list.push({
                x: 11,
                y: 5
            });
            expect(reader.isFlick(event)).toBe(false);
        });

        it('ignore event(return none)', function() {
            event.start = 10000;
            event.end = 11000;
            event.list.push({
                x: 100,
                y: 100
            });
            expect(reader.isFlick(event)).toBe(false);
        });
    });
});


text:
from __future__ import absolute_import, unicode_literals

import os
import signal
import subprocess
import sys
import time
from contextlib import contextmanager
from threading import Thread

import py

from tox import reporter
from tox.constants import INFO
from tox.exception import InvocationError
from tox.reporter import Verbosity
from tox.util.lock import get_unique_file
from tox.util.stdlib import is_main_thread

if sys.version_info >= (3, 3):
    from shlex import quote as shlex_quote
else:
    from pipes import quote as shlex_quote

class Action(object):
    """Action is an effort to group operations with the same goal (within reporting)"""

    def __init__(
        self,
        name,
        msg,
        args,
        log_dir,
        generate_tox_log,
        command_log,
        popen,
        python,
        suicide_timeout,
        interrupt_timeout,
        terminate_timeout,
    ):
        self.name = name
        self.args = args
        self.msg = msg
        self.activity = self.msg.split(" ", 1)[0]
        self.log_dir = log_dir
        self.generate_tox_log = generate_tox_log
        self.via_popen = popen
        self.command_log = command_log
        self._timed_report = None
        self.python = python
        self.suicide_timeout = suicide_timeout
        self.interrupt_timeout = interrupt_timeout
        self.terminate_timeout = terminate_timeout
        if is_main_thread():
            # python allows only main thread to install signal handlers
            # see https://docs.python.org/3/library/signal.html#signals-and-threads
            self._install_sigterm_handler()

    def __enter__(self):
        msg = "{} {}".format(self.msg, " ".join(map(str, self.args)))
        self._timed_report = reporter.timed_operation(self.name, msg)
        self._timed_report.__enter__()

        return self

    def __exit__(self, type, value, traceback):
        self._timed_report.__exit__(type, value, traceback)

    def setactivity(self, name, msg):
        self.activity = name
        if msg:
            reporter.verbosity0("{} {}: {}".format(self.name, name, msg), bold=True)
        else:
            reporter.verbosity1("{} {}: {}".format(self.name, name, msg), bold=True)

    def info(self, name, msg):
        reporter.verbosity1("{} {}: {}".format(self.name, name, msg), bold=True)

    def popen(
        self,
        args,
        cwd=None,
        env=None,
        redirect=True,
        returnout=False,
        ignore_ret=False,
        capture_err=True,
        callback=None,
        report_fail=True,
    ):
        """this drives an interaction with a subprocess"""
        cwd = py.path.local() if cwd is None else cwd
        cmd_args = [str(x) for x in self._rewrite_args(cwd, args)]
        cmd_args_shell = " ".join(shlex_quote(i) for i in cmd_args)
        stream_getter = self._get_standard_streams(
            capture_err,
            cmd_args_shell,
            redirect,
            returnout,
            cwd,
        )
        exit_code, output = None, None
        with stream_getter as (fin, out_path, stderr, stdout):
            try:
                process = self.via_popen(
                    cmd_args,
                    stdout=stdout,
                    stderr=stderr,
                    cwd=str(cwd),
                    env=os.environ.copy() if env is None else env,
                    universal_newlines=True,
                    shell=False,
                    creationflags=(
                        subprocess.CREATE_NEW_PROCESS_GROUP
                        if sys.platform == "win32"
                        else 0
                        # needed for Windows signal send ability (CTRL+C)
                    ),
                )
            except OSError as exception:
                exit_code = exception.errno
            else:
                if callback is not None:
                    callback(process)
                reporter.log_popen(cwd, out_path, cmd_args_shell, process.pid)
                output = self.evaluate_cmd(fin, process, redirect)
                exit_code = process.returncode
            finally:
                if out_path is not None and out_path.exists():
                    lines = out_path.read_text("UTF-8").split("\n")
                    # first three lines are the action, cwd, and cmd - remove it
                    output = "\n".join(lines[3:])
                try:
                    if exit_code and not ignore_ret:
                        if report_fail:
                            msg = "invocation failed (exit code {:d})".format(exit_code)
                            if out_path is not None:
                                msg += ", logfile: {}".format(out_path)
                                if not out_path.exists():
                                    msg += " warning log file missing"
                            reporter.error(msg)
                            if out_path is not None and out_path.exists():
                                reporter.separator("=", "log start", Verbosity.QUIET)
                                reporter.quiet(output)
                                reporter.separator("=", "log end", Verbosity.QUIET)
                        raise InvocationError(cmd_args_shell, exit_code, output)
                finally:
                    self.command_log.add_command(cmd_args, output, exit_code)
        return output

    def evaluate_cmd(self, input_file_handler, process, redirect):
        try:
            if self.generate_tox_log and not redirect:
                if process.stderr is not None:
                    # prevent deadlock
                    raise ValueError("stderr must not be piped here")
                # we read binary from the process and must write using a binary stream
                buf = getattr(sys.stdout, "buffer", sys.stdout)
                last_time = time.time()
                while True:
                    # we have to read one byte at a time, otherwise there
                    # might be no output for a long time with slow tests
                    data = input_file_handler.read(1)
                    if data:
                        buf.write(data)
                        if b"\n" in data or (time.time() - last_time) > 1:
                            # we flush on newlines or after 1 second to
                            # provide quick enough feedback to the user
                            # when printing a dot per test
                            buf.flush()
                            last_time = time.time()
                    elif process.poll() is not None:
                        if process.stdout is not None:
                            process.stdout.close()
                        break
                    else:
                        time.sleep(0.1)
                        # the seek updates internal read buffers
                        input_file_handler.seek(0, 1)
                input_file_handler.close()
            out, _ = process.communicate()  # wait to finish
        except KeyboardInterrupt as exception:
            reporter.error("got KeyboardInterrupt signal")
            main_thread = is_main_thread()
            while True:
                try:
                    if main_thread:
                        # spin up a new thread to disable further interrupt on main thread
                        stopper = Thread(target=self.handle_interrupt, args=(process,))
                        stopper.start()
                        stopper.join()
                    else:
                        self.handle_interrupt(process)
                except KeyboardInterrupt:
                    continue
                break
            raise exception
        return out

    def handle_interrupt(self, process):
        """A three level stop mechanism for children - INT -> TERM -> KILL"""
        msg = "from {} {{}} pid {}".format(os.getpid(), process.pid)
        if self._wait(process, self.suicide_timeout) is None:
            self.info("KeyboardInterrupt", msg.format("SIGINT"))
            process.send_signal(signal.CTRL_C_EVENT if sys.platform == "win32" else signal.SIGINT)
            if self._wait(process, self.interrupt_timeout) is None:
                self.info("KeyboardInterrupt", msg.format("SIGTERM"))
                process.terminate()
                if self._wait(process, self.terminate_timeout) is None:
                    self.info("KeyboardInterrupt", msg.format("SIGKILL"))
                    process.kill()
                    process.communicate()

    @staticmethod
    def _wait(process, timeout):
        if sys.version_info >= (3, 3):
            # python 3 has timeout feature built-in
            try:
                process.communicate(timeout=timeout)
            except subprocess.TimeoutExpired:
                pass
        else:
            # on Python 2 we need to simulate it
            delay = 0.01
            while process.poll() is None and timeout > 0:
                time.sleep(delay)
                timeout -= delay
        return process.poll()

    @contextmanager
    def _get_standard_streams(self, capture_err, cmd_args_shell, redirect, returnout, cwd):
        stdout = out_path = input_file_handler = None
        stderr = subprocess.STDOUT if capture_err else None

        if self.generate_tox_log or redirect:
            out_path = self.get_log_path(self.name)
            with out_path.open("wt") as stdout, out_path.open("rb") as input_file_handler:
                msg = "action: {}, msg: {}\ncwd: {}\ncmd: {}\n".format(
                    self.name.replace("\n", " "),
                    self.msg.replace("\n", " "),
                    str(cwd).replace("\n", " "),
                    cmd_args_shell.replace("\n", " "),
                )
                stdout.write(msg)
                stdout.flush()
                input_file_handler.read()  # read the header, so it won't be written to stdout
                yield input_file_handler, out_path, stderr, stdout
                return

        if returnout:
            stdout = subprocess.PIPE

        yield input_file_handler, out_path, stderr, stdout

    def get_log_path(self, actionid):
        log_file = get_unique_file(self.log_dir, prefix=actionid, suffix=".log")
        return log_file

    def _rewrite_args(self, cwd, args):

        executable = None
        if INFO.IS_WIN:
            # shebang lines are not adhered on Windows so if it's a python script
            # pre-pend the interpreter
            ext = os.path.splitext(str(args[0]))[1].lower()
            if ext == ".py":
                executable = str(self.python)
        if executable is None:
            executable = args[0]
            args = args[1:]

        new_args = [executable]

        # to make the command shorter try to use relative paths for all subsequent arguments
        # note the executable cannot be relative as the Windows applies cwd after invocation
        for arg in args:
            if arg and os.path.isabs(str(arg)):
                arg_path = py.path.local(arg)
                if arg_path.exists() and arg_path.common(cwd) is not None:
                    potential_arg = cwd.bestrelpath(arg_path)
                    if len(potential_arg.split("..")) < 2:
                        # just one parent directory accepted as relative path
                        arg = potential_arg
            new_args.append(str(arg))

        return new_args

    def _install_sigterm_handler(self):
        """Handle sigterm as if it were a keyboardinterrupt"""

        def sigterm_handler(signum, frame):
            reporter.error("Got SIGTERM, handling it as a KeyboardInterrupt")
            raise KeyboardInterrupt()

        signal.signal(signal.SIGTERM, sigterm_handler)


text:
package com.alibaba.dubbo.common.json;

/**
 * ParseException.
 *
 * @author qian.lei
 */
@Deprecated
public class ParseException extends Exception {
    private static final long serialVersionUID = 8611884051738966316L;

    public ParseException() {
        super();
    }

    public ParseException(String message) {
        super(message);
    }
}


text:
<!doctype html>

    <title>Code coverage report for src/</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../prettify.css">
    <link rel="stylesheet" href="../base.css">

Code coverage report for src/

        Statements: 33.33% (45 / 135)
        Branches: 8.08% (8 / 99)
        Functions: 50% (9 / 18)
        Lines: 31.25% (40 / 128)
        Ignored: none

All files » src/

   File

   Statements

   Branches

   Functions

   Lines

	index.js

	33.33%
	(45 / 135)
	8.08%
	(8 / 99)
	50%
	(9 / 18)
	31.25%
	(40 / 128)

Generated by istanbul at Mon Jun 08 2015 12:46:32 GMT-0400 (EDT)


text:
package main

import (
	"context"
	"net/http"
	_ "net/http/pprof"
	"strconv"

	api "github.com/osrg/gobgp/v3/api"
	"github.com/spf13/cobra"
)

var globalOpts struct {
	Host         string
	Port         int
	Target       string
	Debug        bool
	Quiet        bool
	Json         bool
	GenCmpl      bool
	BashCmplFile string
	PprofPort    int
	TLS          bool
	CaFile       string
}

var client api.GobgpApiClient
var ctx context.Context

func newRootCmd() *cobra.Command {
	cobra.EnablePrefixMatching = true
	var cancel context.CancelFunc
	rootCmd := &cobra.Command{
		Use: "gobgp",
		PersistentPreRun: func(cmd *cobra.Command, args []string) {
			if globalOpts.PprofPort > 0 {
				go func() {
					address := "localhost:" + strconv.Itoa(globalOpts.PprofPort)
					if err := http.ListenAndServe(address, nil); err != nil {
						exitWithError(err)
					}
				}()
			}

			if !globalOpts.GenCmpl {
				var err error
				ctx = context.Background()
				client, cancel, err = newClient(ctx)
				if err != nil {
					cancel()
					exitWithError(err)
				}
			}
		},
		Run: func(cmd *cobra.Command, args []string) {
			if globalOpts.GenCmpl {
				cmd.GenBashCompletionFile(globalOpts.BashCmplFile)
			} else {
				cmd.HelpFunc()(cmd, args)
			}
		},
		PersistentPostRun: func(cmd *cobra.Command, args []string) {
			// if children declare their own, cancel is not called. Doesn't matter because the command will exit soon.
			if cancel != nil {
				cancel()
			}
		},
	}

	rootCmd.PersistentFlags().StringVarP(&globalOpts.Host, "host", "u", "127.0.0.1", "host")
	rootCmd.PersistentFlags().IntVarP(&globalOpts.Port, "port", "p", 50051, "port")
	rootCmd.PersistentFlags().StringVarP(&globalOpts.Target, "target", "", "", "alternative to host/port when using UDS. Ex: unix:///var/run/go-bgp.sock if running gobgpd with a UDS socket.")
	rootCmd.PersistentFlags().BoolVarP(&globalOpts.Json, "json", "j", false, "use json format to output format")
	rootCmd.PersistentFlags().BoolVarP(&globalOpts.Debug, "debug", "d", false, "use debug")
	rootCmd.PersistentFlags().BoolVarP(&globalOpts.Quiet, "quiet", "q", false, "use quiet")
	rootCmd.PersistentFlags().BoolVarP(&globalOpts.GenCmpl, "gen-cmpl", "c", false, "generate completion file")
	rootCmd.PersistentFlags().StringVarP(&globalOpts.BashCmplFile, "bash-cmpl-file", "", "gobgp-completion.bash", "bash cmpl filename")
	rootCmd.PersistentFlags().IntVarP(&globalOpts.PprofPort, "pprof-port", "r", 0, "pprof port")
	rootCmd.PersistentFlags().BoolVarP(&globalOpts.TLS, "tls", "", false, "connection uses TLS if true, else plain TCP")
	rootCmd.PersistentFlags().StringVarP(&globalOpts.CaFile, "tls-ca-file", "", "", "The file containing the CA root cert file")

	globalCmd := newGlobalCmd()
	neighborCmd := newNeighborCmd()
	vrfCmd := newVrfCmd()
	policyCmd := newPolicyCmd()
	monitorCmd := newMonitorCmd()
	mrtCmd := newMrtCmd()
	rpkiCmd := newRPKICmd()
	bmpCmd := newBmpCmd()
	logLevelCmd := newLogLevelCmd()
	rootCmd.AddCommand(globalCmd, neighborCmd, vrfCmd, policyCmd, monitorCmd, mrtCmd, rpkiCmd, bmpCmd, logLevelCmd)
	return rootCmd
}


text:
package mysql

import (
	"bytes"
	"context"
	"database/sql"
	"fmt"
	"strings"
	"time"

	"github.com/ezbuy/ezorm/v2/pkg/db"
)

var (
	_ time.Time
	_ bytes.Buffer
	_ = strings.Index
)

// -----------------------------------------------------------------------------

func (m *_UserMgr) queryOne(ctx context.Context, query string, args ...interface{}) (*User, error) {
	ret, err := m.queryLimit(ctx, query, 1, args...)
	if err != nil {
		return nil, err
	}
	if len(ret) == 0 {
		return nil, sql.ErrNoRows
	}
	return ret[0], nil
}

func (m *_UserMgr) query(ctx context.Context, query string, args ...interface{}) (results []*User, err error) {
	return m.queryLimit(ctx, query, -1, args...)
}

func (m *_UserMgr) Query(ctx context.Context, query string, args ...interface{}) (results []*User, err error) {
	return m.queryLimit(ctx, query, -1, args...)
}

func (*_UserMgr) queryLimit(ctx context.Context, query string, limit int, args ...interface{}) (results []*User, err error) {
	rows, err := db.MysqlQuery(ctx, query, args...)
	if err != nil {
		return nil, fmt.Errorf("test.User query error: %v", err)
	}
	defer rows.Close()

	offset := 0
	for rows.Next() {
		if limit >= 0 && offset >= limit {
			break
		}
		offset++

		var result User
		err := rows.Scan(&(result.UserId),
			&(result.UserNumber),
			&(result.Name),
		)
		if err != nil {
			return nil, err
		}

		results = append(results, &result)
	}
	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("test.User fetch result error: %v", err)
	}

	return
}

func (m *_UserMgr) Save(ctx context.Context, obj *User) (sql.Result, error) {
	if obj.UserId == 0 {
		return m.saveInsert(ctx, obj)
	}
	return m.saveUpdate(ctx, obj)
}

func (m *_UserMgr) saveInsert(ctx context.Context, obj *User) (sql.Result, error) {
	query := "INSERT INTO test.test_user (`user_number`, `name`) VALUES (?, ?)"
	result, err := db.MysqlExec(ctx, query, obj.UserNumber, obj.Name)
	if err != nil {
		return result, err
	}

	lastInsertId, err := result.LastInsertId()
	if err != nil {
		return result, err
	}

	obj.UserId = int32(lastInsertId)

	return result, err
}

func (m *_UserMgr) saveUpdate(ctx context.Context, obj *User) (sql.Result, error) {
	query := "UPDATE test.test_user SET `user_number`=?, `name`=? WHERE `user_id`=?"
	return db.MysqlExec(ctx, query, obj.UserNumber, obj.Name, obj.UserId)
}

func (m *_UserMgr) InsertBatch(ctx context.Context, objs []*User) (sql.Result, error) {
	if len(objs) == 0 {
		return nil, fmt.Errorf("Empty insert")
	}

	values := make([]string, 0, len(objs))
	params := make([]interface{}, 0, len(objs)*2)
	for _, obj := range objs {
		values = append(values, "(?, ?)")
		params = append(params, obj.UserNumber, obj.Name)
	}
	query := fmt.Sprintf("INSERT INTO test.test_user (`user_number`, `name`) VALUES %s", strings.Join(values, ","))
	return db.MysqlExec(ctx, query, params...)
}

func (m *_UserMgr) FindByID(ctx context.Context, id int32) (*User, error) {
	query := "SELECT `user_id`, `user_number`, `name` FROM test.test_user WHERE user_id=?"
	return m.queryOne(ctx, query, id)
}

func (m *_UserMgr) FindByIDs(ctx context.Context, ids []int32) ([]*User, error) {
	idsLen := len(ids)
	placeHolders := make([]string, 0, idsLen)
	args := make([]interface{}, 0, idsLen)
	for _, id := range ids {
		placeHolders = append(placeHolders, "?")
		args = append(args, id)
	}

	query := fmt.Sprintf(
		"SELECT `user_id`, `user_number`, `name` FROM test.test_user WHERE user_id IN (%s)",
		strings.Join(placeHolders, ","))
	return m.query(ctx, query, args...)
}

func (m *_UserMgr) FindInUserId(ctx context.Context, ids []int32, sortFields ...string) ([]*User, error) {
	return m.FindByIDs(ctx, ids)
}

func (m *_UserMgr) FindListUserId(ctx context.Context, UserId []int32) ([]*User, error) {
	retmap, err := m.FindMapUserId(ctx, UserId)
	if err != nil {
		return nil, err
	}
	ret := make([]*User, len(UserId))
	for idx, key := range UserId {
		ret[idx] = retmap[key]
	}
	return ret, nil
}

func (m *_UserMgr) FindMapUserId(ctx context.Context, UserId []int32, sortFields ...string) (map[int32]*User, error) {
	ret, err := m.FindInUserId(ctx, UserId, sortFields...)
	if err != nil {
		return nil, err
	}
	retmap := make(map[int32]*User, len(ret))
	for _, n := range ret {
		retmap[n.UserId] = n
	}
	return retmap, nil
}

func (m *_UserMgr) FindListUserNumber(ctx context.Context, UserNumber []int32) ([]*User, error) {
	retmap, err := m.FindMapUserNumber(ctx, UserNumber)
	if err != nil {
		return nil, err
	}
	ret := make([]*User, len(UserNumber))
	for idx, key := range UserNumber {
		ret[idx] = retmap[key]
	}
	return ret, nil
}

func (m *_UserMgr) FindMapUserNumber(ctx context.Context, UserNumber []int32) (map[int32]*User, error) {
	ret, err := m.FindInUserNumber(ctx, UserNumber)
	if err != nil {
		return nil, err
	}
	retmap := make(map[int32]*User, len(ret))
	for _, n := range ret {
		retmap[n.UserNumber] = n
	}
	return retmap, nil
}

func (m *_UserMgr) FindInUserNumber(ctx context.Context, UserNumber []int32, sortFields ...string) ([]*User, error) {
	buf := bytes.NewBuffer(nil)
	buf.WriteString("SELECT `user_id`, `user_number`, `name` FROM test.test_user WHERE ")

	buf.WriteString("`user_number` in ")
	int32ToIds(buf, UserNumber)
	return m.query(ctx, buf.String()+m.GetSort(sortFields))
}

func (m *_UserMgr) FindOneByUserNumber(ctx context.Context, UserNumber int32) (*User, error) {
	query := "SELECT `user_id`, `user_number`, `name` FROM test.test_user WHERE user_number=?"
	return m.queryOne(ctx, query, UserNumber)
}

func (m *_UserMgr) FindListName(ctx context.Context, Name []string) ([]*User, error) {
	retmap, err := m.FindMapName(ctx, Name)
	if err != nil {
		return nil, err
	}
	ret := make([]*User, len(Name))
	for idx, key := range Name {
		ret[idx] = retmap[key]
	}
	return ret, nil
}

func (m *_UserMgr) FindMapName(ctx context.Context, Name []string) (map[string]*User, error) {
	ret, err := m.FindInName(ctx, Name)
	if err != nil {
		return nil, err
	}
	retmap := make(map[string]*User, len(ret))
	for _, n := range ret {
		retmap[n.Name] = n
	}
	return retmap, nil
}

func (m *_UserMgr) FindInName(ctx context.Context, Name []string, sortFields ...string) ([]*User, error) {
	buf := bytes.NewBuffer(nil)
	buf.WriteString("SELECT `user_id`, `user_number`, `name` FROM test.test_user WHERE ")

	buf.WriteString("`name` in ")
	stringToIds(buf, Name)
	return m.query(ctx, buf.String()+m.GetSort(sortFields))
}

func (m *_UserMgr) FindAllByName(ctx context.Context, Name string, sortFields ...string) ([]*User, error) {
	return m.FindByName(ctx, Name, -1, -1, sortFields...)
}

func (m *_UserMgr) FindByName(ctx context.Context, Name string, offset int, limit int, sortFields ...string) ([]*User, error) {
	query := fmt.Sprintf("SELECT `user_id`, `user_number`, `name` FROM test.test_user WHERE `name`=? %s%s", m.GetSort(sortFields), m.GetLimit(offset, limit))

	return m.query(ctx, query, Name)
}

func (m *_UserMgr) FindOne(ctx context.Context, where string, args ...interface{}) (*User, error) {
	query := m.GetQuerysql(where) + m.GetLimit(0, 1)
	return m.queryOne(ctx, query, args...)
}

func (m *_UserMgr) Find(ctx context.Context, where string, args ...interface{}) ([]*User, error) {
	query := m.GetQuerysql(where)
	return m.query(ctx, query, args...)
}

func (m *_UserMgr) FindAll(ctx context.Context) (results []*User, err error) {
	return m.Find(ctx, "")
}

func (m *_UserMgr) FindWithOffset(ctx context.Context, where string, offset int, limit int, args ...interface{}) ([]*User, error) {
	query := m.GetQuerysql(where)

	query = query + " LIMIT ?, ?"

	args = append(args, offset)
	args = append(args, limit)

	return m.query(ctx, query, args...)
}

func (m *_UserMgr) GetQuerysql(where string) string {
	query := "SELECT `user_id`, `user_number`, `name` FROM test.test_user "

	where = strings.TrimSpace(where)
	if where != "" {
		upwhere := strings.ToUpper(where)

		if !strings.HasPrefix(upwhere, "WHERE") && !strings.HasPrefix(upwhere, "ORDER BY") {
			where = " WHERE " + where
		}

		query = query + where
	}

	return query
}

func (m *_UserMgr) Del(ctx context.Context, where string, params ...interface{}) (sql.Result, error) {
	if where != "" {
		where = "WHERE " + where
	}
	query := "DELETE FROM test.test_user " + where
	return db.MysqlExec(ctx, query, params...)
}

// argument example:
// set:"a=?, b=?"
// where:"c=? and d=?"
// params:[]interface{}{"a", "b", "c", "d"}...
func (m *_UserMgr) Update(ctx context.Context, set, where string, params ...interface{}) (sql.Result, error) {
	query := fmt.Sprintf("UPDATE test.test_user SET %s", set)
	if where != "" {
		query = fmt.Sprintf("UPDATE test.test_user SET %s WHERE %s", set, where)
	}
	return db.MysqlExec(ctx, query, params...)
}

func (m *_UserMgr) Count(ctx context.Context, where string, args ...interface{}) (int32, error) {
	query := "SELECT COUNT(*) FROM test.test_user"
	if where != "" {
		query = query + " WHERE " + where
	}

	rows, err := db.MysqlQuery(ctx, query, args...)
	if err != nil {
		return 0, err
	}
	defer rows.Close()

	var count int32
	if rows.Next() {
		err = rows.Scan(&count)
	}
	if err := rows.Err(); err != nil {
		return 0, err
	}

	return count, nil
}

func (m *_UserMgr) GetSort(sorts []string) string {
	if len(sorts) == 0 {
		return ""
	}
	buf := bytes.NewBuffer(nil)
	buf.WriteString(" ORDER BY ")
	for idx, s := range sorts {
		if len(s) == 0 {
			continue
		}
		if s[0] == '-' {
			buf.WriteString(s[1:] + " DESC")
		} else {
			buf.WriteString(s)
		}
		if idx == len(sorts)-1 {
			break
		}
		buf.WriteString(",")
	}
	return buf.String()
}

func (m *_UserMgr) GetId2Obj(objs []*User) map[int32]*User {
	id2obj := make(map[int32]*User, len(objs))
	for _, obj := range objs {
		id2obj[obj.UserId] = obj
	}
	return id2obj
}

func (m *_UserMgr) GetIds(objs []*User) []int32 {
	ids := make([]int32, len(objs))
	for i, obj := range objs {
		ids[i] = obj.UserId
	}
	return ids
}

func (m *_UserMgr) GetLimit(offset, limit int) string {
	if limit <= 0 {
		return ""
	}
	if offset <= 0 {
		return fmt.Sprintf(" LIMIT %d", limit)
	}
	return fmt.Sprintf(" LIMIT %d, %d", offset, limit)
}


text:
<?php

class MappingRepositoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function it_gets_the_list_of_mappings()
    {
        $repo = $this->getRepository();
        $query = Mockery::mock('stdClass');
        $connectionMock = Mockery::mock('Illuminate\Database\Connection');
        $repo->getConnectionResolver()->shouldReceive('connection')->with(null)->andReturn($connectionMock);
        $repo->getConnection()->shouldReceive('table')->once()->with('mappings')->andReturn($query);
        $query->shouldReceive('orderBy')->once()->with('batch', 'asc')->andReturn($query);
        $query->shouldReceive('orderBy')->once()->with('mapping', 'asc')->andReturn($query);
        $query->shouldReceive('pluck')->once()->with('mapping')->andReturn(['bar']);
        $this->assertEquals(['bar'], $repo->getRan());
    }

    /**
     * @test
     */
    public function it_gets_the_last_bach_of_ran_mappings()
    {
        $repo = $this->getMock('Sleimanx2\Plastic\Mappings\Mappings', ['getLastBatchNumber'], [
            $resolver = Mockery::mock('Illuminate\Database\ConnectionResolverInterface'), 'mappings',
        ]);
        $repo->expects($this->once())->method('getLastBatchNumber')->will($this->returnValue(1));
        $query = Mockery::mock('stdClass');
        $connectionMock = Mockery::mock('Illuminate\Database\Connection');
        $repo->getConnectionResolver()->shouldReceive('connection')->with(null)->andReturn($connectionMock);
        $repo->getConnection()->shouldReceive('table')->once()->with('mappings')->andReturn($query);
        $query->shouldReceive('where')->once()->with('batch', 1)->andReturn($query);
        $query->shouldReceive('orderBy')->once()->with('mapping', 'desc')->andReturn($query);
        $query->shouldReceive('get')->once()->andReturn(['foo']);
        $this->assertEquals(['foo'], $repo->getLast());
    }

    /**
     * @test
     */
    public function it_logs_a_mapping_with_a_batch_number()
    {
        $repo = $this->getRepository();
        $query = Mockery::mock('stdClass');
        $connectionMock = Mockery::mock('Illuminate\Database\Connection');
        $repo->getConnectionResolver()->shouldReceive('connection')->with(null)->andReturn($connectionMock);
        $repo->getConnection()->shouldReceive('table')->once()->with('mappings')->andReturn($query);
        $query->shouldReceive('insert')->once()->with(['mapping' => 'bar', 'batch' => 1]);
        $repo->log('bar', 1);
    }

    /**
     * @test
     */
    public function it_deletes_a_mapping()
    {
        $repo = $this->getRepository();
        $query = Mockery::mock('stdClass');
        $connectionMock = Mockery::mock('Illuminate\Database\Connection');
        $repo->getConnectionResolver()->shouldReceive('connection')->with(null)->andReturn($connectionMock);
        $repo->getConnection()->shouldReceive('table')->once()->with('mappings')->andReturn($query);
        $query->shouldReceive('where')->once()->with('mapping', 'foo')->andReturn($query);
        $query->shouldReceive('delete')->once();
        $mapping = (object) ['mapping' => 'foo'];
        $repo->delete($mapping);
    }

    /**
     * @test
     */
    public function it_gets_the_current_batch_number_plus_one()
    {
        $repo = $this->getMock('Sleimanx2\Plastic\Mappings\Mappings', ['getLastBatchNumber'], [
            Mockery::mock('Illuminate\Database\ConnectionResolverInterface'), 'mappings',
        ]);
        $repo->expects($this->once())->method('getLastBatchNumber')->will($this->returnValue(1));
        $this->assertEquals(2, $repo->getNextBatchNumber());
    }

    /**
     * @test
     */
    public function it_gets_the_last_batch_number()
    {
        $repo = $this->getRepository();
        $query = Mockery::mock('stdClass');
        $connectionMock = Mockery::mock('Illuminate\Database\Connection');
        $repo->getConnectionResolver()->shouldReceive('connection')->with(null)->andReturn($connectionMock);
        $repo->getConnection()->shouldReceive('table')->once()->with('mappings')->andReturn($query);
        $query->shouldReceive('max')->once()->andReturn(1);
        $this->assertEquals(1, $repo->getLastBatchNumber());
    }

    /**
     * @test
     */
    public function testCreateRepositoryCreatesProperDatabaseTable()
    {
        $repo = $this->getRepository();
        $schema = Mockery::mock('stdClass');
        $connectionMock = Mockery::mock('Illuminate\Database\Connection');
        $repo->getConnectionResolver()->shouldReceive('connection')->with(null)->andReturn($connectionMock);
        $repo->getConnection()->shouldReceive('getSchemaBuilder')->once()->andReturn($schema);
        $schema->shouldReceive('create')->once()->with('mappings', Mockery::type('Closure'));
        $repo->createRepository();
    }

    protected function getRepository()
    {
        return new \Sleimanx2\Plastic\Mappings\Mappings(Mockery::mock('Illuminate\Database\ConnectionResolverInterface'), 'mappings');
    }
}


text:
using System;
using NServiceBus;

namespace IronTester.Common.Messages.Initialization
{
    public interface IInitializeStatus : IMessage
    {
        Guid RequestId { get; set; }
        Decimal Progress { get; set; }
    }
}


text:
<?php

/**
 * Jms_Article
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    ##PACKAGE##
 * @subpackage ##SUBPACKAGE##
 * @author     ##NAME## <##EMAIL##>
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
class Jms_Article extends Jms_BaseArticle
{

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="biz.yf.oa.dao.SettingMapper">

	<select id="listObs" parameterType="Integer" resultType="HashMap">
		SELECT * FROM `oa_obs` where pid = ${value}
	</select>

</mapper>


text:
				{{index+1}}

			{{field.title}}

                {{ 'OPTIONAL' | translate }}

            {{field.description}}

                <input type="radio" value="true"
					class="focusOn"
                    style="opacity: 0; margin-left: 0px;"
					ng-model="field.fieldValue"
				    ng-focus="setActiveField(field._id, index, true)"
					ng-model-options="{ debounce: 250 }"
					ng-required="field.required"
					ng-change="$root.nextField()"
                    ng-disabled="field.disabled" />

					{{ 'Y' | translate }}

				{{ 'YES' | translate }}

                <input type="radio" value="false"
			        style="opacity:0; margin-left:0px;"
			        ng-model="field.fieldValue"
			        ng-model-options="{ debounce: 250 }"
			        ng-required="field.required"
			        ng-change="$root.nextField()"
                    ng-disabled="field.disabled"/>

				{{ 'N' | translate }}

			{{ 'NO' | translate }}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface ml.alternet.facet.Trackable (Alternet Libs 1.0 API)</title>
<meta name="date" content="2020-01-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
ml.alternet.facet.Trackable

Packages that use Trackable

Package
Description

ml.alternet.parser

Allow to design grammar, parse input and generate a custom data structure.

ml.alternet.scan

Scan Unicode character streams.

Uses of Trackable in ml.alternet.parser

Classes in ml.alternet.parser that implement Trackable

Modifier and Type
Class and Description

static class
EventsHandler.NumberValue

A number as the token value.

static class
EventsHandler.RuleEnd

Event fired when a rule ends ; indicates whether
 the rule was fulfilled or not.

static class
EventsHandler.RuleEvent<R extends Grammar.Rule>

When a rule or token is matched while parsing.

static class
EventsHandler.RuleStart

Event fired when a rule starts.

static class
EventsHandler.StringValue

A string as the token value.

static class
EventsHandler.TokenValue<T>

A wrapper of a parsed value, the token that creates it,
 and the position where the value was found when
 available.

Methods in ml.alternet.parser with parameters of type Trackable

Modifier and Type
Method and Description

abstract EventsHandler.TokenValue<T>
Grammar.TypedToken.newTokenValue(TokensCollector<?> buf,
             Trackable trackable)

Create a token value.

EventsHandler.TokenValue<String>
Grammar.TypedToken.String.newTokenValue(TokensCollector<?> buf,
             Trackable trackable)

EventsHandler.TokenValue<Number>
Grammar.TypedToken.Number.newTokenValue(TokensCollector<?> buf,
             Trackable trackable)

EventsHandler.TokenValue<T>
Grammar.TypedToken.TypedNumber.newTokenValue(TokensCollector<?> buf,
             Trackable trackable)

EventsHandler.TokenValue<T>
Grammar.TypedToken.Mapper.newTokenValue(TokensCollector<?> buf,
             Trackable trackable)

Constructors in ml.alternet.parser with parameters of type Trackable

Constructor and Description

NumberValue(Grammar.Token token,
           Number value,
           Trackable trackable)

Create a number token value.

RuleEnd(Grammar.Rule rule,
       Trackable trackable,
       boolean matched)

Create a rule end event.

RuleEvent(R rule,
         Trackable trackable)

Create a rule/token event.

RuleStart(Grammar.Rule rule,
         Trackable trackable)

Create a rule start event.

StringValue(Grammar.Token token,
           int value,
           Trackable trackable)

Create a string token value.

StringValue(Grammar.Token token,
           String value,
           Trackable trackable)

Create a string token value.

TokenValue(Grammar.Token token,
          T value,
          Trackable trackable)

Wrap a value that was read.

Uses of Trackable in ml.alternet.scan

Classes in ml.alternet.scan that implement Trackable

Modifier and Type
Class and Description

class
ReaderScanner

A scanner for stream of characters.

class
Scanner

A scanner can read Unicode characters from an input
 stream under conditions.

class
StringScanner

A scanner for sequences of chars (i.e. strings).

class
TrackableScanner

A scanner that tracks the current line, column, and offset.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2020 Alternet. All rights reserved.


text:
\section{Nulla ullamcorper vestibulum turpis}
\label{sec:nulla}

\subsection{Summary of the Material}
\lipsum[2]

\begin{itemize}
	\item \lipsum[1]
	\item \lipsum[2]
\end{itemize}

\lipsum[3]

\subsection{Discussion}
\lipsum[4-6]


text:
#ifndef __IPERF_UDP_H
#define __IPERF_UDP_H

/**
 * iperf_udp_recv -- receives the client data for UDP
 *
 *returns state of packet received
 *
 */
int iperf_udp_recv(struct iperf_stream *);

/**
 * iperf_udp_send -- sends the client data for UDP
 *
 * returns: bytes sent
 *
 */
int iperf_udp_send(struct iperf_stream *) /* __attribute__((hot)) */;

/**
 * iperf_udp_accept -- accepts a new UDP connection
 * on udp_listener_socket
 *returns 0 on success
 *
 */
int iperf_udp_accept(struct iperf_test *);

int iperf_udp_listen(struct iperf_test *);

int iperf_udp_connect(struct iperf_test *);

int iperf_udp_init(struct iperf_test *);

#endif


text:
#ifndef WebContextMenuProxyQt_h
#define WebContextMenuProxyQt_h

#include "WebContextMenuProxy.h"
#include <QtCore/QObject>

namespace WebKit {

class WebPageProxy;

class WebContextMenuProxyQt : public QObject, public WebContextMenuProxy {
    Q_OBJECT
public:
    static PassRefPtr<WebContextMenuProxyQt> create(WebPageProxy*);

private:
    WebContextMenuProxyQt(WebPageProxy*);

    virtual void showContextMenu(const WebCore::IntPoint&, const Vector<WebContextMenuItemData>&);
    virtual void hideContextMenu();
};

} // namespace WebKit

#endif // WebContextMenuProxyQt_h