text:
"""
Aggregating results into DataPoints

Copyright 2015 BlazeMeter Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from abc import abstractmethod
import copy
import logging
import math
import re
from collections import Counter

from bzt.utils import BetterDict
from bzt.engine import EngineModule
from bzt.modules.moves import iteritems

class KPISet(BetterDict):
    """
    Main entity in results, contains all KPIs for single label,
    capable of merging other KPISet's into it to compose cumulative results
    """
    ERRORS = "errors"
    SAMPLE_COUNT = "throughput"
    CONCURRENCY = "concurrency"
    SUCCESSES = "succ"
    FAILURES = "fail"
    RESP_TIMES = "rt"
    AVG_RESP_TIME = "avg_rt"
    STDEV_RESP_TIME = "stdev_rt"
    AVG_LATENCY = "avg_lt"
    AVG_CONN_TIME = "avg_ct"
    PERCENTILES = "perc"
    RESP_CODES = "rc"
    ERRTYPE_ERROR = 0
    ERRTYPE_ASSERT = 1

    def __init__(self, perc_levels=()):
        super(KPISet, self).__init__()
        self.sum_rt = 0
        self.sum_lt = 0
        self.sum_cn = 0
        self.perc_levels = perc_levels
        # scalars
        self.get(self.SAMPLE_COUNT, 0)
        self.get(self.CONCURRENCY, 0)
        self.get(self.SUCCESSES, 0)
        self.get(self.FAILURES, 0)
        self.get(self.AVG_RESP_TIME, 0)
        self.get(self.STDEV_RESP_TIME, 0)
        self.get(self.AVG_LATENCY, 0)
        self.get(self.AVG_CONN_TIME, 0)
        # vectors
        self.get(self.ERRORS, [])
        self.get(self.RESP_TIMES, Counter())
        self.get(self.RESP_CODES, Counter())
        self.get(self.PERCENTILES)
        self._concurrencies = BetterDict()

    def __deepcopy__(self, memo):
        mycopy = KPISet(self.perc_levels)
        mycopy.sum_rt = self.sum_rt
        mycopy.sum_lt = self.sum_lt
        mycopy.sum_cn = self.sum_cn
        for key, val in iteritems(self):
            mycopy[key] = copy.deepcopy(val, memo)
        return mycopy

    @staticmethod
    def error_item_skel(error, ret_c, cnt, errtype, urls):
        """

        :type error: str
        :type ret_c: str
        :type cnt: int
        :type errtype: int
        :type urls: Counter
        :rtype: dict
        """
        return {
            "cnt": cnt,
            "msg": error,
            "rc": ret_c,
            "type": errtype,
            "urls": urls
        }

    def add_sample(self, sample):
        """
        Add sample, consisting of: cnc, rt, cn, lt, rc, error, trname

        :type sample: tuple
        """
        # TODO: introduce a flag to not count failed in resp times? or offer it always?
        cnc, r_time, con_time, latency, r_code, error, trname = sample
        self[self.SAMPLE_COUNT] = self.get(self.SAMPLE_COUNT, 0) + 1
        if cnc:
            self._concurrencies[trname] = cnc

        if r_code is not None:
            resp_codes = self.get(self.RESP_CODES)
            resp_codes[r_code] = resp_codes.get(r_code, 0) + 1

            # count times only if we have RCs
            if con_time:
                self.sum_cn += con_time
            self.sum_lt += latency
            self.sum_rt += r_time

        if error is not None:
            self[self.FAILURES] = self.get(self.FAILURES, 0) + 1

            item = self.error_item_skel(error, r_code, 1, KPISet.ERRTYPE_ERROR, Counter())
            self.inc_list(self.get(self.ERRORS), ("msg", error), item)
        else:
            self[self.SUCCESSES] = self.get(self.SUCCESSES, 0) + 1

        self.get(self.RESP_TIMES)[r_time] += 1
        # TODO: max/min rt? there is percentiles...
        # TODO: throughput if interval is not 1s

    @staticmethod
    def inc_list(values, selector, value):
        """
        Increment list item, based on selector criteria

        :param values: list to update
        :type values: list
        :param selector: tuple of 2 values, field name and value to match
        :type selector: tuple
        :param value: dict to put into list
        :type value: dict
        """
        found = False
        for item in values:
            if item[selector[0]] == selector[1]:
                item['cnt'] += value['cnt']
                item['urls'] += value['urls']
                found = True
                break

        if not found:
            values.append(value)

    def recalculate(self):
        """
        Recalculate averages, stdev and percentiles

        :return:
        """
        if self[self.SAMPLE_COUNT]:
            self[self.AVG_CONN_TIME] = self.sum_cn / self[self.SAMPLE_COUNT]
            self[self.AVG_LATENCY] = self.sum_lt / self[self.SAMPLE_COUNT]
            self[self.AVG_RESP_TIME] = self.sum_rt / self[self.SAMPLE_COUNT]

        if self._concurrencies:
            self[self.CONCURRENCY] = sum(self._concurrencies.values())

        perc, stdev = self.__perc_and_stdev(self[self.RESP_TIMES], self.perc_levels, self[self.AVG_RESP_TIME])
        for level, val in perc:
            self[self.PERCENTILES][str(float(level))] = val

        self[self.STDEV_RESP_TIME] = stdev

        return self

    def merge_kpis(self, src, sid=None):
        """
        Merge other instance into self

        :param sid: source ID to use when suming up concurrency
        :type src: KPISet
        :return:
        """
        src.recalculate()

        self.sum_cn += src.sum_cn
        self.sum_lt += src.sum_lt
        self.sum_rt += src.sum_rt

        self[self.SAMPLE_COUNT] += src[self.SAMPLE_COUNT]
        self[self.SUCCESSES] += src[self.SUCCESSES]
        self[self.FAILURES] += src[self.FAILURES]
        # NOTE: should it be average? mind the timestamp gaps
        self._concurrencies[sid] = src[self.CONCURRENCY]

        self[self.RESP_TIMES].update(src[self.RESP_TIMES])
        self[self.RESP_CODES].update(src[self.RESP_CODES])

        for src_item in src[self.ERRORS]:
            self.inc_list(self[self.ERRORS], ('msg', src_item['msg']), src_item)

    @staticmethod
    def from_dict(obj):
        """

        :type obj: dict
        :rtype: KPISet
        """
        inst = KPISet()
        for key, val in iteritems(obj):
            inst[key] = val
        inst.sum_cn = obj[inst.AVG_CONN_TIME] * obj[inst.SAMPLE_COUNT]
        inst.sum_lt = obj[inst.AVG_LATENCY] * obj[inst.SAMPLE_COUNT]
        inst.sum_rt = obj[inst.AVG_RESP_TIME] * obj[inst.SAMPLE_COUNT]
        inst.perc_levels = [float(x) for x in inst[inst.PERCENTILES].keys()]
        inst[inst.RESP_TIMES] = {float(level): inst[inst.RESP_TIMES][level] for level in inst[inst.RESP_TIMES].keys()}
        for error in inst[KPISet.ERRORS]:
            error['urls'] = Counter(error['urls'])
        return inst

    @staticmethod
    def __perc_and_stdev(cnts_dict, percentiles_to_calc=(), avg=0):
        """
        from http://stackoverflow.com/questions/25070086/percentiles-from-counts-of-values
        Returns [(percentile, value)] with nearest rank percentiles.
        Percentile 0: <min_value>, 100: <max_value>.
        cnts_dict: { <value>: <count> }
        percentiles_to_calc: iterable for percentiles to calculate; 0 <= ~ <= 100

        upd: added stdev calc to have it in single-pass for mans of efficiency

        :type percentiles_to_calc: list(float)
        :type cnts_dict: collections.Counter
        """
        assert all(0 <= percentile <= 100 for percentile in percentiles_to_calc)
        percentiles = []
        if not cnts_dict:
            return percentiles, 0

        num = sum(cnts_dict.values())
        cnts = sorted(cnts_dict.items())
        curr_cnts_pos = 0  # current position in cnts
        curr_pos = cnts[0][1]  # sum of freqs up to current_cnts_pos

        sqr_diffs = 0
        for percentile in sorted(percentiles_to_calc):
            if percentile < 100:
                percentile_pos = percentile / 100.0 * num
                while curr_pos <= percentile_pos and curr_cnts_pos < len(cnts):
                    sqr_diffs += cnts[curr_cnts_pos][1] * math.pow(cnts[curr_cnts_pos][0] - avg, 2)

                    curr_cnts_pos += 1
                    curr_pos += cnts[curr_cnts_pos][1]

                percentiles.append((percentile, cnts[curr_cnts_pos][0]))
            else:
                percentiles.append((percentile, cnts[-1][0]))  # we could add a small value

        while curr_cnts_pos < len(cnts):
            sqr_diffs += cnts[curr_cnts_pos][1] * math.pow(cnts[curr_cnts_pos][0] - avg, 2)
            curr_cnts_pos += 1

        stdev = math.sqrt(sqr_diffs / len(cnts))
        return percentiles, stdev

class DataPoint(BetterDict):
    """
    Represents an aggregate data poing

    :param ts: timestamp of this point
    """

    SOURCE_ID = 'id'
    TIMESTAMP = "ts"
    CURRENT = "current"
    CUMULATIVE = "cumulative"
    SUBRESULTS = "subresults"

    def __init__(self, ts, perc_levels=()):
        super(DataPoint, self).__init__()
        self.perc_levels = perc_levels
        self[self.SOURCE_ID] = None
        self[self.TIMESTAMP] = ts
        self[self.CUMULATIVE] = BetterDict()
        self[self.CURRENT] = BetterDict()
        self[self.SUBRESULTS] = []

    def __merge_kpis(self, src, dst, sid):
        """
        :param src: KPISet
        :param dst: KPISet
        :param sid: int
        :return:
        """
        for label, val in iteritems(src):
            dest = dst.get(label, KPISet(self.perc_levels))
            if not isinstance(val, KPISet):
                val = KPISet.from_dict(val)
                val.perc_levels = self.perc_levels
            dest.merge_kpis(val, sid)

    def recalculate(self):
        """
        Recalculate all KPISet's
        """
        for val in self[self.CURRENT].values():
            val.recalculate()

        for val in self[self.CUMULATIVE].values():
            val.recalculate()

    def merge_point(self, src):
        """

        :type src: DataPoint
        """
        if self[self.TIMESTAMP] != src[self.TIMESTAMP]:
            self.log.warning("Tried to merge data for %s and %s", self[self.TIMESTAMP], src[self.TIMESTAMP])
            raise ValueError("Cannot merge different timestamps")

        self[DataPoint.SUBRESULTS].append(src)

        self.__merge_kpis(src[self.CURRENT], self[self.CURRENT], src[DataPoint.SOURCE_ID])
        self.__merge_kpis(src[self.CUMULATIVE], self[self.CUMULATIVE], src[DataPoint.SOURCE_ID])

        self.recalculate()

class ResultsProvider(object):
    """
    :type listeners: list[AggregatorListener]
    """

    def __init__(self):
        super(ResultsProvider, self).__init__()
        self.cumulative = BetterDict()
        self.track_percentiles = []
        self.listeners = []

    def add_listener(self, listener):
        """
        Add aggregate results listener

        :type listener: AggregatorListener
        """
        self.listeners.append(listener)

    def __merge_to_cumulative(self, current):
        """
        Merge current KPISet to cumulative
        :param current: KPISet
        :return:
        """
        for label, data in iteritems(current):
            cumul = self.cumulative.get(label, KPISet(self.track_percentiles))
            cumul.merge_kpis(data)

    def datapoints(self, final_pass=False):
        """
        Generator object that returns datapoints from the reader

        :type final_pass: bool
        """
        for datapoint in self._calculate_datapoints(final_pass):
            current = datapoint[DataPoint.CURRENT]
            self.__merge_to_cumulative(current)
            datapoint[DataPoint.CUMULATIVE] = copy.deepcopy(self.cumulative)
            datapoint.recalculate()

            for listener in self.listeners:
                listener.aggregated_second(datapoint)
            yield datapoint

    @abstractmethod
    def _calculate_datapoints(self, final_pass=False):
        """

        :rtype : tuple
        """
        pass

class ResultsReader(ResultsProvider):
    """
    Aggregator that reads samples one by one,
    supposed to be attached to every executor
    """
    label_generalize_regexps = [
        (re.compile(r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b"), "U"),
        (re.compile(r"\b[0-9a-fA-F]{2,}\b"), "U"),
        # (re.compile(r"\b[0-9a-fA-F]{32}\b"), "U"), # implied by previous, maybe prev is too wide
        (re.compile(r"\b\d{2,}\b"), "N")
    ]

    def __init__(self, perc_levels=()):
        super(ResultsReader, self).__init__()
        self.generalize_labels = True
        self.ignored_labels = []
        self.log = logging.getLogger(self.__class__.__name__)
        self.buffer = {}
        self.buffer_len = 2
        self.min_timestamp = 0
        self.track_percentiles = perc_levels

    def __process_readers(self, final_pass=False):
        """

        :param final_pass: True if in post-process stage
        :return:
        """
        for result in self._read(final_pass):
            if result is None:
                self.log.debug("No data from reader")
                break
            elif isinstance(result, list) or isinstance(result, tuple):
                t_stamp, label, conc, r_time, con_time, latency, r_code, error, trname = result
                if label in self.ignored_labels:
                    continue
                if t_stamp < self.min_timestamp:
                    self.log.warning("Putting sample %s into %s", t_stamp, self.min_timestamp)
                    t_stamp = self.min_timestamp
                if t_stamp not in self.buffer:
                    self.buffer[t_stamp] = []
                self.buffer[t_stamp].append((label, conc, r_time, con_time, latency, r_code, error, trname))
            else:
                raise ValueError("Unsupported results from reader: %s" % result)

    def __aggreagate_current(self, datapoint, samples):
        """
        :param datapoint: DataPoint
        :param samples: list of samples
        :return:
        """
        current = datapoint[DataPoint.CURRENT]
        for sample in samples:
            label, r_time, concur, con_time, latency, r_code, error, trname = sample
            if label == '':
                label = '[empty]'

            if self.generalize_labels:
                label = self.__generalize_label(label)

            label = current.get(label, KPISet(self.track_percentiles))
            # empty means overall
            label.add_sample((r_time, concur, con_time, latency, r_code, error, trname))
        overall = KPISet(self.track_percentiles)
        for label in current.values():
            overall.merge_kpis(label, datapoint[DataPoint.SOURCE_ID])
        current[''] = overall
        return current

    def _calculate_datapoints(self, final_pass=False):
        """
        A generator to read available datapoints

        :type final_pass: bool
        :rtype: DataPoint
        """
        self.__process_readers(final_pass)

        self.log.debug("Buffer len: %s", len(self.buffer))
        if not self.buffer:
            return
        timestamps = sorted(self.buffer.keys())
        while final_pass or (timestamps[-1] >= (timestamps[0] + self.buffer_len)):
            timestamp = timestamps.pop(0)
            self.min_timestamp = timestamp + 1
            self.log.debug("Aggregating: %s", timestamp)
            samples = self.buffer.pop(timestamp)
            datapoint = self.__get_new_datapoint(timestamp)
            self.__aggreagate_current(datapoint, samples)
            yield datapoint

            if not timestamps:
                break

    def __get_new_datapoint(self, timestamp):
        """
        :rtype: DataPoint
        """
        point = DataPoint(timestamp, self.track_percentiles)
        point[DataPoint.SOURCE_ID] = id(self)
        return point

    @abstractmethod
    def _read(self, final_pass=False):
        """

        :param final_pass: True if called from post-process stage, when reader
            should report possible rests of results
        :rtype: list
        :return: timestamp, label, concurrency, rt, latency, rc, error
        """
        yield

    def __generalize_label(self, label):
        for regexp, replacement in self.label_generalize_regexps:
            label = regexp.sub(replacement, label)

        return label

class ConsolidatingAggregator(EngineModule, ResultsProvider):
    """

    :type underlings: list[bzt.modules.aggregator.ResultsProvider]
    """
    # FIXME: it was oscillating with remote test of 100 servers
    def __init__(self):
        EngineModule.__init__(self)
        ResultsProvider.__init__(self)
        self.generalize_labels = True
        self.ignored_labels = []
        self.underlings = []
        self.buffer = BetterDict()
        self.buffer_len = 2

    def prepare(self):
        """
        Read aggregation options
        """
        super(ConsolidatingAggregator, self).prepare()
        self.track_percentiles = self.settings.get("percentiles", self.track_percentiles)
        self.buffer_len = self.settings.get("buffer-seconds", self.buffer_len)
        self.ignored_labels = self.settings.get("ignore-labels", self.ignored_labels)
        self.generalize_labels = self.settings.get("generalize-labels", self.generalize_labels)

    def add_underling(self, underling):
        """
        Add source for aggregating

        :type underling: ResultsProvider
        """
        underling.track_percentiles = self.track_percentiles
        if isinstance(underling, ResultsReader):
            underling.ignored_labels = self.ignored_labels
            underling.generalize_labels = self.generalize_labels
            # underling.buffer_len = self.buffer_len  # NOTE: is it ok for underling to have the same buffer len?
        self.underlings.append(underling)

    def check(self):
        """
        Check if there is next aggregate data present

        :rtype: bool
        """
        for point in self.datapoints():
            self.log.debug("Processed datapoint: %s/%s", point[DataPoint.TIMESTAMP], point[DataPoint.SOURCE_ID])
        return super(ConsolidatingAggregator, self).check()

    def post_process(self):
        """
        Process all remaining aggregate data
        """
        super(ConsolidatingAggregator, self).post_process()
        for point in self.datapoints(True):
            self.log.debug("Processed datapoint: %s/%s", point[DataPoint.TIMESTAMP], point[DataPoint.SOURCE_ID])

    def _process_underlings(self, final_pass):
        for underling in self.underlings:
            for data in [x for x in underling.datapoints(final_pass)]:
                tstamp = data[DataPoint.TIMESTAMP]
                if self.buffer:
                    mints = min(self.buffer.keys())
                    if tstamp < mints:
                        self.log.warning("Putting datapoint %s into %s", tstamp, mints)
                        data[DataPoint.TIMESTAMP] = mints
                        tstamp = mints
                self.buffer.get(tstamp, []).append(data)

    def _calculate_datapoints(self, final_pass=False):
        """
        Override ResultsProvider._calculate_datapoints

        """
        self._process_underlings(final_pass)

        self.log.debug("Consolidator buffer[%s]: %s", len(self.buffer), self.buffer.keys())
        if not self.buffer:
            return

        timestamps = sorted(self.buffer.keys())
        while timestamps and (final_pass or (timestamps[-1] >= timestamps[0] + self.buffer_len)):
            tstamp = timestamps.pop(0)
            self.log.debug("Merging into %s", tstamp)
            points_to_consolidate = self.buffer.pop(tstamp)
            point = DataPoint(tstamp, self.track_percentiles)
            for subresult in points_to_consolidate:
                self.log.debug("Merging %s", subresult[DataPoint.TIMESTAMP])
                point.merge_point(subresult)
            point.recalculate()
            yield point

class NoneAggregator(EngineModule, ResultsProvider):
    """
    Dummy aggregator
    """

    def __init__(self):
        EngineModule.__init__(self)
        ResultsProvider.__init__(self)

    def _calculate_datapoints(self, final_pass=False):
        pass


text:
@implementation IndexButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.imageView.contentMode = UIViewContentModeCenter;
    }
    return self;
}

+(IndexButton *)buttonWithTitle:(NSString *)title andFrame:(CGRect)frame andImageName:(NSString *)imageName andClass:(id)classobject andSEL:(SEL)sel
{
    // 自定义Button
    IndexButton *inBtn = [[IndexButton alloc] init];
    inBtn.frame = frame;
    inBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [inBtn setTitle:title forState:UIControlStateNormal];
    [inBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [inBtn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [inBtn addTarget:classobject action:sel forControlEvents:UIControlEventTouchUpInside];

    return inBtn;
}

//-(void)setHighlighted:(BOOL)highlighted
//{
//    // 取消高亮
//}

-(CGRect)titleRectForContentRect:(CGRect)contentRect
{

    NSDictionary *dict = @{
                           NSFontAttributeName : [UIFont systemFontOfSize:14]
                           };
    CGFloat titleW = 0;

    titleW = [self.currentTitle boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size.width;

    CGFloat titleH = [self.currentTitle boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size.height;

    CGFloat titleX = (contentRect.size.width - titleW) / 2.0;
    CGFloat titleY = 55;

    return CGRectMake(titleX, titleY, titleW, titleH);

}

-(CGRect)imageRectForContentRect:(CGRect)contentRect
{
    CGFloat imageW = 60;
    CGFloat imageH = 60;
    CGFloat imageX = (contentRect.size.width - imageW) / 2.0;
    CGFloat imageY = 0;

    return CGRectMake(imageX, imageY, imageW, imageH);
}

@end

redpajama_set_name: RedPajamaGithub


text:
/****************************************************************************
 * libc/uio/lib_readv.c
 *
 *   Copyright (C) 2017 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: readv()
 *
 * Description:
 *   The readv() function is equivalent to read(), except as described below.
 *   The readv() function places the input data into the iovcnt buffers
 *   specified by the members of the iov array: iov[0], iov[1], ...,
 *   iov[iovcnt-1].  The iovcnt argument is valid if greater than 0 and less
 *   than or equal to IOV_MAX as defined in limits.h.
 *
 *   Each iovec entry specifies the base address and length of an area in
 *   memory where data should be placed.  The readv() function will always
 *   fill an area completely before proceeding to the next.
 *
 *   Upon successful completion, readv() will mark for update the st_atime
 *   field of the file.
 *
 * Input Parameters:
 *   filedes - The open file descriptor for the file to be read
 *   iov     - Array of read buffer descriptors
 *   iovcnt  - Number of elements in iov[]
 *
 * Returned Value:
 *   Upon successful completion, readv() will return a non-negative integer
 *   indicating the number of bytes actually read.  Otherwise, the functions
 *   will return -1 and set errno to indicate the error.  See read().
 *
 ****************************************************************************/

ssize_t readv(int fildes, FAR const struct iovec *iov, int iovcnt)
{
	ssize_t ntotal;
	ssize_t nread;
	size_t remaining;
	FAR uint8_t *buffer;
	int i;

	/* Process each entry in the struct iovec array */

	for (i = 0, ntotal = 0; i < iovcnt; i++) {
		/* Ignore zero-length reads */

		if (iov[i].iov_len > 0) {
			buffer    = iov[i].iov_base;
			remaining = iov[i].iov_len;

			/* Read repeatedly as necessary to fill buffer */

			do {
				/* NOTE:  read() is a cancellation point */

				nread = read(fildes, buffer, remaining);

				/* Check for a read error */

				if (nread < 0) {
					return nread;
				}

				/* Check for an end-of-file condition */

				else if (nread == 0) {
					return ntotal;
				}

				/* Update pointers and counts in order to handle partial
				 * buffer reads.
				 */

				buffer    += nread;
				remaining -= nread;
				ntotal    += nread;
			} while (remaining > 0);
		}
	}

	return ntotal;
}


text:
public class MyLinkedList<E> extends MyAbstractList<E> {
  private Node<E> head, tail;

  public MyLinkedList() {
  }

  public MyLinkedList(E[] objects) {
    super(objects);
  }

  public E getFirst() {
    if (size == 0) { return null; }
    else { return head.element; }
  }

  public E getLast() {
    if (size == 0) { return null; }
    else { return tail.element; }
  }

  public void addFirst(E e) {
    Node<E> newNode = new Node<>(e);
    newNode.next = head;
    head = newNode;
    size++;

    if (tail == null) { tail = head; }
  }

  public void addLast(E e) {
    Node<E> newNode = new Node<>(e);

    if (tail == null) { head = tail = newNode; }
    else {
      tail.next = newNode;
      tail = tail.next;
    }

    size++;
  }

  public void add(int index, E e) {
    if (index == 0) { addFirst(e); }
    else if (index >= size) { addLast(e); }
    else {
      Node<E> current = head;
      for (int i = 1; i < index; i++) {
        current = current.next;
      }
      Node<E> temp = current.next;
      current.next = new Node<E>(e);
      (current.next).next = temp;
      size++;
    }
  }

  public E removeFirst() {
    if (size == 0) { return null; }
    else {
      Node<E> temp = head;
      head = head.next;
      size--;
      if (head == null) { tail = null; }
      return temp.element;
    }
  }

  public E removeLast() {
    if (size == 0) { return null; }
    else if (size == 1) {
      Node<E> temp = head;
      head = tail = null;
      size = 0;
      return temp.element;
    } else {
      Node<E> current = head;

      for (int i = 0; i < size - 2; i++) {
        current = current.next;
      }

      Node<E> temp = tail;
      tail = current;
      tail.next = null;
      size--;
      return temp.element;
    }
  }

  public E remove(int index) {
    if (index < 0 || index >= size) { return null; }
    else if (index == 0) { return removeFirst(); }
    else if (index == size - 1) { return removeLast(); }
    else {
      Node<E> previous = head;

      for (int i = 1; i < index; i++) {
        previous = previous.next;
      }

      Node<E> current = previous.next;
      previous.next = current.next;
      size--;
      return current.element;
    }
  }

  @Override
  public String toString() {
    StringBuilder result = new StringBuilder("[");

    Node<E> current = head;
    for (int i = 0; i < size; i++) {
      result.append(current.element);
      current = current.next;
      if (current != null) {
        result.append(", ");
      } else {
        result.append("]");
      }
    }

    if (size == 0) { result.append("]"); }

    return result.toString();
  }

  @Override
  public void clear() {
    size = 0;
    head = tail = null;
  }

  @Override
  public boolean contains(E e) {
    Node<E> current = head;
    for (int i = 0; i < size; i++) {
      if (e.equals(current.element)) { return true; }
      current = current.next;
    }
    return false;
  }

  @Override
  public E get(int index) {
    if (index < 0 || index >= size || size == 0) {
      throw new IndexOutOfBoundsException(index + "");
    }
    Node<E> current = head;
    for (int i = 0; i < index; i++) {
      current = current.next;
    }
    return current.element;
  }

  @Override
  public int indexOf(E e) {
    Node<E> current = head;
    for (int i = 0; i < size; i++) {
      if (e.equals(current.element)) { return i; }
      current = current.next;
    }
    return -1;
  }

  @Override
  public int lastIndexOf(E e) {
    Node<E> current = head;
    int largestIndex = -1;
    for (int i = 0; i < size; i++) {
      if (e.equals(current.element)) { largestIndex = i; }
      current = current.next;
    }
    return largestIndex;
  }

  @Override
  public E set(int index, E e) {
    if (index < 0 || index >= size || size == 0) {
      throw new IndexOutOfBoundsException(index + "");
    }
    Node<E> current = head;
    for (int i = 0; i < index; i++) {
      current = current.next;
    }
    E temp = current.element;
    current.element = e;
    return temp;
  }

  @Override
  public java.util.Iterator<E> iterator() {
    return new LinkedListIterator();
  }

  private class LinkedListIterator implements java.util.Iterator<E> {
    private Node<E> current = head;

    @Override
    public boolean hasNext() {
      return (current != null);
    }

    @Override
    public E next() {
      E e = current.element;
      current = current.next;
      return e;
    }

    @Override
    public void remove() {
      System.out.println("Implementation left as exercise");
    }
  }

  private static class Node<E> {
    E element;
    Node<E> next;

    public Node(E element) {
      this.element = element;
    }
  }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Br. mycol. Soc. 48: 461 (1965)

#### Original name
Sporotrichum cerealis Thüm., 1880

### Remarks
null


text:
package de.unipaderborn.visuflow.wizard;

import java.io.IOException;
//import java.util.HashSet;
import java.util.Map;
import java.util.Set;

//import java.util.Set;
import com.sun.codemodel.JBlock;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JClassAlreadyExistsException;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
import com.sun.codemodel.JPackage;
import com.sun.codemodel.JType;
import com.sun.codemodel.JVar;

import heros.FlowFunctions;
import soot.G;
import soot.jimple.toolkits.ide.icfg.JimpleBasedInterproceduralCFG;
import soot.toolkits.graph.ExceptionalUnitGraph;

import heros.InterproceduralCFG;
import heros.solver.IFDSSolver;

/**
 *
 * @author kaarthik
 *
 */
public class CodeGenerator {

	/**
	 * This function generates the source code according to the input from the input.
	 * @param input The wizard object from the Visuflow wizard.
	 * @throws JClassAlreadyExistsException
	 * @throws IOException
	 */
	public static void generateSource(WizardInput input) throws JClassAlreadyExistsException, IOException {
		if (input.AnalysisFramework.equals("Soot")) {
			generateGeneralClass(input);

		} else {
			generateIFDSClass(input);
		}
		generateMain(input);
	}

	/**
	 * This function is responsible for generating the stub for normal soot analysis based on user input.
	 * @param input The wizard object from the Visuflow wizard.
	 * @throws JClassAlreadyExistsException
	 * @throws IOException
	 */
	public static void generateGeneralClass(WizardInput input) throws JClassAlreadyExistsException, IOException {
		JCodeModel codeModel = new JCodeModel();
		JPackage jp = codeModel._package(input.getPackageName());
		JDefinedClass classToBeCreated = jp._class(input.getAnalysisType());

		classToBeCreated.field(JMod.PRIVATE, Integer.class, "flowThroughCount").assign(JExpr.lit(0));
		classToBeCreated.field(JMod.PRIVATE | JMod.FINAL, soot.SootMethod.class, "method");

		JClass flowAbstraction = null;
		try {
			flowAbstraction = codeModel.ref(Class.forName("java.util." + input.getFlowType()));

			if (input.getFlowType1() != null && !input.getFlowType1().equals("Custom")) {
				flowAbstraction = flowAbstraction.narrow(Class.forName("java.lang." + input.getFlowType1()));
			} else if (input.getCustomClassFirst() != null) {
				JDefinedClass firstClass = jp._class(input.getCustomClassFirst());
				flowAbstraction = flowAbstraction.narrow(firstClass);
			}

			if (input.getFlowtype2() != null && !input.getFlowtype2().equals("Custom")) {
				flowAbstraction = flowAbstraction.narrow(Class.forName("java.lang." + input.getFlowtype2()));
			} else if (input.getCustomClassSecond() != null) {
				JDefinedClass secondClass = jp._class(input.getCustomClassSecond());
				flowAbstraction = flowAbstraction.narrow(secondClass);
			}

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// JClass flowAbstraction = codeModel.ref(HashSet.class).narrow(Integer.class);
		JClass jClassExtends = null;
		try {
			jClassExtends = codeModel.ref(Class.forName("soot.toolkits.scalar." + input.getAnalysisDirection() + "FlowAnalysis")).narrow(soot.Unit.class)
					.narrow(flowAbstraction);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		classToBeCreated._extends(jClassExtends);
		JMethod ctor = classToBeCreated.constructor(JMod.PUBLIC);
		ctor.param(soot.Body.class, "body");
		// ctor.param(Integer.class, "reporter");
		JBlock ctorBlock = ctor.body();
		JType exceptionalType = codeModel.ref(ExceptionalUnitGraph.class);
		ctorBlock.invoke("super").arg(JExpr._new(exceptionalType).arg(JExpr.ref("body")));

		ctorBlock.assign(JExpr._this().ref("method"), JExpr.ref("body").invoke("getMethod"));

		// Flow through function
		JMethod flowThrough = classToBeCreated.method(JMod.PUBLIC, void.class, "flowThrough");
		flowThrough.param(flowAbstraction, "in");
		flowThrough.param(soot.Unit.class, "unit");
		flowThrough.param(flowAbstraction, "out");
		flowThrough.annotate(codeModel.ref(Override.class));

		// InitialFlow
		JMethod newInitialFlow = classToBeCreated.method(JMod.PROTECTED, flowAbstraction, "newInitialFlow");
		JBlock newInitialFlowBlock = newInitialFlow.body();
		newInitialFlow.annotate(codeModel.ref(Override.class));
		JVar newInitialFlowImpl = newInitialFlowBlock.decl(flowAbstraction, "varName");
		// newInitialFlowImpl.init(JExpr._new(flowAbstraction));
		newInitialFlowBlock._return(newInitialFlowImpl);

		JMethod entryInitialFlow = classToBeCreated.method(JMod.PROTECTED, flowAbstraction, "entryInitialFlow");
		JBlock entryInitialFlowBlock = entryInitialFlow.body();
		entryInitialFlow.annotate(codeModel.ref(Override.class));
		JVar entryInitialFlowImpl = entryInitialFlowBlock.decl(flowAbstraction, "varName");
		// entryInitialFlowImpl.init(JExpr._new(flowAbstraction));
		entryInitialFlowBlock._return(entryInitialFlowImpl);

		JMethod merge = classToBeCreated.method(JMod.PROTECTED, void.class, "merge");
		merge.param(flowAbstraction, "in1");
		merge.param(flowAbstraction, "in2");
		merge.param(flowAbstraction, "out");
		merge.annotate(codeModel.ref(Override.class));
		if (input.getFlowType() != "Set") {
			merge.body().invoke(JExpr.ref("out"), "putAll").arg(JExpr.ref("in1"));
			merge.body().invoke(JExpr.ref("out"), "putAll").arg(JExpr.ref("in2"));
		} else {
			merge.body().invoke(JExpr.ref("out"), "addAll").arg(JExpr.ref("in1"));
			merge.body().invoke(JExpr.ref("out"), "addAll").arg(JExpr.ref("in2"));
		}

		JMethod copy = classToBeCreated.method(JMod.PROTECTED, void.class, "copy");
		copy.param(flowAbstraction, "source");
		copy.param(flowAbstraction, "dest");
		copy.annotate(codeModel.ref(Override.class));
		copy.body().invoke(JExpr.ref("dest"), "clear");
		if (input.getFlowType() != "Set") {
			copy.body().invoke(JExpr.ref("dest"), "putAll").arg(JExpr.ref("source"));
		} else {
			copy.body().invoke(JExpr.ref("dest"), "addAll").arg(JExpr.ref("source"));
		}

		JMethod doAnalysis = classToBeCreated.method(JMod.PROTECTED, void.class, "doAnalysis");
		doAnalysis.body().invoke(JExpr._super(), "doAnalysis");
		codeModel.build(input.getFile());
		// generateMain(input);
	}

	/**
	 * This function is responsible for generating the stub for IFDS/IDE analysis based on user input.
	 * @param input The wizard object from the Visuflow wizard.
	 * @throws JClassAlreadyExistsException
	 * @throws IOException
	 */
	public static void generateIFDSClass(WizardInput input) throws JClassAlreadyExistsException, IOException {
		JCodeModel codeModel = new JCodeModel();
		JPackage jp = codeModel._package(input.getPackageName());
		JDefinedClass classToBeCreated = jp._class(input.getAnalysisType());

		JClass flowAbstraction = null;
		try {
			if(!input.getFlowType().equals("Select")){
			flowAbstraction = codeModel.ref(Class.forName("java.util." + input.getFlowType()));

			if (input.getFlowType1() != null && !input.getFlowType1().equals("Custom")) {
				flowAbstraction = flowAbstraction.narrow(Class.forName("java.lang." + input.getFlowType1()));
			} else if (input.getCustomClassFirst() != null) {
				JDefinedClass firstClass = jp._class(input.getCustomClassFirst());
				flowAbstraction = flowAbstraction.narrow(firstClass);
			}

			if (input.getFlowtype2() != null && !input.getFlowtype2().equals("Custom")) {
				flowAbstraction = flowAbstraction.narrow(Class.forName("java.lang." + input.getFlowtype2()));
			} else if (input.getCustomClassSecond() != null) {
				JDefinedClass secondClass = jp._class(input.getCustomClassSecond());
				flowAbstraction = flowAbstraction.narrow(secondClass);
			}
			}
			else{
				if (input.getFlowType1() != null && !input.getFlowType1().equals("Custom")) {
					flowAbstraction = codeModel.ref(Class.forName("java.lang." + input.getFlowType1()));
				} else if (input.getCustomClassFirst() != null) {
					flowAbstraction = jp._class(input.getCustomClassFirst());
				}
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		JClass interproceduralCFG = codeModel.ref(heros.InterproceduralCFG.class);
		interproceduralCFG = interproceduralCFG.narrow(soot.Unit.class);
		interproceduralCFG = interproceduralCFG.narrow(soot.SootMethod.class);

		JClass extendsClass = codeModel.ref(soot.jimple.toolkits.ide.DefaultJimpleIFDSTabulationProblem.class);
		extendsClass = extendsClass.narrow(flowAbstraction);
		extendsClass = extendsClass.narrow(interproceduralCFG);

		classToBeCreated._extends(extendsClass);

		JMethod ctor = classToBeCreated.constructor(JMod.PUBLIC);
		ctor.param(interproceduralCFG, "icfg");
		JBlock ctorBlock = ctor.body();
		ctorBlock.invoke("super").arg(JExpr.ref("icfg"));

		JClass mapParam = codeModel.ref(Map.class);
		mapParam = mapParam.narrow(soot.Unit.class);
		JClass setParam = codeModel.ref(Set.class).narrow(flowAbstraction);
		mapParam = mapParam.narrow(setParam);

		JMethod initialSeeds = classToBeCreated.method(JMod.PUBLIC, mapParam, "initialSeeds");
		initialSeeds.annotate(codeModel.ref(Override.class));
		initialSeeds.body()._return(JExpr._null());

		JClass flowFunctions = codeModel.ref(FlowFunctions.class);
		flowFunctions = flowFunctions.narrow(soot.Unit.class);
		flowFunctions = flowFunctions.narrow(flowAbstraction);
		flowFunctions = flowFunctions.narrow(soot.SootMethod.class);

		JMethod createFlowFunctionsFactory = classToBeCreated.method(JMod.PROTECTED, flowFunctions, "createFlowFunctionsFactory");
		createFlowFunctionsFactory.annotate(codeModel.ref(Override.class));
		createFlowFunctionsFactory.body()._return(JExpr._null());

		JMethod createZeroValue = classToBeCreated.method(JMod.PROTECTED, flowAbstraction, "createZeroValue");
		createZeroValue.annotate(codeModel.ref(Override.class));
		createZeroValue.body()._return(JExpr._null());
		codeModel.build(input.getFile());
	}

	/**
	 * This function is responsible for generating the stub for the main method of the analysis based on user input.
	 * @param input The wizard object from the Visuflow wizard.
	 * @throws JClassAlreadyExistsException
	 * @throws IOException
	 */
	public static void generateMain(WizardInput input) throws JClassAlreadyExistsException, IOException {
		JCodeModel codeModel = new JCodeModel();
		JPackage jp = codeModel._package(input.getPackageName());
		JDefinedClass classToBeCreated = jp._class(input.getClassName());
		JMethod runAnalysis = classToBeCreated.method(JMod.PUBLIC | JMod.STATIC, void.class, "runAnalysis");
		JBlock runAnalysisBody = runAnalysis.body();
		JClass sootG = codeModel.ref(G.class);
		runAnalysisBody.staticInvoke(sootG, "reset");

		if (input.AnalysisFramework.equals("Soot")) {
			JClass transform = codeModel.ref(soot.Transform.class);
			JDefinedClass anonymousBodyTransformer = codeModel.anonymousClass(soot.BodyTransformer.class);
			JMethod internalTrasnform = anonymousBodyTransformer.method(JMod.PROTECTED, void.class, "internalTransform");
			internalTrasnform.param(soot.Body.class, "b");
			internalTrasnform.param(String.class, "phaseName");

			JClass jClassExtends = codeModel.ref(Map.class).narrow(String.class).narrow(String.class);
			internalTrasnform.param(jClassExtends, "options");
			internalTrasnform.annotate(codeModel.ref(Override.class));
			JBlock internalTrasnformBlock = internalTrasnform.body();

			JClass ipa = codeModel.ref(input.getAnalysisType());
			JVar newInitialFlowImpl = internalTrasnformBlock.decl(ipa, "ipa");
			newInitialFlowImpl.init(JExpr._new(ipa).arg(JExpr.ref("b")));
			internalTrasnformBlock.invoke(JExpr.ref("ipa"), "doAnalysis");
			runAnalysisBody.decl(transform, "transform").init(JExpr._new(transform).arg(JExpr.lit("jtp.analysis")).arg(JExpr._new(anonymousBodyTransformer)));
			codeModel.ref(soot.PackManager.class).staticRef("v()").invoke("getPath");
			runAnalysisBody
					.add(codeModel.ref(soot.PackManager.class).staticRef("v()").invoke("getPack").arg(JExpr.lit("jtp")).invoke("add").arg(JExpr.ref("transform")));

			JClass sootMain = codeModel.ref(soot.Main.class);
			runAnalysisBody.staticInvoke(sootMain, "main").arg(JExpr.newArray(codeModel.ref(String.class)).add(JExpr.lit("-pp")).add(JExpr.lit("-process-dir")));
			JMethod mainMethod = classToBeCreated.method(JMod.PUBLIC | JMod.STATIC, void.class, "main");
			mainMethod.param(String[].class, "args");
			JBlock mainMethodBlock = mainMethod.body();
			mainMethodBlock.invoke("runAnalysis");

		} else {
			JClass transform = codeModel.ref(soot.Transform.class);
			JDefinedClass anonymousBodyTransformer = codeModel.anonymousClass(soot.SceneTransformer.class);
			JMethod internalTrasnform = anonymousBodyTransformer.method(JMod.PROTECTED, void.class, "internalTransform");
			internalTrasnform.param(String.class, "phaseName");

			JClass jClassExtends = codeModel.ref(Map.class).narrow(String.class).narrow(String.class);
			internalTrasnform.param(jClassExtends, "options");
			internalTrasnform.annotate(codeModel.ref(Override.class));
			JBlock internalTrasnformBlock = internalTrasnform.body();

			JClass ipa = codeModel.ref(InterproceduralCFG.class);
			ipa = ipa.narrow(soot.Unit.class);
			ipa = ipa.narrow(soot.SootMethod.class);
			JVar newInitialFlowImpl = internalTrasnformBlock.decl(ipa, "icfg");
			JClass jimpleICFG = codeModel.ref(JimpleBasedInterproceduralCFG.class);
			newInitialFlowImpl.init(JExpr._new(jimpleICFG));

			JClass ipaproblem = codeModel.ref(input.getAnalysisType());
			JVar ipaproblemImpl = internalTrasnformBlock.decl(ipaproblem, "problem");
			ipaproblemImpl.init(JExpr._new(ipaproblem).arg(JExpr.ref("icfg")));

			JClass flowAbstraction = null;
			try {
				if(!input.getFlowType().equals("Select")){
				flowAbstraction = codeModel.ref(Class.forName("java.util." + input.getFlowType()));

				if (input.getFlowType1() != null && !input.getFlowType1().equals("Custom")) {
					flowAbstraction = flowAbstraction.narrow(Class.forName("java.lang." + input.getFlowType1()));
				} else if (input.getCustomClassFirst() != null) {
					JDefinedClass firstClass = jp._class(input.getCustomClassFirst());
					flowAbstraction = flowAbstraction.narrow(firstClass);
				}

				if (input.getFlowtype2() != null && !input.getFlowtype2().equals("Custom")) {
					flowAbstraction = flowAbstraction.narrow(Class.forName("java.lang." + input.getFlowtype2()));
				} else if (input.getCustomClassSecond() != null) {
					JDefinedClass secondClass = jp._class(input.getCustomClassSecond());
					flowAbstraction = flowAbstraction.narrow(secondClass);
				}
				}else{
					if (input.getFlowType1() != null && !input.getFlowType1().equals("Custom")) {
						flowAbstraction = codeModel.ref(Class.forName("java.lang." + input.getFlowType1()));
					} else if (input.getCustomClassFirst() != null) {
						flowAbstraction = jp._class(input.getCustomClassFirst());
					}
				}

			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			JClass ifdsSolver = codeModel.ref(IFDSSolver.class);
			ifdsSolver = ifdsSolver.narrow(soot.Unit.class);
			ifdsSolver = ifdsSolver.narrow(flowAbstraction);
			ifdsSolver = ifdsSolver.narrow(soot.SootMethod.class);
			ifdsSolver = ifdsSolver.narrow(ipa);
			JVar ifdsSolverImpl = internalTrasnformBlock.decl(ifdsSolver, "solver");
			ifdsSolverImpl.init(JExpr._new(ifdsSolver).arg(JExpr.ref("problem")));

			internalTrasnformBlock.invoke(JExpr.ref("solver"), "solve");

			runAnalysisBody.decl(transform, "transform").init(JExpr._new(transform).arg(JExpr.lit("wjtp.analysis")).arg(JExpr._new(anonymousBodyTransformer)));
			codeModel.ref(soot.PackManager.class).staticRef("v()").invoke("getPath");
			runAnalysisBody
					.add(codeModel.ref(soot.PackManager.class).staticRef("v()").invoke("getPack").arg(JExpr.lit("wjtp")).invoke("add").arg(JExpr.ref("transform")));

			JClass sootMain = codeModel.ref(soot.Main.class);
			runAnalysisBody.staticInvoke(sootMain, "main").arg(JExpr.newArray(codeModel.ref(String.class)).add(JExpr.lit("-pp")).add(JExpr.lit("-process-dir")));
			JMethod mainMethod = classToBeCreated.method(JMod.PUBLIC | JMod.STATIC, void.class, "main");
			mainMethod.param(String[].class, "args");
			JBlock mainMethodBlock = mainMethod.body();
			mainMethodBlock.invoke("runAnalysis");
		}

		codeModel.build(input.getFile());
	}
}


text:
<!DOCTYPE HTML>

<title>ZipExtraField (Apache Ant API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="dc.created" content="2020-05-10">
<meta name="description" content="declaration: package: org.apache.tools.zip, interface: ZipExtraField">
<meta name="generator" content="javadoc/ClassWriterImpl">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../script-dir/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

Package org.apache.tools.zip

Interface ZipExtraField

All Known Subinterfaces:

CentralDirectoryParsingZipExtraField

All Known Implementing Classes:

AbstractUnicodeExtraField, AsiExtraField, JarMarker, UnicodeCommentExtraField, UnicodePathExtraField, UnparseableExtraFieldData, UnrecognizedExtraField, Zip64ExtendedInformationExtraField

public interface ZipExtraField

General format of extra field data.

Extra fields usually appear twice per file, once in the local
 file data and once in the central directory.  Usually they are the
 same, but they don't have to be.  java.util.zip.ZipOutputStream will
 only use the local file data in both places.

Method Summary

<button role="tab" aria-selected="true" aria-controls="memberSummary_tabpanel" tabindex="0" onkeydown="switchTab(event)" id="t0" class="activeTableTab">All Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t2" class="tableTab" onclick="show(2);">Instance Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t3" class="tableTab" onclick="show(4);">Abstract Methods</button>

Modifier and Type
Method
Description

byte[]
getCentralDirectoryData()

The actual data to put into central directory - without Header-ID or
 length specifier.

ZipShort
getCentralDirectoryLength()

Length of the extra field in the central directory - without
 Header-ID or length specifier.

ZipShort
getHeaderId()

The Header-ID.

byte[]
getLocalFileDataData()

The actual data to put into local file data - without Header-ID
 or length specifier.

ZipShort
getLocalFileDataLength()

Length of the extra field in the local file data - without
 Header-ID or length specifier.

void
parseFromLocalFileData(byte[] data,
int offset,
int length)

Populate data from this array as if it was in local file data.

Method Details

getHeaderId

ZipShort getHeaderId()

The Header-ID.

Returns:

the header id

Since:

1.1

getLocalFileDataLength

ZipShort getLocalFileDataLength()

Length of the extra field in the local file data - without
 Header-ID or length specifier.

Returns:

the length of the field in the local file data

Since:

1.1

getCentralDirectoryLength

ZipShort getCentralDirectoryLength()

Length of the extra field in the central directory - without
 Header-ID or length specifier.

Returns:

the length of the field in the central directory

Since:

1.1

getLocalFileDataData

byte[] getLocalFileDataData()

The actual data to put into local file data - without Header-ID
 or length specifier.

Returns:

the data

Since:

1.1

getCentralDirectoryData

byte[] getCentralDirectoryData()

The actual data to put into central directory - without Header-ID or
 length specifier.

Returns:

the data

Since:

1.1

parseFromLocalFileData

void parseFromLocalFileData(byte[] data,
int offset,
int length)
                     throws java.util.zip.ZipException

Populate data from this array as if it was in local file data.

Parameters:

data - an array of bytes

offset - the start offset

length - the number of bytes in the array from offset

Throws:

java.util.zip.ZipException - on error

Since:

1.1

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package picocli.spring.boot.autoconfigure.example.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import picocli.CommandLine;
import picocli.spring.boot.autoconfigure.sample.MyCommand;
import picocli.spring.boot.autoconfigure.sample.MySpringApp;

import static org.junit.Assert.*;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;

/**
 * Add the following dependency to your build.gradle:
 *
 * <pre>
 * dependencies {
 *     // ...
 *     testImplementation "org.springframework.boot:spring-boot-starter-test:$springBootVersion"
 * }
 * </pre>
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = NONE, classes = MySpringApp.class)
public class ExampleTest {

    @Autowired
    CommandLine.IFactory factory;

    @Autowired
    MyCommand myCommand;

    @Test
    public void testParsingCommandLineArgs() {
        CommandLine.ParseResult parseResult = new CommandLine(myCommand, factory)
            .parseArgs("-x", "abc", "sub", "-y", "123");
        assertEquals("abc", myCommand.x);
        assertNull(myCommand.positionals);

        assertTrue(parseResult.hasSubcommand());
        CommandLine.ParseResult subResult = parseResult.subcommand();
        MyCommand.Sub sub = (MyCommand.Sub) subResult.commandSpec().userObject();
        assertEquals("123", sub.y);
        assertNull(sub.positionals);
    }

    @Test
    public void testUsageHelp() {
        String expected = String.format("" +
            "Usage: mycommand [-hV] [-x=<x>] [<positionals>...] [COMMAND]%n" +
            "      [<positionals>...]   positional params%n" +
            "  -h, --help               Show this help message and exit.%n" +
            "  -V, --version            Print version information and exit.%n" +
            "  -x=<x>                   optional option%n" +
            "Commands:%n" +
            "  sub%n");
        String actual = new CommandLine(myCommand, factory).getUsageMessage(CommandLine.Help.Ansi.OFF);
        assertEquals(expected, actual);
    }
}


text:
package com.microsoft.azure.management.recoveryservices.backup.v2016_06_01;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

/**
 * Defines values for BackupManagementType.
 */
public enum BackupManagementType {
    /** Enum value Invalid. */
    INVALID("Invalid"),

    /** Enum value AzureIaasVM. */
    AZURE_IAAS_VM("AzureIaasVM"),

    /** Enum value MAB. */
    MAB("MAB"),

    /** Enum value DPM. */
    DPM("DPM"),

    /** Enum value AzureBackupServer. */
    AZURE_BACKUP_SERVER("AzureBackupServer"),

    /** Enum value AzureSql. */
    AZURE_SQL("AzureSql");

    /** The actual serialized value for a BackupManagementType instance. */
    private String value;

    BackupManagementType(String value) {
        this.value = value;
    }

    /**
     * Parses a serialized value to a BackupManagementType instance.
     *
     * @param value the serialized value to parse.
     * @return the parsed BackupManagementType object, or null if unable to parse.
     */
    @JsonCreator
    public static BackupManagementType fromString(String value) {
        BackupManagementType[] items = BackupManagementType.values();
        for (BackupManagementType item : items) {
            if (item.toString().equalsIgnoreCase(value)) {
                return item;
            }
        }
        return null;
    }

    @JsonValue
    @Override
    public String toString() {
        return this.value;
    }
}


text:
    <mat-card class="oppia-page-card oppia-long-text">

          <subtopic-summary-tile [classroomUrlFragment]="classroomUrlFragment"
                                 [subtopic]="subtopic"
                                 [topicId]="topicId"
                                 [topicUrlFragment]="topicUrlFragment">
          </subtopic-summary-tile>

    </mat-card>


text:
<?php

declare(strict_types=1);

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Tests\Tokenizer\Analyzer\Analysis;

use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\CaseAnalysis;

/**
 * @covers \PhpCsFixer\Tokenizer\Analyzer\Analysis\CaseAnalysis
 *
 * @internal
 */
final class CaseAnalysisTest extends TestCase
{
    public function testColonIndex(): void
    {
        $analysis = new CaseAnalysis(20);
        static::assertSame(20, $analysis->getColonIndex());
    }
}


text:
$context.section('Простая панель');
//= require panel-basic
$context.section('Заголовок');
//= require panel-header
$context.section('Кнопки в подвале');
//= require panel-buttons-footer
$context.section('Кнопки в заголовке');
//= require panel-buttons-header
$context.section('Типы');
//= require panel-type


text:
export const INCREMENT = 'INCREMENT'
export const DECREMENT = 'DECREMENT'

export const SELECT_OP = 'SELECT_OP'
export const UPDATE1 = 'UPDATE1'
export const UPDATE2 = 'UPDATE2'

export const LOCK_UI = 'LOCK_UI'
export const UNLOCK_UI = 'UNLOCK_UI'

export const PUSH_HISTORY = 'PUSH_HISTORY'
export const REPLACE_HISTORY = 'REPLACE_HISTORY'
export const GO_TO = 'GO_TO'
export const GO_BACK = 'GO_BACK'
export const GO_FORWARD = 'GO_FORWARD'
export const CHANGE_LOCATION = 'CHANGE_LOCATION'


text:
<?php

namespace Multidanze\Twittie;

use Phalcon\DiInterface;
use Abraham\TwitterOAuth\TwitterOAuth;

/**
 * Class Mailer
 *
 * @package Multidanze\Twittie
 */
class Twittie
{
    /**
     * @var api_key
     */
    protected $api_key;

    /**
     * @var api_secret
     */
    protected $api_secret;

    /**
     * @var access_token
     */
    protected $access_token;

    /**
     * @var access_secret
     */
    protected $access_secret;

    /**
     * Create a new service provider instance.
     *
     * @param array $config
     */
    public function __construct($config)
    {
        if (!$config->api_key || !$config->api_secret || $config->api_key == 'api_key_here' || $config->api_secret == 'api_secret_here') {
            throw new \RuntimeException('You need a consumer key and secret keys. Get one from dev.twitter.com/apps');
        }

        $this->api_key = $config->api_key;
        $this->api_secret = $config->api_secret;
        $this->access_token = $config->access_token;
        $this->access_secret = $config->access_secret;
    }

    public function getTweets($username, $number, $exclude_replies, $list_slug, $hashtag)
    {
        // Connect
        $connection = $this->getConnectionWithToken();

        // Get Tweets
        if (!empty($list_slug)) {
            $params = array(
                'owner_screen_name' => $username,
                'slug' => $list_slug,
                'per_page' => $number
            );

            $url = '/lists/statuses';
        } else if($hashtag) {
            $params = array(
                'count' => $number,
                'q' => '#'.$hashtag
            );

            $url = '/search/tweets';
        } else {
            $params = array(
                'count' => $number,
                'exclude_replies' => $exclude_replies,
                'screen_name' => $username
            );

            $url = '/statuses/user_timeline';
        }

        $tweets = $connection->get($url, $params);
        return $tweets;
    }

    /**
     * Gets connection with user Twitter account
     * @return Object               Twitter Session
     */
    protected function getConnectionWithToken()
    {
        $connection = new TwitterOAuth($this->api_key, $this->api_secret, $this->access_token, $this->access_secret);

        return $connection;
    }

}


text:
package forplay.sample.noise.html;

import forplay.core.ForPlay;
import forplay.html.HtmlAssetManager;
import forplay.html.HtmlGame;
import forplay.html.HtmlPlatform;
import forplay.sample.noise.core.NoiseGame;
import forplay.sample.noise.resources.NoiseAutoBundle;

public class NoiseGameHtml extends HtmlGame {

  @Override
  public void start() {
    HtmlPlatform platform = HtmlPlatform.register();

    HtmlAssetManager assets = platform.assetManager();
    assets.addClientBundle("^", NoiseAutoBundle.INSTANCE);

    ForPlay.run(new NoiseGame());
  }
}


text:
layout: docs
outdated_text: "Эта версия документации устарела!"
in_development_text: "Эта версия документации находится в стадии разработки!"
click_here_text: "Нажмите здесь для последней выпущенной версии."
toc_text: "Содержание"
latest_text: "Последняя"
visit_github_text: "Другие версии на GitHub."
plugin_version_text: "Эта документация описывает этот плагин версии"
---

<style type="text/css">
    #home ul li {
        height: 160px;
    }
</style>

{{ content }}


text:
extern crate jsonrpc_core as core;
extern crate parking_lot;

#[macro_use]
extern crate log;

mod handler;
mod subscription;
mod types;

pub use self::handler::{PubSubHandler, SubscribeRpcMethod, UnsubscribeRpcMethod};
pub use self::subscription::{Session, Sink, Subscriber, new_subscription};
pub use self::types::{PubSubMetadata, SubscriptionId, TransportError, SinkResult};


text:
package ubc.pavlab.aspiredb.server.biomartquery;

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

import javax.annotation.PostConstruct;

import net.sf.ehcache.search.Attribute;
import net.sf.ehcache.search.expression.Criteria;

import org.apache.commons.lang.time.StopWatch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import ubc.pavlab.aspiredb.server.util.GenomeBin;
import ubc.pavlab.aspiredb.server.util.SearchableEhcache;
import ubc.pavlab.aspiredb.shared.GeneValueObject;

/**
 * BioMart cache imlementation
 *
 * @author frances
 * @version $Id: BioMartCacheImpl.java,v 1.8 2013/07/15 16:01:53 anton Exp $
 */
@Component
public class BioMartCacheImpl extends SearchableEhcache<GeneValueObject> implements BioMartCache {
    // These constants are used in ehcache.xml. If they are changed, ehcache.xml must be modified.
    private static final String CACHE_NAME = "BioMartCache";
    private static final String GENE_ENSEMBL_ID_SEARCH_ATTRIBUTE_NAME = "ensemblId";
    private static final String GENE_NAME_SEARCH_ATTRIBUTE_NAME = "name";
    private static final String GENE_SYMBOL_SEARCH_ATTRIBUTE_NAME = "symbol";
    private static final String CHROMOSOME_SEARCH_ATTRIBUTE_NAME = "genomicRangeChromosome";
    private static final String START_SEARCH_ATTRIBUTE_NAME = "genomicRangeStart";
    private static final String END_SEARCH_ATTRIBUTE_NAME = "genomicRangeEnd";
    private static final String BIN_SEARCH_ATTRIBUTE_NAME = "genomicRangeBin";

    private Attribute<Object> geneEnsemblIdAttribute;
    private Attribute<Object> geneNameAttribute;
    private Attribute<Object> geneSymbolAttribute;
    private Attribute<Object> chromosomeAttribute;
    private Attribute<Object> startAttribute;
    private Attribute<Object> endAttribute;
    private Attribute<Object> binAttribute;

    protected static Log log = LogFactory.getLog( BioMartCacheImpl.class );

    @Override
    public Collection<GeneValueObject> fetchGenesByGeneSymbols( Collection<String> geneSymbols ) {
        Criteria symbolCriteria = geneSymbolAttribute.in( geneSymbols );

        return fetchByCriteria( symbolCriteria );
    }

    @Override
    public Collection<GeneValueObject> fetchGenesByBin( int bin ) {

        Criteria eqBin = binAttribute.eq( bin );

        StopWatch timer = new StopWatch();
        timer.start();
        final Collection<GeneValueObject> geneValueObjects = fetchByCriteria( eqBin );
        log.info( "Fetching " + geneValueObjects.size() + " genes took " + timer.getTime() + " ms" );

        return geneValueObjects;
    }

    @Override
    public Collection<GeneValueObject> fetchGenesByLocation( String chromosomeName, Long start, Long end ) {
        Criteria chromosomeCriteria = chromosomeAttribute.eq( chromosomeName );
        Criteria insideVariant = startAttribute.between( start.intValue(), end.intValue() ).or(
                endAttribute.between( start.intValue(), end.intValue() ) );
        Criteria overlapsStart = startAttribute.le( start.intValue() ).and( endAttribute.ge( start.intValue() ) );
        Criteria overlapsEnd = startAttribute.le( end.intValue() ).and( endAttribute.ge( end.intValue() ) );
        Criteria inRelevantBins = binAttribute.in( GenomeBin.relevantBins( chromosomeName, start.intValue(),
                end.intValue() ) );

        Criteria hasName = geneSymbolAttribute.ne( "" );

        final Collection<GeneValueObject> geneValueObjects = fetchByCriteria( hasName.and( chromosomeCriteria
                .and( inRelevantBins.and( insideVariant.or( overlapsStart ).or( overlapsEnd ) ) ) ) );

        return geneValueObjects;
    }

    @Override
    public Collection<GeneValueObject> findGenes( String queryString ) {
        /*
         * String regexQueryString = "*" + queryString + "*";
         *
         * Criteria nameCriteria = geneNameAttribute.ilike( regexQueryString ); Criteria symbolCriteria =
         * geneSymbolAttribute.ilike( regexQueryString );
         */
        // return fetchByCriteria( nameCriteria.or( symbolCriteria ) );

        Collection<GeneValueObject> results = new ArrayList<>();

        // 1. Exact Gene Symbols
        String regexQueryString = queryString;
        Criteria symbolCriteria = geneSymbolAttribute.ilike( regexQueryString );
        results.addAll( fetchByCriteria( symbolCriteria ) );

        // 2. Prefix Gene Symbols
        regexQueryString = queryString + "*";
        symbolCriteria = geneSymbolAttribute.ilike( regexQueryString );
        Collection<GeneValueObject> tmp = fetchByCriteria( symbolCriteria );
        tmp.removeAll( results );
        results.addAll( tmp );

        // 3. Prefix Gene name
        Criteria nameCriteria = geneNameAttribute.ilike( regexQueryString );
        tmp = fetchByCriteria( nameCriteria );
        tmp.removeAll( results );
        results.addAll( tmp );

        return results;
    }

    @Override
    public String getCacheName() {
        return CACHE_NAME;
    }

    @Override
    public List<GeneValueObject> getGenes( List<String> geneStrings ) {
        List<GeneValueObject> genes = new ArrayList<GeneValueObject>( geneStrings.size() );

        for ( String geneString : geneStrings ) {
            Criteria symbolCriteria = geneSymbolAttribute.ilike( geneString );
            Criteria ensemblIdCriteria = geneEnsemblIdAttribute.ilike( geneString );
            Collection<GeneValueObject> fetchedGenes = fetchByCriteria( symbolCriteria.or( ensemblIdCriteria ) );
            if ( fetchedGenes.size() > 0 ) {
                // Only use the first gene.
                genes.add( fetchedGenes.iterator().next() );
            } else {
                genes.add( null );
            }
        }

        return genes;
    }

    @Override
    public Object getKey( GeneValueObject gene ) {
        return gene.getEnsemblId();
    }

    @SuppressWarnings("unused")
    @PostConstruct
    private void initialize() {
        geneEnsemblIdAttribute = getSearchAttribute( GENE_ENSEMBL_ID_SEARCH_ATTRIBUTE_NAME );
        geneNameAttribute = getSearchAttribute( GENE_NAME_SEARCH_ATTRIBUTE_NAME );
        geneSymbolAttribute = getSearchAttribute( GENE_SYMBOL_SEARCH_ATTRIBUTE_NAME );
        chromosomeAttribute = getSearchAttribute( CHROMOSOME_SEARCH_ATTRIBUTE_NAME );
        startAttribute = getSearchAttribute( START_SEARCH_ATTRIBUTE_NAME );
        endAttribute = getSearchAttribute( END_SEARCH_ATTRIBUTE_NAME );
        binAttribute = getSearchAttribute( BIN_SEARCH_ATTRIBUTE_NAME );
    }
}


text:
////////////////////////////////////////////////////////////////////////////////
//
// Public thread module include file for using threads in other modules
//
///////////////////////////////////////////////////////////////////////////////

#if !defined(__SP_THREADS_H)
#define __SP_THREADS_H

#include <pthread.h>

#include "basics/callback.h"
#include "threads/pcqueue.h"

#endif  // __SP_THREADS_H


text:
package com.facebook.buck.apple;

import com.facebook.buck.util.ProcessExecutor;
import com.facebook.buck.util.ProcessExecutorParams;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.nio.file.Path;
import java.util.EnumSet;
import java.util.Optional;
import java.util.Set;

/** Utility class for code signing. */
public class CodeSigning {
  // Utility class, do not instantiate.
  private CodeSigning() {}

  /**
   * Checks whether a binary or bundle already has a valid code signature.
   *
   * @param path Resolved path to the binary or bundle.
   * @return Whether the binary or bundle has a valid code signature.
   */
  public static boolean hasValidSignature(ProcessExecutor processExecutor, Path path)
      throws InterruptedException, IOException {
    ProcessExecutorParams processExecutorParams =
        ProcessExecutorParams.builder()
            .setCommand(ImmutableList.of("codesign", "--verify", "-v", path.toString()))
            .build();

    // Specify that stdout is expected, or else output may be wrapped in Ansi escape chars.
    Set<ProcessExecutor.Option> options =
        EnumSet.of(ProcessExecutor.Option.EXPECTING_STD_OUT, ProcessExecutor.Option.IS_SILENT);

    ProcessExecutor.Result result =
        processExecutor.launchAndExecute(
            processExecutorParams,
            options,
            /* stdin */ Optional.empty(),
            /* timeOutMs */ Optional.empty(),
            /* timeOutHandler */ Optional.empty());

    return result.getExitCode() == 0
        && result.getStderr().isPresent()
        && result.getStderr().get().contains(": satisfies its Designated Requirement");
  }

  /**
   * Checks whether a binary or bundle contains specific entitlement.
   *
   * @param path Resolved path to the binary or bundle.
   * @param entitlementKey Entitlement key to check.
   * @return Whether the binary or bundle contains the entitlement.
   */
  public static boolean hasEntitlement(
      ProcessExecutor processExecutor, Path path, String entitlementKey)
      throws InterruptedException, IOException {
    ProcessExecutorParams processExecutorParams =
        ProcessExecutorParams.builder()
            .setCommand(ImmutableList.of("codesign", "-d", "--entitlements", ":-", path.toString()))
            .build();

    // Specify that stdout is expected, or else output may be wrapped in Ansi escape chars.
    Set<ProcessExecutor.Option> options =
        EnumSet.of(ProcessExecutor.Option.EXPECTING_STD_OUT, ProcessExecutor.Option.IS_SILENT);

    ProcessExecutor.Result result =
        processExecutor.launchAndExecute(
            processExecutorParams,
            options,
            /* stdin */ Optional.empty(),
            /* timeOutMs */ Optional.empty(),
            /* timeOutHandler */ Optional.empty());

    return result.getExitCode() == 0
        && result.getStdout().isPresent()
        && result.getStdout().get().contains(entitlementKey);
  }
}


text:
Recursively scans the keyspace of a Redis 2.8+ instance using SCAN, HSCAN, ZSCAN, & SSCAN as well as Lists.

Fairly safe in a production environment as it does **NOT** use KEYS * to iterate.

Optionally pass a redis pattern to filter from.

## Install
`npm install redisscan`

## Example

```javascript
var redisScan = require('redisscan');
var redis     = require('redis').createClient();

redisScan({
    redis: redis,
    pattern: 'awesome:key:prefix:*',
    keys_only: false,
    each_callback: function (type, key, subkey, length, value, cb) {
        console.log(type, key, subkey, length, value);
        cb();
    },
    done_callback: function (err) {
        console.log("-=-=-=-=-=--=-=-=-");
        redis.quit();
    }
});
```

### redisScan(parameters):

* `redis`: **required** `node-redis` client instance
* `pattern`: **optional** wildcard key pattern to match, e.g: `some:key:pattern:*` [docs](https://redis.io/commands/scan#the-match-option)
* `keys_only`: **optional** boolean -- returns nothing but keys, no types,lengths,values etc. (defaults to `false`)
* `count_amt`: **optional** positive/non-zero integer -- redis hint for work done per SCAN operation (defaults to 10) [docs](https://redis.io/commands/scan#the-count-option)
* `each_callback`: **required** `function (type, key, subkey, length, value, next)`  This is called for every string, and every subkey/value in a container when not using `keys_only`, so outer keys may show up multiple times.
    * `type` may be `"string"`, `"hash"`, `"set"`, `"zset"`, `"list"`
    * `key` is the redis key
    * `subkey` may be `null` or populated with a hash key
    * `length` is the length of a set or list
    * `value` is the value of the key or subkey when appropriate
    * `next()` should be called as a function with no arguments if successful or an `Error` object if not.
* `done_callback`: **optional** function called when scanning completes with one argument, and `Error` object if an error ws raised

## Note/Warning

If values are changing, there is no guarantee on value integrity. This is not atomic.
I recommend using a lock pattern with this function.

License MIT (c) 2014 Nathanael C. Fritz


text:
'use strict'

const fs = require('mz/fs')
const path = require('path')
const os = require('os')
const pidusage = require('pidusage')
const handlebars = require('handlebars')
let io
let appName
try {
  appName = require('../../package.json').name
} catch (err) {}

const defaultConfig = {
  path: '/status',
  title: appName,
  spans: [
    {
      interval: 1,
      retention: 60
    },
    {
      interval: 5,
      retention: 60
    },
    {
      interval: 15,
      retention: 60
    }
  ]
}

const last = function(arr) {
  return arr[arr.length - 1]
}

const gatherOsMetrics = (io, span) => {
  const defaultResponse = {
    '2': 0,
    '3': 0,
    '4': 0,
    '5': 0,
    count: 0,
    mean: 0,
    timestamp: Date.now()
  }

  const sendMetrics = (span) => {
    io.emit('stats', {
      os: span.os[span.os.length - 2],
      responses: span.responses[span.responses.length - 2],
      interval: span.interval,
      retention: span.retention
    })
  }

  pidusage(process.pid, (err, stat) => {
    if (err) {
      console.error(err)
      return
    }
    stat.memory = stat.memory / 1024 / 1024 // Convert from B to MB
    stat.load = os.loadavg()
    stat.timestamp = Date.now()

    span.os.push(stat)
    if (
      !span.responses[0] ||
      last(span.responses).timestamp + span.interval * 1000 < Date.now()
    )
      span.responses.push(defaultResponse)

    if (span.os.length >= span.retention) span.os.shift()
    if (span.responses[0] && span.responses.length > span.retention)
      span.responses.shift()

    sendMetrics(span)
  })
}

const encoding = { encoding: 'utf8' }

const middlewareWrapper = (app, config) => {
  if (!app.listen) {
    throw new Error('First parameter must be an http server')
  }
  io = require('socket.io')(app)
  Object.assign(defaultConfig, config)
  config = defaultConfig
  const htmlFilePath = path.join(__dirname, 'index.html')
  const indexHtml = fs.readFileSync(htmlFilePath, encoding)
  const template = handlebars.compile(indexHtml)

  io.on('connection', (socket) => {
    socket.emit('start', config.spans)
    socket.on('change', function() {
      socket.emit('start', config.spans)
    })
  })

  config.spans.forEach((span) => {
    span.os = []
    span.responses = []
    const interval = setInterval(
      () => gatherOsMetrics(io, span),
      span.interval * 1000
    )
    interval.unref()
  })
  // console.log(config)

  return async (ctx, next) => {
    const startTime = process.hrtime()

    if (ctx.path === config.path) {
      ctx.body = template(config)
    } else if (ctx.url === `${config.path}/koa-monitor-frontend.js`) {
      const pathToJs = path.join(__dirname, 'koa-monitor-frontend.js')
      ctx.body = await fs.readFile(pathToJs, encoding)
    } else {
      let timer
      if (config.requestTimeout) {
        timer = setTimeout(() => {
          record.call(ctx, true)
        }, config.requestTimeout)
      }

      await next

      timer && clearTimeout(timer)
      record.call(ctx)
    }

    function record(timeout) {
      const diff = process.hrtime(startTime)
      const responseTime = diff[0] * 1e3 + diff[1] * 1e-6
      // if timeout, set response code to 5xx.
      const category = timeout ? 5 : Math.floor(ctx.statusCode / 100)

      config.spans.forEach((span) => {
        const lastResponse = last(span.responses)
        if (
          lastResponse &&
          lastResponse.timestamp / 1000 + span.interval > Date.now() / 1000
        ) {
          lastResponse[category]++
          lastResponse.count++
          lastResponse.mean =
            lastResponse.mean +
            (responseTime - lastResponse.mean) / lastResponse.count
        } else {
          span.responses.push({
            '2': category === 2 ? 1 : 0,
            '3': category === 3 ? 1 : 0,
            '4': category === 4 ? 1 : 0,
            '5': category === 5 ? 1 : 0,
            count: 1,
            mean: responseTime,
            timestamp: Date.now()
          })
        }
      })
    }
  }
}

module.exports = middlewareWrapper


text:
$:.unshift "../lib"
require 'eventmachine'
require 'test/unit'

class TestDeferUsage < Test::Unit::TestCase

  def test_defers
    n = 0
    n_times = 20
    EM.run {
      n_times.times {
        work_proc = proc { n += 1 }
        callback = proc { EM.stop if n == n_times }
        EM.defer work_proc, callback
      }
    }
    assert_equal( n, n_times )
  end unless RUBY_VERSION >= '1.9.0'

end


text:
import parser from 'cheerio-without-node-native'

export default function (html) {

  const $ = parser.load(html)
  const result = []

  $('ul.list li').each(function (i, elem) {
    const $this = $(this)
    const img = $this.find('img').attr('src')
    const thumbs = Array.from($this.find('img').map(function (i, elem) {
      return $(this).attr('src')
    }).filter(index => !!index))

    const text = $this.text()
    const arr = text.split('\n').map(item => item.replace(/\t/g, '').trim()).filter(item => item)

    const target = $this.find('.content')
    if (!target) return
    if (!target.length) return
    const matched = target[0].parent.attribs.href.match(/\d+/)
    const id = matched ? matched[0] : arr[1] + arr[2]
    const nextArr = arr.slice(-3)
    let circle = $this.find('a.node').text() || ''
    let base = 1
    if (!circle) base = 0
    const mock = {
      circle,
      content: arr.slice(base, -3).join('\n'),
      psnid: nextArr[0],
      date: nextArr[1],
      avatar: img,
      id,
      thumbs,
      count: nextArr[2],
      type: nextArr[2],
      circleHref: ($this.find('a.node').attr('href') || '').trim()
    }
    result.push(mock)
  })
  return result
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Statistics of compound:prt in UD_English-GUM</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_English-GUM: Relations: compound:prt

This relation is a language-specific subtype of <tt>compound</tt>.

640 nodes (0%) are attached to their parents as compound:prt.

640 instances of compound:prt (100%) are left-to-right (parent precedes child).
Average distance between parent and child is 1.265625.

The following 3 pairs of parts of speech are connected with compound:prt: <tt>VERB</tt>-<tt>ADP</tt> (630; 98% instances), <tt>NOUN</tt>-<tt>ADP</tt> (9; 1% instances), <tt>PROPN</tt>-<tt>ADP</tt> (1; 0% instances).

# visual-style 14	bgColor:blue
# visual-style 14	fgColor:white
# visual-style 12	bgColor:blue
# visual-style 12	fgColor:white
# visual-style 12 14 compound:prt	color:blue
1	Next	next	ADJ	JJ	Degree=Pos	2	amod	2:amod	Discourse=joint-other_m:115->109:3|Entity=(50-time-new-cf4-2-sgl
2	time	time	NOUN	NN	Number=Sing	12	obl:tmod	12:obl:tmod	Entity=50)
3	if	if	SCONJ	IN	_	5	mark	5:mark	Discourse=contingency-condition:116->117:0
4	I	I	PRON	PRP	Case=Nom|Number=Sing|Person=1|PronType=Prs	5	nsubj	5:nsubj	Entity=(4-person-giv:inact-cf1-1-ana)
5	leave	leave	VERB	VBP	Mood=Ind|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin	12	advcl	12:advcl:if	_
6	in	in	ADP	IN	_	8	case	8:case	_
7	the	the	DET	DT	Definite=Def|PronType=Art	8	det	8:det	Entity=(51-time-new-cf3-2-sgl
8	morning	morning	NOUN	NN	Number=Sing	5	obl	5:obl:in	Entity=51)|SpaceAfter=No
9	,	,	PUNCT	,	_	5	punct	5:punct	_
10	I	I	PRON	PRP	Case=Nom|Number=Sing|Person=1|PronType=Prs	12	nsubj	12:nsubj	Discourse=same-unit_m:117->115:0|Entity=(4-person-giv:act-cf1-1-ana)
11	'll	will	AUX	MD	VerbForm=Fin	12	aux	12:aux	_
12	wake	wake	VERB	VB	VerbForm=Inf	0	root	0:root	_
13	you	you	PRON	PRP	Case=Acc|Number=Sing|Person=2|PronType=Prs	12	obj	12:obj	Entity=(10-person-giv:inact-cf2-1-ana)
14	up	up	ADP	RP	_	12	compound:prt	12:compound:prt	SpaceAfter=No
15	.	.	PUNCT	.	_	12	punct	12:punct	_

# visual-style 15	bgColor:blue
# visual-style 15	fgColor:white
# visual-style 14	bgColor:blue
# visual-style 14	fgColor:white
# visual-style 14 15 compound:prt	color:blue
1	And	and	CCONJ	CC	_	8	cc	8:cc	Discourse=joint-other_m:171->163:2
2	if	if	SCONJ	IN	_	4	mark	4:mark	Discourse=contingency-condition:172->173:0
3	you	you	PRON	PRP	Case=Nom|Number=Sing|Person=2|PronType=Prs	4	nsubj	4:nsubj	Entity=(9-person-giv:inact-cf1-1-ana)
4	have	have	VERB	VBP	Mood=Ind|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin	8	advcl	8:advcl:if	_
5	n't	not	PART	RB	Polarity=Neg	4	advmod	4:advmod	_
6	already	already	ADV	RB	_	4	advmod	4:advmod	_
7	be	be	AUX	VB	Mood=Imp|Person=2|VerbForm=Fin	8	cop	8:cop	Discourse=same-unit_m:173->171:0
8	sure	sure	ADJ	JJ	Degree=Pos	0	root	0:root	_
9	to	to	PART	TO	_	10	mark	10:mark	_
10	give	give	VERB	VB	VerbForm=Inf	8	xcomp	8:xcomp	_
11	this	this	DET	DT	Number=Sing|PronType=Dem	12	det	12:det	Entity=(110-abstract-acc:com-cf2-2-sgl
12	video	video	NOUN	NN	Number=Sing	10	iobj	10:iobj	Entity=110)
13	a	a	DET	DT	Definite=Ind|PronType=Art	14	det	14:det	Entity=(111-abstract-new-cf3-2-sgl
14	thumbs	thumb	NOUN	NN	Number=Sing	10	obj	10:obj	_
15	up	up	ADP	RP	_	14	compound:prt	14:compound:prt	Entity=111)|SpaceAfter=No
16	.	.	PUNCT	.	_	8	punct	8:punct	_

# visual-style 46	bgColor:blue
# visual-style 46	fgColor:white
# visual-style 45	bgColor:blue
# visual-style 45	fgColor:white
# visual-style 45 46 compound:prt	color:blue
1	Her	her	PRON	PRP$	Case=Gen|Gender=Fem|Number=Sing|Person=3|Poss=Yes|PronType=Prs	2	nmod:poss	2:nmod:poss	Discourse=causal-result:86->85:0|Entity=(93-abstract-new-cf5-2-coref(1-person-giv:inact-cf1-1-ana-Ichiyō_Higuchi)
2	experience	experience	NOUN	NN	Number=Sing	8	nsubj	8:nsubj	_
3	living	live	VERB	VBG	VerbForm=Ger	2	acl	2:acl	Discourse=elaboration-attribute:87->86:0
4	in	in	ADP	IN	_	6	case	6:case	_
5	this	this	DET	DT	Number=Sing|PronType=Dem	6	det	6:det	Entity=(86-place-giv:inact-cf3-2-coref
6	neighborhood	neighborhood	NOUN	NN	Number=Sing	3	obl	3:obl:in	Entity=86)93)
7	would	would	AUX	MD	Number=Sing|Person=3|VerbForm=Fin	8	aux	8:aux	Discourse=same-unit_m:88->86:1
8	provide	provide	VERB	VB	VerbForm=Inf	0	root	0:root	_
9	material	material	NOUN	NN	Number=Sing	8	obj	8:obj	Entity=(94-abstract-new-cf9-3-sgl
10	for	for	ADP	IN	_	11	case	11:case	_
11	several	several	ADJ	JJ	Degree=Pos	8	obl	8:obl:for	Entity=(95-abstract-new-cf10-1-sgl
12	of	of	ADP	IN	_	15	case	15:case	_
13	her	her	PRON	PRP$	Case=Gen|Gender=Fem|Number=Sing|Person=3|Poss=Yes|PronType=Prs	15	nmod:poss	15:nmod:poss	Bridge=17<96|Entity=(96-abstract-acc:inf-cf4-3-coref(1-person-giv:act-cf1-1-ana-Ichiyō_Higuchi)
14	later	late	ADJ	JJR	Degree=Cmp	15	amod	15:amod	_
15	stories	story	NOUN	NNS	Number=Plur	11	obl	11:obl:of	Entity=96)95)94)|SpaceAfter=No
16	,	,	PUNCT	,	_	19	punct	19:punct	_
17	especially	especially	ADV	RB	Degree=Pos	19	advmod	19:advmod	_
18	"	''	PUNCT	``	_	19	punct	19:punct	SpaceAfter=No
19	Takekurabe	Takekurabe	PROPN	NNP	Number=Sing	15	appos	15:appos	Bridge=17<97|Entity=(97-abstract-acc:inf-cf2-1-coref-Takekurabe)|SpaceAfter=No
20	"	''	PUNCT	''	_	19	punct	19:punct	SpaceAfter=No
21	,	,	PUNCT	,	_	19	punct	19:punct	_
22	(	(	PUNCT	-LRB-	_	26	punct	26:punct	Discourse=elaboration-additional:89->88:0|SpaceAfter=No
23	literally	literally	ADV	RB	Degree=Pos	26	advmod	26:advmod	SpaceAfter=No
24	,	,	PUNCT	,	_	23	punct	23:punct	SpaceAfter=No
25	"	''	PUNCT	''	_	26	punct	26:punct	_
26	Comparing	Comparing	PROPN	NNP	Number=Sing	15	appos	15:appos	Entity=(97-abstract-giv:act-cf2-1,2-coref-Takekurabe
27	heights	height	PROPN	NNPS	Number=Plur	26	obj	26:obj	Entity=(98-abstract-new-cf6-1-sgl-Takekurabe)97)|SpaceAfter=No
28	"	''	PUNCT	''	_	26	punct	26:punct	SpaceAfter=No
29	;	;	PUNCT	:	_	26	punct	26:punct	_
30	"	''	PUNCT	``	_	33	punct	33:punct	SpaceAfter=No
31	Child	Child	PROPN	NNP	Number=Sing	33	nmod:poss	33:nmod:poss	Entity=(97-abstract-giv:act-cf2-3-coref-Takekurabe
32	's	's	PART	POS	_	31	case	31:case	_
33	Play	Play	PROPN	NNP	Number=Sing	19	parataxis	19:parataxis	Entity=97)|SpaceAfter=No
34	"	''	PUNCT	''	_	33	punct	33:punct	_
35	in	in	ADP	IN	_	40	case	40:case	_
36	the	the	DET	DT	Definite=Def|PronType=Art	40	det	40:det	Entity=(99-abstract-new-cf7-3,4,5-sgl
37	Robert	Robert	PROPN	NNP	Number=Sing	40	compound	40:compound	Entity=(100-person-new-cf11-1,2,3-sgl-Robert_Lyons_Danly
38	Lyons	Lyons	PROPN	NNP	Number=Sing	37	flat	37:flat	_
39	Danly	Danly	PROPN	NNP	Number=Sing	37	flat	37:flat	Entity=100)
40	translation	translation	NOUN	NN	Number=Sing	33	nmod	33:nmod:in	Entity=99)|SpaceAfter=No
41	;	;	PUNCT	:	_	33	punct	33:punct	_
42	also	also	ADV	RB	_	43	advmod	43:advmod	Discourse=joint-list_m:90->89:0
43	called	call	VERB	VBN	Tense=Past|VerbForm=Part	19	acl	19:acl	_
44	"	''	PUNCT	``	_	45	punct	45:punct	SpaceAfter=No
45	Growing	Growing	PROPN	NNP	Number=Sing	43	xcomp	43:xcomp	Entity=(97-abstract-giv:act-cf2-1-coref-Takekurabe
46	Up	up	ADP	RP	_	45	compound:prt	45:compound:prt	Entity=97)|SpaceAfter=No
47	"	''	PUNCT	''	_	45	punct	45:punct	_
48	in	in	ADP	IN	_	52	case	52:case	_
49	the	the	DET	DT	Definite=Def|PronType=Art	52	det	52:det	Entity=(101-abstract-new-cf8-3,4-sgl
50	Edward	Edward	PROPN	NNP	Number=Sing	52	compound	52:compound	Entity=(102-person-new-cf12-1,2-sgl-Edward_Seidensticker
51	Seidensticker	Seidensticker	PROPN	NNP	Number=Sing	50	flat	50:flat	Entity=102)
52	translation	translation	NOUN	NN	Number=Sing	45	obl	45:obl:in	Entity=101)|SpaceAfter=No
53	.	.	PUNCT	.	_	43	punct	43:punct	SpaceAfter=No
54	)	)	PUNCT	-RRB-	_	43	punct	43:punct	_

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
package alluxio.shell.command;

import alluxio.client.FileSystemTestUtils;
import alluxio.client.WriteType;
import alluxio.exception.ExceptionMessage;
import alluxio.shell.AbstractAlluxioShellTest;

import alluxio.util.io.BufferUtils;

import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;

/**
 * Tests checksum command.
 */
public final class ChecksumCommandTest  extends AbstractAlluxioShellTest {

  /**
   * Tests md5 checksum calculation.
   */
  @Test
  public void checksum() throws IOException {
    FileSystemTestUtils.createByteFile(mFileSystem, "/testFile", WriteType.MUST_CACHE, 10);
    mFsShell.run("checksum", "/testFile");
    String str = mOutput.toString();
    String[] splitString = str.split("\\s+");

    byte[] data = BufferUtils.getIncreasingByteArray(10);
    try {
      String expectedMd5 = DigestUtils.md5Hex(data);
      Assert.assertEquals(splitString[1], expectedMd5);
    } catch (Exception e) {
      Assert.fail("md5cksum failure not expected: " + e.getMessage());
    }
  }

  /**
   * Test invalid args.
   */
  @Test
  public void checksumInvalidArgs() throws IOException {
    mFsShell.run("checksum", "/testFile");
    String expected = ExceptionMessage.PATH_DOES_NOT_EXIST.getMessage("/testFile") + "\n";
    Assert.assertEquals(expected, mOutput.toString());

    mFsShell.run("mkdir", "/testFolder");
    int ret = mFsShell.run("checksum", "/testFolder");
    Assert.assertEquals(-1, ret);
  }
}


text:
package com.evolveum.midpoint.prism.impl;

import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.impl.item.DummyContainerImpl;
import com.evolveum.midpoint.prism.impl.item.DummyPropertyImpl;
import com.evolveum.midpoint.prism.impl.item.DummyReferenceImpl;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.xnode.XNode;
import com.evolveum.midpoint.util.exception.SchemaException;

import org.jetbrains.annotations.NotNull;

import javax.xml.namespace.QName;

/**
 *
 */
public class ItemFactoryImpl implements ItemFactory {

    @NotNull private final PrismContextImpl prismContext;

    public ItemFactoryImpl(PrismContextImpl prismContext) {
        this.prismContext = prismContext;
    }

    @Override
    public <T> PrismProperty<T> createProperty(QName itemName) {
        return new PrismPropertyImpl<>(itemName, prismContext);
    }

    @Override
    public <T> PrismProperty<T> createProperty(QName itemName, PrismPropertyDefinition<T> definition) {
        return new PrismPropertyImpl<>(itemName, definition, prismContext);
    }

    @Override
    public <T> PrismPropertyValue<T> createPropertyValue() {
        return new PrismPropertyValueImpl<>(null, prismContext);
    }

    @Override
    public <T> PrismPropertyValue<T> createPropertyValue(T realValue) {
        return new PrismPropertyValueImpl<>(realValue, prismContext);
    }

    @Override
    public <T> PrismPropertyValue<T> createPropertyValue(XNode rawValue) {
        PrismPropertyValueImpl<T> rv = new PrismPropertyValueImpl<>(null, prismContext);
        rv.setRawElement(rawValue);
        return rv;
    }

    @Override
    public <T> PrismPropertyValue<T> createPropertyValue(T value, OriginType originType, Objectable originObject) {
        return new PrismPropertyValueImpl<>(value, prismContext, originType, originObject, null);
    }

    @Override
    public PrismReference createReference(QName name) {
        return new PrismReferenceImpl(name, null, prismContext);
    }

    @Override
    public PrismReference createReference(QName name, PrismReferenceDefinition definition) {
        return new PrismReferenceImpl(name, definition, prismContext);
    }

    @Override
    public PrismReferenceValue createReferenceValue() {
        return new PrismReferenceValueImpl(null);
    }

    @Override
    public PrismReferenceValue createReferenceValue(PrismObject<?> target) {
        PrismReferenceValue rv = new PrismReferenceValueImpl(target.getOid());
        rv.setPrismContext(prismContext);
        rv.setObject(target);
        if (target.getDefinition() != null) {
            rv.setTargetType(target.getDefinition().getTypeName());
        }
        return rv;
    }

    @Override
    public PrismReferenceValue createReferenceValue(String targetOid) {
        PrismReferenceValue rv = new PrismReferenceValueImpl(targetOid);
        rv.setPrismContext(prismContext);
        return rv;
    }

    @Override
    public PrismReferenceValue createReferenceValue(String oid, OriginType originType, Objectable originObject) {
        PrismReferenceValue rv = new PrismReferenceValueImpl(oid, originType, originObject);
        rv.setPrismContext(prismContext);
        return rv;
    }

    @Override
    public PrismReferenceValue createReferenceValue(String oid, QName targetType) {
        PrismReferenceValue rv = new PrismReferenceValueImpl(oid, targetType);
        rv.setPrismContext(prismContext);
        return rv;
    }

    @Override
    public PrismValue createValue(Object realValue) {
        if (realValue instanceof Containerable) {
            return ((Containerable) realValue).asPrismContainerValue();
        } else if (realValue instanceof Referencable) {
            return ((Referencable) realValue).asReferenceValue();
        } else {
            return createPropertyValue(realValue);
        }
    }

    @Override
    public PrismContainer createContainer(QName name) {
        return new PrismContainerImpl(name, prismContext);
    }

    @Override
    public <C extends Containerable> PrismContainer<C> createContainer(QName name, PrismContainerDefinition<C> definition) {
        return new PrismContainerImpl<>(name, definition, prismContext);
    }

    @Override
    public <O extends Objectable> PrismObject<O> createObject(QName name, PrismObjectDefinition<O> definition) {
        return new PrismObjectImpl<>(name, definition, prismContext);
    }

    @Override
    public <O extends Objectable> PrismObjectValue<O> createObjectValue(O objectable) {
        return new PrismObjectValueImpl<>(objectable, prismContext);
    }

    @Override
    public <C extends Containerable> PrismContainerValue<C> createContainerValue(C containerable) {
        return new PrismContainerValueImpl<>(containerable, prismContext);
    }

    @Override
    public <C extends Containerable> PrismContainerValue<C> createContainerValue() {
        return new PrismContainerValueImpl<>(prismContext);
    }

    @Override
    public <V extends PrismValue,D extends ItemDefinition> Item<V,D> createDummyItem(Item<V,D> itemOld, D definition, ItemPath path) throws SchemaException {
        Item<V,D> itemMid;
        if (itemOld == null) {
            itemMid = definition.instantiate();
        } else {
            itemMid = itemOld.clone();
        }
        if (itemMid instanceof PrismProperty<?>) {
            return (Item<V,D>) new DummyPropertyImpl<>((PrismProperty<?>)itemMid, path);
        } else if (itemMid instanceof PrismReference) {
            return (Item<V,D>) new DummyReferenceImpl((PrismReference)itemMid, path);
        } else if (itemMid instanceof PrismContainer<?>) {
            return (Item<V,D>) new DummyContainerImpl<>((PrismContainer<?>)itemMid, path);
        } else {
            throw new IllegalStateException("Unknown type "+itemMid.getClass());
        }
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE369_Divide_by_Zero__float_rand_53b.c
Label Definition File: CWE369_Divide_by_Zero__float.label.xml
Template File: sources-sinks-53b.tmpl.c
*/
/*
 * @description
 * CWE: 369 Divide by Zero
 * BadSource: rand Set data to result of RAND32(), which may be zero
 * GoodSource: A hardcoded non-zero number (two)
 * Sinks:
 *    GoodSink: Check value of or near zero before dividing
 *    BadSink : Divide a constant by data
 * Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
 *
 * */

#include "std_testcase.h"

#include <math.h>

#ifndef OMITBAD

/* bad function declaration */
void CWE369_Divide_by_Zero__float_rand_53c_badSink(float data);

void CWE369_Divide_by_Zero__float_rand_53b_badSink(float data)
{
    CWE369_Divide_by_Zero__float_rand_53c_badSink(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE369_Divide_by_Zero__float_rand_53c_goodG2BSink(float data);

void CWE369_Divide_by_Zero__float_rand_53b_goodG2BSink(float data)
{
    CWE369_Divide_by_Zero__float_rand_53c_goodG2BSink(data);
}

/* goodB2G uses the BadSource with the GoodSink */
void CWE369_Divide_by_Zero__float_rand_53c_goodB2GSink(float data);

void CWE369_Divide_by_Zero__float_rand_53b_goodB2GSink(float data)
{
    CWE369_Divide_by_Zero__float_rand_53c_goodB2GSink(data);
}

#endif /* OMITGOOD */


text:
package br.com.yanaga.samples.academico.infrastructure.jpa;

import br.com.yanaga.samples.academico.domain.Sigla;

import javax.persistence.AttributeConverter;

public class SiglaAttributeConverter implements AttributeConverter<Sigla, String> {
	@Override
	public String convertToDatabaseColumn(Sigla attribute) {
		if (attribute != null) {
			return attribute.toString();
		}
		return null;
	}

	@Override
	public Sigla convertToEntityAttribute(String dbData) {
		if (dbData != null) {
			return Sigla.of(dbData);
		}
		return null;
	}
}


text:
/**
 * limitation(s) placed upon the access or use of the data
 */
export type Restriction =
    /**
     * exclusive right to the publication, production, or sale of the rights to a
     * literary, dramatic, musical, or artistic work, or to the use of a
     * commercial print or label, granted by law for a specified period of time to
     * an author, composer, artist, distributor
     */
    'copyright' |
    /**
     * government has granted exclusive right to make, sell, use or license an
     * invention or discovery
     */
    'patent' |
    /**
     * produced or sold information awaiting a patent
     */
    'patentPending' |
    /**
     * a name, symbol, or other device identifying a product, officially
     * registered and legally restricted to the use of the owner or manufacturer
     */
    'trademark' |
    /**
     * formal permission to do something
     */
    'license' |
    /**
     * rights to financial benefit from and control of distribution of
     * non-tangible property that is a result of creativity
     */
    'intellectualPropertyRights' |
    /**
     * withheld from general circulation or disclosure
     */
    'restricted' |
    /**
     * limitation not listed
     */
    'otherRestrictions';