text:
import itertools
import os
import re
import pandas as pd

from trappy.bare_trace import BareTrace
from trappy.utils import listify

def _plot_freq_hists(allfreqs, what, axis, title):
    """Helper function for plot_freq_hists

    allfreqs is the output of a Cpu*Power().get_all_freqs() (for
    example, CpuInPower.get_all_freqs()).  what is a string: "in" or
    "out"

    """
    import trappy.plot_utils

    for ax, actor in zip(axis, allfreqs):
        this_title = "freq {} {}".format(what, actor)
        this_title = trappy.plot_utils.normalize_title(this_title, title)
        xlim = (0, allfreqs[actor].max())

        trappy.plot_utils.plot_hist(allfreqs[actor], ax, this_title, "KHz", 20,
                             "Frequency", xlim, "default")

class GenericFTrace(BareTrace):
    """Generic class to parse output of FTrace.  This class is meant to be
subclassed by FTrace (for parsing FTrace coming from trace-cmd) and SysTrace."""

    thermal_classes = {}

    sched_classes = {}

    dynamic_classes = {}

    def __init__(self, name="", normalize_time=True, scope="all",
                 events=[], window=(0, None), abs_window=(0, None)):
        super(GenericFTrace, self).__init__(name)

        if not hasattr(self, "needs_raw_parsing"):
            self.needs_raw_parsing = False

        self.class_definitions.update(self.dynamic_classes.items())
        self.__add_events(listify(events))

        if scope == "thermal":
            self.class_definitions.update(self.thermal_classes.items())
        elif scope == "sched":
            self.class_definitions.update(self.sched_classes.items())
        elif scope != "custom":
            self.class_definitions.update(self.thermal_classes.items() +
                                          self.sched_classes.items())

        for attr, class_def in self.class_definitions.iteritems():
            trace_class = class_def()
            setattr(self, attr, trace_class)
            self.trace_classes.append(trace_class)

        self.__parse_trace_file(self.trace_path, window, abs_window)
        if self.needs_raw_parsing and (self.trace_path_raw is not None):
            self.__parse_trace_file(self.trace_path_raw, window, abs_window,
                                    raw=True)
        self.finalize_objects()

        if normalize_time:
            self.normalize_time()

    @classmethod
    def register_parser(cls, cobject, scope):
        """Register the class as an Event. This function
        can be used to register a class which is associated
        with an FTrace unique word.

        .. seealso::

            :mod:`trappy.dynamic.register_dynamic_ftrace` :mod:`trappy.dynamic.register_ftrace_parser`

        """

        if not hasattr(cobject, "name"):
            cobject.name = cobject.unique_word.split(":")[0]

        # Add the class to the classes dictionary
        if scope == "all":
            cls.dynamic_classes[cobject.name] = cobject
        else:
            getattr(cls, scope + "_classes")[cobject.name] = cobject

    @classmethod
    def unregister_parser(cls, cobject):
        """Unregister a parser

        This is the opposite of FTrace.register_parser(), it removes a class
        from the list of classes that will be parsed on the trace

        """

        # TODO: scopes should not be hardcoded (nor here nor in the FTrace object)
        all_scopes = [cls.thermal_classes, cls.sched_classes,
                      cls.dynamic_classes]
        known_events = ((n, c, sc) for sc in all_scopes for n, c in sc.items())

        for name, obj, scope_classes in known_events:
            if cobject == obj:
                del scope_classes[name]

    def __add_events(self, events):
        """Add events to the class_definitions

        If the events are known to trappy just add that class to the
        class definitions list.  Otherwise, register a class to parse
        that event

        """

        from trappy.dynamic import DynamicTypeFactory, default_init
        from trappy.base import Base

        # TODO: scopes should not be hardcoded (nor here nor in the FTrace object)
        all_scopes = [self.thermal_classes, self.sched_classes,
                      self.dynamic_classes]
        known_events = {k: v for sc in all_scopes for k, v in sc.iteritems()}

        for event_name in events:
            for cls in known_events.itervalues():
                if (event_name == cls.unique_word) or \
                   (event_name + ":" == cls.unique_word):
                    self.class_definitions[event_name] = cls
                    break
            else:
                kwords = {
                    "__init__": default_init,
                    "unique_word": event_name + ":",
                    "name": event_name,
                }
                trace_class = DynamicTypeFactory(event_name, (Base,), kwords)
                self.class_definitions[event_name] = trace_class

    def __populate_data(self, fin, cls_for_unique_word, window, abs_window):
        """Append to trace data from a txt trace"""

        def contains_unique_word(line, unique_words=cls_for_unique_word.keys()):
            for unique_word in unique_words:
                if unique_word in line:
                    return True
            return False

        special_fields_regexp = r"^\s*(?P<comm>.*)-(?P<pid>\d+)(?:\s+\(.*\))"\
                                r"?\s+\[(?P<cpu>\d+)\](?:\s+....)?\s+"\
                                r"(?P<timestamp>[0-9]+\.[0-9]+):"
        special_fields_regexp = re.compile(special_fields_regexp)
        start_match = re.compile(r"[A-Za-z0-9_]+=")

        actual_trace = itertools.dropwhile(self.trace_hasnt_started(), fin)
        actual_trace = itertools.takewhile(self.trace_hasnt_finished(),
                                           actual_trace)

        for line in itertools.ifilter(contains_unique_word, actual_trace):
            for unique_word, cls in cls_for_unique_word.iteritems():
                if unique_word in line:
                    trace_class = cls
                    break
            else:
                raise ValueError("No unique in {}".format(line))

            line = line[:-1]

            special_fields_match = special_fields_regexp.match(line)
            comm = special_fields_match.group('comm')
            pid = int(special_fields_match.group('pid'))
            cpu = int(special_fields_match.group('cpu'))
            timestamp = float(special_fields_match.group('timestamp'))

            if not self.basetime:
                self.basetime = timestamp

            if (timestamp < window[0] + self.basetime) or \
               (timestamp < abs_window[0]):
                continue

            if (window[1] and timestamp > window[1] + self.basetime) or \
               (abs_window[1] and timestamp > abs_window[1]):
                return

            try:
                data_start_idx =  start_match.search(line).start()
            except AttributeError:
                continue

            data_str = line[data_start_idx:]

            # Remove empty arrays from the trace
            data_str = re.sub(r"[A-Za-z0-9_]+=\{\} ", r"", data_str)

            trace_class.append_data(timestamp, comm, pid, cpu, data_str)

    def trace_hasnt_started(self):
        """Return a function that accepts a line and returns true if this line
is not part of the trace.

        Subclasses of GenericFTrace may override this to skip the
        beginning of a file that is not part of the trace.  The first
        time the returned function returns False it will be considered
        the beginning of the trace and this function will never be
        called again (because once it returns False, the trace has
        started).

        """
        return lambda x: False

    def trace_hasnt_finished(self):
        """Return a function that accepts a line and returns true if this line
is part of the trace.

        This function is called with each line of the file *after*
        trace_hasnt_started() returns True so the first line it sees
        is part of the trace.  The returned function should return
        True as long as the line it receives is part of the trace.  As
        soon as this function returns False, the rest of the file will
        be dropped.  Subclasses of GenericFTrace may override this to
        stop processing after the end of the trace is found to skip
        parsing the end of the file if it contains anything other than
        trace.

        """
        return lambda x: True

    def __parse_trace_file(self, trace_file, window, abs_window, raw=False):
        """parse the trace and create a pandas DataFrame"""

        # Memoize the unique words to speed up parsing the trace file
        cls_for_unique_word = {}
        for trace_name in self.class_definitions.iterkeys():
            trace_class = getattr(self, trace_name)

            if self.needs_raw_parsing and (trace_class.parse_raw != raw):
                continue

            unique_word = trace_class.unique_word
            cls_for_unique_word[unique_word] = trace_class

        if len(cls_for_unique_word) == 0:
            return

        with open(trace_file) as fin:
            self.__populate_data(fin, cls_for_unique_word, window, abs_window)

    # TODO: Move thermal specific functionality

    def get_all_freqs_data(self, map_label):
        """get an array of tuple of names and DataFrames suitable for the
        allfreqs plot"""

        cpu_in_freqs = self.cpu_in_power.get_all_freqs(map_label)
        cpu_out_freqs = self.cpu_out_power.get_all_freqs(map_label)

        ret = []
        for label in map_label.values():
            in_label = label + "_freq_in"
            out_label = label + "_freq_out"

            cpu_inout_freq_dict = {in_label: cpu_in_freqs[label],
                                   out_label: cpu_out_freqs[label]}
            dfr = pd.DataFrame(cpu_inout_freq_dict).fillna(method="pad")
            ret.append((label, dfr))

        try:
            gpu_freq_in_data = self.devfreq_in_power.get_all_freqs()
            gpu_freq_out_data = self.devfreq_out_power.get_all_freqs()
        except KeyError:
            gpu_freq_in_data = gpu_freq_out_data = None

        if gpu_freq_in_data is not None:
            inout_freq_dict = {"gpu_freq_in": gpu_freq_in_data["freq"],
                               "gpu_freq_out": gpu_freq_out_data["freq"]
                           }
            dfr = pd.DataFrame(inout_freq_dict).fillna(method="pad")
            ret.append(("GPU", dfr))

        return ret

    def plot_freq_hists(self, map_label, ax):
        """Plot histograms for each actor input and output frequency

        ax is an array of axis, one for the input power and one for
        the output power

        """

        in_base_idx = len(ax) / 2

        try:
            devfreq_out_all_freqs = self.devfreq_out_power.get_all_freqs()
            devfreq_in_all_freqs = self.devfreq_in_power.get_all_freqs()
        except KeyError:
            devfreq_out_all_freqs = None
            devfreq_in_all_freqs = None

        out_allfreqs = (self.cpu_out_power.get_all_freqs(map_label),
                        devfreq_out_all_freqs, ax[0:in_base_idx])
        in_allfreqs = (self.cpu_in_power.get_all_freqs(map_label),
                       devfreq_in_all_freqs, ax[in_base_idx:])

        for cpu_allfreqs, devfreq_freqs, axis in (out_allfreqs, in_allfreqs):
            if devfreq_freqs is not None:
                devfreq_freqs.name = "GPU"
                allfreqs = pd.concat([cpu_allfreqs, devfreq_freqs], axis=1)
            else:
                allfreqs = cpu_allfreqs

            allfreqs.fillna(method="pad", inplace=True)
            _plot_freq_hists(allfreqs, "out", axis, self.name)

    def plot_load(self, mapping_label, title="", width=None, height=None,
                  ax=None):
        """plot the load of all the clusters, similar to how compare runs did it

        the mapping_label has to be a dict whose keys are the cluster
        numbers as found in the trace and values are the names that
        will appear in the legend.

        """
        import trappy.plot_utils

        load_data = self.cpu_in_power.get_load_data(mapping_label)
        try:
            gpu_data = pd.DataFrame({"GPU":
                                     self.devfreq_in_power.data_frame["load"]})
            load_data = pd.concat([load_data, gpu_data], axis=1)
        except KeyError:
            pass

        load_data = load_data.fillna(method="pad")
        title = trappy.plot_utils.normalize_title("Utilization", title)

        if not ax:
            ax = trappy.plot_utils.pre_plot_setup(width=width, height=height)

        load_data.plot(ax=ax)

        trappy.plot_utils.post_plot_setup(ax, title=title)

    def plot_normalized_load(self, mapping_label, title="", width=None,
                             height=None, ax=None):
        """plot the normalized load of all the clusters, similar to how compare runs did it

        the mapping_label has to be a dict whose keys are the cluster
        numbers as found in the trace and values are the names that
        will appear in the legend.

        """
        import trappy.plot_utils

        load_data = self.cpu_in_power.get_normalized_load_data(mapping_label)
        if "load" in self.devfreq_in_power.data_frame:
            gpu_dfr = self.devfreq_in_power.data_frame
            gpu_max_freq = max(gpu_dfr["freq"])
            gpu_load = gpu_dfr["load"] * gpu_dfr["freq"] / gpu_max_freq

            gpu_data = pd.DataFrame({"GPU": gpu_load})
            load_data = pd.concat([load_data, gpu_data], axis=1)

        load_data = load_data.fillna(method="pad")
        title = trappy.plot_utils.normalize_title("Normalized Utilization", title)

        if not ax:
            ax = trappy.plot_utils.pre_plot_setup(width=width, height=height)

        load_data.plot(ax=ax)

        trappy.plot_utils.post_plot_setup(ax, title=title)

    def plot_allfreqs(self, map_label, width=None, height=None, ax=None):
        """Do allfreqs plots similar to those of CompareRuns

        if ax is not none, it must be an array of the same size as
        map_label.  Each plot will be done in each of the axis in
        ax

        """
        import trappy.plot_utils

        all_freqs = self.get_all_freqs_data(map_label)

        setup_plot = False
        if ax is None:
            ax = [None] * len(all_freqs)
            setup_plot = True

        for this_ax, (label, dfr) in zip(ax, all_freqs):
            this_title = trappy.plot_utils.normalize_title("allfreqs " + label,
                                                        self.name)

            if setup_plot:
                this_ax = trappy.plot_utils.pre_plot_setup(width=width,
                                                        height=height)

            dfr.plot(ax=this_ax)
            trappy.plot_utils.post_plot_setup(this_ax, title=this_title)

class FTrace(GenericFTrace):
    """A wrapper class that initializes all the classes of a given run

    - The FTrace class can receive the following optional parameters.

    :param path: Path contains the path to the trace file.  If no path is given, it
        uses the current directory by default.  If path is a file, and ends in
        .dat, it's run through "trace-cmd report".  If it doesn't end in
        ".dat", then it must be the output of a trace-cmd report run.  If path
        is a directory that contains a trace.txt, that is assumed to be the
        output of "trace-cmd report".  If path is a directory that doesn't
        have a trace.txt but has a trace.dat, it runs trace-cmd report on the
        trace.dat, saves it in trace.txt and then uses that.

    :param name: is a string describing the trace.

    :param normalize_time: is used to make all traces start from time 0 (the
        default).  If normalize_time is False, the trace times are the same as
        in the trace file.

    :param scope: can be used to limit the parsing done on the trace.  The default
        scope parses all the traces known to trappy.  If scope is thermal, only
        the thermal classes are parsed.  If scope is sched, only the sched
        classes are parsed.

    :param events: A list of strings containing the name of the trace
        events that you want to include in this FTrace object.  The
        string must correspond to the event name (what you would pass
        to "trace-cmd -e", i.e. 4th field in trace.txt)

    :param window: a tuple indicating a time window.  The first
        element in the tuple is the start timestamp and the second one
        the end timestamp.  Timestamps are relative to the first trace
        event that's parsed.  If you want to trace until the end of
        the trace, set the second element to None.  If you want to use
        timestamps extracted from the trace file use "abs_window".

    :param abs_window: a tuple indicating an absolute time window.
        This parameter is similar to the "window" one but its values
        represent timestamps that are not normalized, (i.e. the ones
        you find in the trace file)

    :type path: str
    :type name: str
    :type normalize_time: bool
    :type scope: str
    :type events: list
    :type window: tuple
    :type abs_window: tuple

    This is a simple example:
    ::

        import trappy
        trappy.FTrace("trace_dir")

    """

    def __init__(self, path=".", name=".", normalize_time=True, scope="all",
                 events=[], window=(0, None), abs_window=(0, None)):
        self.trace_path, self.trace_path_raw = self.__process_path(path)
        self.needs_raw_parsing = True

        self.__populate_metadata()

        super(FTrace, self).__init__(name, normalize_time, scope, events,
                                     window, abs_window)

    def __process_path(self, basepath):
        """Process the path and return the path to the trace text file"""

        if os.path.isfile(basepath):
            trace_name = os.path.splitext(basepath)[0]
        else:
            trace_name = os.path.join(basepath, "trace")

        trace_txt = trace_name + ".txt"
        trace_raw = trace_name + ".raw.txt"
        trace_dat = trace_name + ".dat"

        if os.path.isfile(trace_dat):
            # Both TXT and RAW traces must always be generated
            if not os.path.isfile(trace_txt) or \
               not os.path.isfile(trace_raw):
                self.__run_trace_cmd_report(trace_dat)
            # TXT (and RAW) traces must match the most recent binary trace
            elif os.path.getmtime(trace_txt) < os.path.getmtime(trace_dat):
                self.__run_trace_cmd_report(trace_dat)

        if not os.path.isfile(trace_raw):
            trace_raw = None

        return trace_txt, trace_raw

    def __run_trace_cmd_report(self, fname):
        """Run "trace-cmd report fname > fname.txt"
           and "trace-cmd report -R fname > fname.raw.txt"

        The resulting traces are stored in files with extension ".txt"
        and ".raw.txt" respectively.  If fname is "my_trace.dat", the
        trace is stored in "my_trace.txt" and "my_trace.raw.txt".  The
        contents of the destination files are overwritten if they
        exist.

        """
        from subprocess import check_output

        cmd = ["trace-cmd", "report"]

        if not os.path.isfile(fname):
            raise IOError("No such file or directory: {}".format(fname))

        raw_trace_output = os.path.splitext(fname)[0] + ".raw.txt"
        trace_output = os.path.splitext(fname)[0] + ".txt"
        cmd.append(fname)

        with open(os.devnull) as devnull:
            try:
                out = check_output(cmd, stderr=devnull)
            except OSError as exc:
                if exc.errno == 2 and not exc.filename:
                    raise OSError(2, "trace-cmd not found in PATH, is it installed?")
                else:
                    raise

            # Add the -R flag to the trace-cmd
            # for raw parsing
            cmd.insert(-1, "-R")
            raw_out = check_output(cmd, stderr=devnull)

        with open(trace_output, "w") as fout:
            fout.write(out)

        with open(raw_trace_output, "w") as fout:
            fout.write(raw_out)

    def __populate_metadata(self):
        """Populates trace metadata"""

        # Meta Data as expected to be found in the parsed trace header
        metadata_keys = ["version", "cpus"]

        for key in metadata_keys:
            setattr(self, "_" + key, None)

        with open(self.trace_path) as fin:
            for line in fin:
                if not metadata_keys:
                    return

                metadata_pattern = r"^\b(" + "|".join(metadata_keys) + \
                                   r")\b\s*=\s*([0-9]+)"
                match = re.search(metadata_pattern, line)
                if match:
                    setattr(self, "_" + match.group(1), match.group(2))
                    metadata_keys.remove(match.group(1))

                if re.search(r"^\s+[^\[]+-\d+\s+\[\d+\]\s+\d+\.\d+:", line):
                    # Reached a valid trace line, abort metadata population
                    return


text:
package steps

import (
	"fmt"
	"io"
	"net/url"
	"os"

	"code.cloudfoundry.org/bbs/models"
	"code.cloudfoundry.org/bytefmt"
	"code.cloudfoundry.org/cacheddownloader"
	"code.cloudfoundry.org/executor/depot/log_streamer"
	"code.cloudfoundry.org/garden"
	"code.cloudfoundry.org/lager"
	"github.com/tedsuo/ifrit"
)

type downloadStep struct {
	container        garden.Container
	model            models.DownloadAction
	cachedDownloader cacheddownloader.CachedDownloader
	streamer         log_streamer.LogStreamer
	rateLimiter      chan struct{}
	cancelDownload   chan struct{}

	logger lager.Logger
}

func NewDownload(
	container garden.Container,
	model models.DownloadAction,
	cachedDownloader cacheddownloader.CachedDownloader,
	rateLimiter chan struct{},
	streamer log_streamer.LogStreamer,
	logger lager.Logger,
) ifrit.Runner {
	logger = logger.Session("download-step", lager.Data{
		"to":       model.To,
		"cacheKey": model.CacheKey,
		"user":     model.User,
	})

	return &downloadStep{
		container:        container,
		model:            model,
		cachedDownloader: cachedDownloader,
		streamer:         streamer,
		rateLimiter:      rateLimiter,
		logger:           logger,
		cancelDownload:   make(chan struct{}),
	}
}

func (step *downloadStep) Run(signals <-chan os.Signal, ready chan<- struct{}) error {
	close(ready)

	step.logger.Info("acquiring-limiter")
	select {
	case step.rateLimiter <- struct{}{}:
	case <-signals:
		return new(CancelledError)
	}
	defer func() {
		<-step.rateLimiter
	}()
	step.logger.Info("acquired-limiter")

	errCh := make(chan error, 1)
	go func() {
		errCh <- step.perform()
	}()

	select {
	case err := <-errCh:
		return err
	case <-signals:
		close(step.cancelDownload)
		return new(CancelledError)
	}
}

func (step *downloadStep) perform() error {
	step.emit("Downloading %s...\n", step.model.Artifact)

	downloadedFile, downloadedSize, err := step.fetch()
	if err != nil {
		var errString string
		if step.model.Artifact != "" {
			errString = fmt.Sprintf("Downloading %s failed", step.model.Artifact)
		} else {
			errString = "Downloading failed"
		}

		step.emitError(fmt.Sprintf("%s\n", errString))
		return NewEmittableError(err, errString)
	}

	err = step.streamIn(step.model.To, downloadedFile)
	if err != nil {
		var errString string
		if step.model.Artifact != "" {
			errString = fmt.Sprintf("Copying %s into the container failed: %v", step.model.Artifact, err)
		} else {
			errString = fmt.Sprintf("Copying into the container failed: %v", err)
		}
		step.emitError(fmt.Sprintf("%s\n", errString))
		return NewEmittableError(err, errString)
	}

	if downloadedSize != 0 {
		step.emit("Downloaded %s (%s)\n", step.model.Artifact, bytefmt.ByteSize(uint64(downloadedSize)))
	} else {
		step.emit("Downloaded %s\n", step.model.Artifact)
	}

	return nil
}

func (step *downloadStep) fetch() (io.ReadCloser, int64, error) {
	step.logger.Info("fetch-starting")
	url, err := url.ParseRequestURI(step.model.From)
	if err != nil {
		step.logger.Error("parse-request-uri-error", err)
		return nil, 0, err
	}

	tarStream, downloadedSize, err := step.cachedDownloader.Fetch(
		step.logger.Session("downloader"),
		url,
		step.model.CacheKey,
		cacheddownloader.ChecksumInfoType{
			Algorithm: step.model.GetChecksumAlgorithm(),
			Value:     step.model.GetChecksumValue(),
		},
		step.cancelDownload,
	)
	if err != nil {
		step.logger.Error("fetch-failed", err)
		return nil, 0, err
	}

	step.logger.Info("fetch-complete", lager.Data{"size": downloadedSize})
	return tarStream, downloadedSize, nil
}

func (step *downloadStep) streamIn(destination string, reader io.ReadCloser) error {
	step.logger.Info("stream-in-starting")

	wrappedReader := &ReadSizer{Reader: reader}

	// StreamIn will close the reader
	err := step.container.StreamIn(garden.StreamInSpec{Path: destination, TarStream: wrappedReader, User: step.model.User})
	if err != nil {
		step.logger.Error("stream-in-failed", err, lager.Data{
			"destination": destination,
		})
		return err
	}

	step.logger.Info("stream-in-complete", lager.Data{"size": wrappedReader.BytesRead()})
	return nil
}

func (step *downloadStep) emit(format string, a ...interface{}) {
	if step.model.Artifact != "" {
		fmt.Fprintf(step.streamer.Stdout(), format, a...)
	}
}

func (step *downloadStep) emitError(format string, a ...interface{}) {
	err_bytes := []byte(fmt.Sprintf(format, a...))
	if len(err_bytes) > 1024 {
		truncation_length := 1024 - len([]byte(" (error truncated)"))
		err_bytes = append(err_bytes[:truncation_length], []byte(" (error truncated)")...)
	}

	fmt.Fprintf(step.streamer.Stderr(), string(err_bytes))
}

type ReadSizer struct {
	bytesRead int
	io.Reader
}

func (r *ReadSizer) Read(dest []byte) (int, error) {
	n, err := r.Reader.Read(dest)
	r.bytesRead += n
	return n, err
}

func (r *ReadSizer) BytesRead() int {
	return r.bytesRead
}

redpajama_set_name: RedPajamaGithub


text:
CONSUL_HTTP_ADDR=${CONSUL_HTTP_ADDR:-"localhost:8500"}
SERVICE_NAME=$1
NODE_NAME=$2
SERVICE_ADDRESS=${3:-10.0.0.1}
SERVICE_PORT=${4:-80}

echo "Registering service $SERVICE_NAME at address $SERVICE_ADDRESS"
curl -X PUT --data "{\"Node\": \"$NODE_NAME\", \"Address\": \"$SERVICE_ADDRESS\", \"Service\": { \"Service\": \"$SERVICE_NAME\", \"Port\": $SERVICE_PORT } }" "http://$CONSUL_HTTP_ADDR/v1/catalog/register"


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lentinus radicosus var. lobatus Pat.

### Remarks
null


text:
@class User;

@interface ContactCell : UICollectionViewCell

- (void)configureWithUser:(User *)user;

@end


text:
/**
 * Autogenerated by Thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package test.fixtures.patch;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.util.Collections;
import java.util.BitSet;
import java.util.Arrays;
import com.facebook.thrift.*;
import com.facebook.thrift.annotations.*;
import com.facebook.thrift.async.*;
import com.facebook.thrift.meta_data.*;
import com.facebook.thrift.server.*;
import com.facebook.thrift.transport.*;
import com.facebook.thrift.protocol.*;

@SuppressWarnings({ "unused", "serial" })
public class MyDataPatch implements TBase, java.io.Serializable, Cloneable {
  private static final TStruct STRUCT_DESC = new TStruct("MyDataPatch");
  private static final TField ASSIGN_FIELD_DESC = new TField("assign", TType.STRUCT, (short)1);
  private static final TField CLEAR_FIELD_DESC = new TField("clear", TType.BOOL, (short)2);
  private static final TField PATCH_PRIOR_FIELD_DESC = new TField("patchPrior", TType.STRUCT, (short)3);
  private static final TField ENSURE_FIELD_DESC = new TField("ensure", TType.STRUCT, (short)5);
  private static final TField PATCH_FIELD_DESC = new TField("patch", TType.STRUCT, (short)6);

  /**
   * Assigns to a (set) value.
   *
   * If set, all other operations are ignored.
   *
   * Note: Optional and union fields must be set before assigned.
   *
   */
  public final MyData assign;
  /**
   * Clears a value. Applies first.
   */
  public final Boolean clear;
  /**
   * Patches any previously set values. Applies second.
   */
  public final MyDataFieldPatch patchPrior;
  /**
   * Initialize fields, using the given defaults. Applies third.
   */
  public final MyData ensure;
  /**
   * Patches any set value, including newly set values. Applies last.
   */
  public final MyDataFieldPatch patch;
  public static final int ASSIGN = 1;
  public static final int CLEAR = 2;
  public static final int PATCHPRIOR = 3;
  public static final int ENSURE = 5;
  public static final int PATCH = 6;

  public MyDataPatch(
      MyData assign,
      Boolean clear,
      MyDataFieldPatch patchPrior,
      MyData ensure,
      MyDataFieldPatch patch) {
    this.assign = assign;
    this.clear = clear;
    this.patchPrior = patchPrior;
    this.ensure = ensure;
    this.patch = patch;
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public MyDataPatch(MyDataPatch other) {
    if (other.isSetAssign()) {
      this.assign = TBaseHelper.deepCopy(other.assign);
    } else {
      this.assign = null;
    }
    if (other.isSetClear()) {
      this.clear = TBaseHelper.deepCopy(other.clear);
    } else {
      this.clear = null;
    }
    if (other.isSetPatchPrior()) {
      this.patchPrior = TBaseHelper.deepCopy(other.patchPrior);
    } else {
      this.patchPrior = null;
    }
    if (other.isSetEnsure()) {
      this.ensure = TBaseHelper.deepCopy(other.ensure);
    } else {
      this.ensure = null;
    }
    if (other.isSetPatch()) {
      this.patch = TBaseHelper.deepCopy(other.patch);
    } else {
      this.patch = null;
    }
  }

  public MyDataPatch deepCopy() {
    return new MyDataPatch(this);
  }

  /**
   * Assigns to a (set) value.
   *
   * If set, all other operations are ignored.
   *
   * Note: Optional and union fields must be set before assigned.
   *
   */
  public MyData getAssign() {
    return this.assign;
  }

  // Returns true if field assign is set (has been assigned a value) and false otherwise
  public boolean isSetAssign() {
    return this.assign != null;
  }

  /**
   * Clears a value. Applies first.
   */
  public Boolean isClear() {
    return this.clear;
  }

  // Returns true if field clear is set (has been assigned a value) and false otherwise
  public boolean isSetClear() {
    return this.clear != null;
  }

  /**
   * Patches any previously set values. Applies second.
   */
  public MyDataFieldPatch getPatchPrior() {
    return this.patchPrior;
  }

  // Returns true if field patchPrior is set (has been assigned a value) and false otherwise
  public boolean isSetPatchPrior() {
    return this.patchPrior != null;
  }

  /**
   * Initialize fields, using the given defaults. Applies third.
   */
  public MyData getEnsure() {
    return this.ensure;
  }

  // Returns true if field ensure is set (has been assigned a value) and false otherwise
  public boolean isSetEnsure() {
    return this.ensure != null;
  }

  /**
   * Patches any set value, including newly set values. Applies last.
   */
  public MyDataFieldPatch getPatch() {
    return this.patch;
  }

  // Returns true if field patch is set (has been assigned a value) and false otherwise
  public boolean isSetPatch() {
    return this.patch != null;
  }

  @Override
  public boolean equals(Object _that) {
    if (_that == null)
      return false;
    if (this == _that)
      return true;
    if (!(_that instanceof MyDataPatch))
      return false;
    MyDataPatch that = (MyDataPatch)_that;

    if (!TBaseHelper.equalsNobinary(this.isSetAssign(), that.isSetAssign(), this.assign, that.assign)) { return false; }

    if (!TBaseHelper.equalsNobinary(this.isSetClear(), that.isSetClear(), this.clear, that.clear)) { return false; }

    if (!TBaseHelper.equalsNobinary(this.isSetPatchPrior(), that.isSetPatchPrior(), this.patchPrior, that.patchPrior)) { return false; }

    if (!TBaseHelper.equalsNobinary(this.isSetEnsure(), that.isSetEnsure(), this.ensure, that.ensure)) { return false; }

    if (!TBaseHelper.equalsNobinary(this.isSetPatch(), that.isSetPatch(), this.patch, that.patch)) { return false; }

    return true;
  }

  @Override
  public int hashCode() {
    return Arrays.deepHashCode(new Object[] {assign, clear, patchPrior, ensure, patch});
  }

  // This is required to satisfy the TBase interface, but can't be implemented on immutable struture.
  public void read(TProtocol iprot) throws TException {
    throw new TException("unimplemented in android immutable structure");
  }

  public static MyDataPatch deserialize(TProtocol iprot) throws TException {
    MyData tmp_assign = null;
    Boolean tmp_clear = null;
    MyDataFieldPatch tmp_patchPrior = null;
    MyData tmp_ensure = null;
    MyDataFieldPatch tmp_patch = null;
    TField __field;
    iprot.readStructBegin();
    while (true)
    {
      __field = iprot.readFieldBegin();
      if (__field.type == TType.STOP) {
        break;
      }
      switch (__field.id)
      {
        case ASSIGN:
          if (__field.type == TType.STRUCT) {
            tmp_assign = MyData.deserialize(iprot);
          } else {
            TProtocolUtil.skip(iprot, __field.type);
          }
          break;
        case CLEAR:
          if (__field.type == TType.BOOL) {
            tmp_clear = iprot.readBool();
          } else {
            TProtocolUtil.skip(iprot, __field.type);
          }
          break;
        case PATCHPRIOR:
          if (__field.type == TType.STRUCT) {
            tmp_patchPrior = MyDataFieldPatch.deserialize(iprot);
          } else {
            TProtocolUtil.skip(iprot, __field.type);
          }
          break;
        case ENSURE:
          if (__field.type == TType.STRUCT) {
            tmp_ensure = MyData.deserialize(iprot);
          } else {
            TProtocolUtil.skip(iprot, __field.type);
          }
          break;
        case PATCH:
          if (__field.type == TType.STRUCT) {
            tmp_patch = MyDataFieldPatch.deserialize(iprot);
          } else {
            TProtocolUtil.skip(iprot, __field.type);
          }
          break;
        default:
          TProtocolUtil.skip(iprot, __field.type);
          break;
      }
      iprot.readFieldEnd();
    }
    iprot.readStructEnd();

    MyDataPatch _that;
    _that = new MyDataPatch(
      tmp_assign
      ,tmp_clear
      ,tmp_patchPrior
      ,tmp_ensure
      ,tmp_patch
    );
    _that.validate();
    return _that;
  }

  public void write(TProtocol oprot) throws TException {
    validate();

    oprot.writeStructBegin(STRUCT_DESC);
    if (this.assign != null) {
      if (isSetAssign()) {
        oprot.writeFieldBegin(ASSIGN_FIELD_DESC);
        this.assign.write(oprot);
        oprot.writeFieldEnd();
      }
    }
    if (this.clear != null) {
      oprot.writeFieldBegin(CLEAR_FIELD_DESC);
      oprot.writeBool(this.clear);
      oprot.writeFieldEnd();
    }
    if (this.patchPrior != null) {
      oprot.writeFieldBegin(PATCH_PRIOR_FIELD_DESC);
      this.patchPrior.write(oprot);
      oprot.writeFieldEnd();
    }
    if (this.ensure != null) {
      oprot.writeFieldBegin(ENSURE_FIELD_DESC);
      this.ensure.write(oprot);
      oprot.writeFieldEnd();
    }
    if (this.patch != null) {
      oprot.writeFieldBegin(PATCH_FIELD_DESC);
      this.patch.write(oprot);
      oprot.writeFieldEnd();
    }
    oprot.writeFieldStop();
    oprot.writeStructEnd();
  }

  @Override
  public String toString() {
    return toString(1, true);
  }

  @Override
  public String toString(int indent, boolean prettyPrint) {
    return TBaseHelper.toStringHelper(this, indent, prettyPrint);
  }

  public void validate() throws TException {
    // check for required fields
  }

}


text:
#ifndef _USB_DEVICE_COMPOSITE_H_
#define _USB_DEVICE_COMPOSITE_H_ 1
#include "FreeRTOS.h"
#include "semphr.h"
#include "event_groups.h"

#include "virtual_com.h"
#include "disk.h"

/*******************************************************************************
* Definitions
******************************************************************************/
#if defined(USB_DEVICE_CONFIG_EHCI) && (USB_DEVICE_CONFIG_EHCI > 0)
#define CONTROLLER_ID kUSB_ControllerEhci0
#endif
#if defined(USB_DEVICE_CONFIG_KHCI) && (USB_DEVICE_CONFIG_KHCI > 0)
#define CONTROLLER_ID kUSB_ControllerKhci0
#endif
#if defined(USB_DEVICE_CONFIG_LPCIP3511FS) && (USB_DEVICE_CONFIG_LPCIP3511FS > 0U)
#define CONTROLLER_ID kUSB_ControllerLpcIp3511Fs0
#endif

#define USB_DEVICE_INTERRUPT_PRIORITY (3U)

typedef struct _usb_device_composite_struct
{
    usb_device_handle deviceHandle; /* USB device handle. */
    usb_cdc_vcom_struct_t cdcVcom;  /* CDC virtual com device structure. */
    usb_msc_struct_t mscDisk; /* MSC disk device structure.                                                        */
    xTaskHandle applicationTaskHandle; /* Application task handle. */
    xTaskHandle deviceTaskHandle;      /* USB device task handle. */
    uint8_t speed;  /* Speed of USB device. USB_SPEED_FULL/USB_SPEED_LOW/USB_SPEED_HIGH.                 */
    uint8_t attach; /* A flag to indicate whether a usb device is attached. 1: attached, 0: not attached */
    uint8_t currentConfiguration; /* Current configuration value. */
    uint8_t
        currentInterfaceAlternateSetting[USB_INTERFACE_COUNT]; /* Current alternate setting value for each interface. */
} usb_device_composite_struct_t;

/*******************************************************************************
* API
******************************************************************************/
/*!
 * @brief CDC class specific callback function.
 *
 * This function handles the CDC class specific requests.
 *
 * @param handle          The CDC ACM class handle.
 * @param event           The CDC ACM class event type.
 * @param param           The parameter of the class specific request.
 *
 * @return A USB error code or kStatus_USB_Success.
 */
extern usb_status_t USB_DeviceCdcVcomCallback(class_handle_t handle, uint32_t event, void *param);
/*!
 * @brief Virtual COM device set configuration function.
 *
 * This function sets configuration for CDC class.
 *
 * @param handle The CDC ACM class handle.
 * @param configure The CDC ACM class configure index.
 *
 * @return A USB error code or kStatus_USB_Success.
 */
extern usb_status_t USB_DeviceCdcVcomSetConfigure(class_handle_t handle, uint8_t configure);
/*!
 * @brief Virtual COM device initialization function.
 *
 * This function initializes the device with the composite device class information.
 *
 * @param deviceComposite The pointer to the composite device structure.
 *
 * @return A USB error code or kStatus_USB_Success.
 */
extern usb_status_t USB_DeviceCdcVcomInit(usb_device_composite_struct_t *deviceComposite);
/*!
 * @brief Application task function.
 *
 * This function runs the task for application.
 *
 * @return None.
 */
extern void USB_DeviceCdcVcomTask(void);

/*!
 * @brief MSC class specific callback function.
 *
 * This function handles the MSCclass specific requests.
 *
 * @param handle          The MSC class handle.
 * @param event           The MSC class event type.
 * @param param           The parameter of the class specific request.
 *
 * @return A USB error code or kStatus_USB_Success.
 */
extern usb_status_t USB_DeviceMscCallback(class_handle_t handle, uint32_t event, void *param);
/*!
 * @brief MSC disk device set configuration function.
 *
 * This function sets configuration for MSC class.
 *
 * @param handle The MSC class handle.
 * @param configure The MSC class configure index.
 *
 * @return A USB error code or kStatus_USB_Success.
 */
extern usb_status_t USB_DeviceMscDiskSetConfigure(class_handle_t handle, uint8_t configure);
/*!
 * @brief MSC disk device initialization function.
 *
 * This function initializes the device with the composite device class information.
 *
 * @param deviceComposite The pointer to the composite device structure.
 *
 * @return A USB error code or kStatus_USB_Success.
 */
extern usb_status_t USB_DeviceMscDiskInit(usb_device_composite_struct_t *deviceComposite);

#endif /* _USB_DEVICE_COMPOSITE_H_ */


text:
class MagicLaunch < Cask
  version '1.4.3'
  sha256 'f209f58e22c5881dc226b294181cc324a9e446425548b5de35c6f26bab1c7a4d'

  url "https://www.oneperiodic.com/files/Magic%20Launch%20v#{version}.zip"
  homepage 'http://www.oneperiodic.com/products/magiclaunch/'

  prefpane 'Magic Launch.prefPane'
  zap :delete => '~/Library/Preferences/com.metakine.magic-launch.agent.plist'
end


text:
using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Diagnostics;
using Microsoft.AspNet.Diagnostics.Entity;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Security.Cookies;
using Microsoft.Data.Entity;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;
using Microsoft.Framework.Logging.Console;
using FileUploadSample.Models;

namespace FileUploadSample
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            // Setup configuration sources.
            Configuration = new Configuration()
                .AddJsonFile("config.json")
                .AddEnvironmentVariables();
        }

        public IConfiguration Configuration { get; set; }

        // This method gets called by the runtime.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add EF services to the services container.
            services.AddEntityFramework(Configuration)
                .AddSqlServer()
                .AddDbContext<ApplicationDbContext>();

            // Add Identity services to the services container.
            services.AddIdentity<ApplicationUser, IdentityRole>(Configuration)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            // Add MVC services to the services container.
            services.AddMvc();

            // Uncomment the following line to add Web API servcies which makes it easier to port Web API 2 controllers.
            // You need to add Microsoft.AspNet.Mvc.WebApiCompatShim package to project.json
            // services.AddWebApiConventions();

        }

        // Configure is called after ConfigureServices is called.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory)
        {
            // Configure the HTTP request pipeline.
            // Add the console logger.
            loggerfactory.AddConsole();

            // Add the following to the request pipeline only in development environment.
            if (string.Equals(env.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase))
            {
                app.UseBrowserLink();
                app.UseErrorPage(ErrorPageOptions.ShowAll);
                app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
            }
            else
            {
                // Add Error handling middleware which catches all application specific errors and
                // send the request to the following path or controller action.
                app.UseErrorHandler("/Home/Error");
            }

            // Add static files to the request pipeline.
            app.UseStaticFiles();

            // Add cookie-based authentication to the request pipeline.
            app.UseIdentity();

            // Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" });

                // Uncomment the following line to add a route for porting Web API 2 controllers.
                // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            });
        }
    }
}


text:
package game.scenes;

import engine.TimeManager;
import engine.common.Behavior;
import engine.common.GameObject;
import game.scenes.loaders.TestSceneLoader;

/**
 * A behavior that controls the Test Scene script
 *
 * @author Brandon Porter
 *
 */
public class SplashSceneBehavior extends Behavior {
	private static final float CUBE_SPEED = 175f;

	private GameObject _cube;

	/**
	 * Constructs a new behavior for the Test Scene
	 */
	public SplashSceneBehavior() {
		super(TestSceneLoader.NAME);
	}

	@SuppressWarnings("unused")
	private void start() {
		this._cube = this.getScene().findGameObject("Cube");
	}

	@SuppressWarnings("unused")
	private void update() {
		_cube.getTransform().rotate(0, CUBE_SPEED * TimeManager.getDeltaTime(), 0);
	}
}


text:
package pollers

import (
	"context"
	"errors"
	"io"
	"net/http"
	"strings"
	"testing"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared"
	"github.com/stretchr/testify/require"
)

func TestIsTerminalState(t *testing.T) {
	require.False(t, IsTerminalState("Updating"), "Updating is not a terminal state")
	require.True(t, IsTerminalState("Succeeded"), "Succeeded is a terminal state")
	require.True(t, IsTerminalState("failed"), "failed is a terminal state")
	require.True(t, IsTerminalState("canceled"), "canceled is a terminal state")
}

func TestStatusCodeValid(t *testing.T) {
	require.True(t, StatusCodeValid(&http.Response{StatusCode: http.StatusOK}))
	require.True(t, StatusCodeValid(&http.Response{StatusCode: http.StatusAccepted}))
	require.True(t, StatusCodeValid(&http.Response{StatusCode: http.StatusCreated}))
	require.True(t, StatusCodeValid(&http.Response{StatusCode: http.StatusNoContent}))
	require.False(t, StatusCodeValid(&http.Response{StatusCode: http.StatusPartialContent}))
	require.False(t, StatusCodeValid(&http.Response{StatusCode: http.StatusBadRequest}))
	require.False(t, StatusCodeValid(&http.Response{StatusCode: http.StatusInternalServerError}))
}

type fakeResult[T any] struct {
	Result T
}

func TestNewResumeToken(t *testing.T) {
	n, err := NewResumeToken[struct{}](fakeResult[struct{}]{})
	require.Error(t, err)
	require.Empty(t, n)
	n, err = NewResumeToken[interface{}](fakeResult[interface{}]{})
	require.Error(t, err)
	require.Empty(t, n)
	n, err = NewResumeToken[int](fakeResult[int]{})
	require.NoError(t, err)
	require.Equal(t, `{"type":"int","token":{"Result":0}}`, n)
	n, err = NewResumeToken[*float64](fakeResult[*float64]{})
	require.NoError(t, err)
	require.Equal(t, `{"type":"*float64","token":{"Result":null}}`, n)
}

func TestExtractToken(t *testing.T) {
	tk, err := ExtractToken("not a JSON object")
	require.Error(t, err)
	require.Nil(t, tk)
	tk, err = ExtractToken(`{ "not": "a token" }`)
	require.Error(t, err)
	require.Nil(t, tk)
	tk, err = ExtractToken(`{"type":"int","token":{"Result":0}}`)
	require.NoError(t, err)
	require.Equal(t, `{"Result":0}`, string(tk))
}

func TestIsTokenValid(t *testing.T) {
	err := IsTokenValid[int]("not a JSON object")
	require.Error(t, err)
	err = IsTokenValid[int](`{ "not": "a token" }`)
	require.Error(t, err)
	err = IsTokenValid[int](`{ "type": 123 }`)
	require.Error(t, err)
	err = IsTokenValid[struct{}](`{ "type": "empty" }`)
	require.Error(t, err)
	err = IsTokenValid[int](`{"type":"*float64","token":{"Result":null}}`)
	require.Error(t, err)
	err = IsTokenValid[int](`{"type":"int","token":{"Result":0}}`)
	require.NoError(t, err)
}

func TestIsValidURL(t *testing.T) {
	require.False(t, IsValidURL("/foo"))
	require.True(t, IsValidURL("https://foo.bar/baz"))
}

func TestFailed(t *testing.T) {
	require.False(t, Failed("Succeeded"))
	require.False(t, Failed("Updating"))
	require.True(t, Failed("failed"))
}

func TestGetJSON(t *testing.T) {
	j, err := GetJSON(&http.Response{Body: http.NoBody})
	require.ErrorIs(t, err, ErrNoBody)
	require.Nil(t, j)
	j, err = GetJSON(&http.Response{Body: io.NopCloser(strings.NewReader(`{ "foo": "bar" }`))})
	require.NoError(t, err)
	require.Equal(t, "bar", j["foo"])
}

func TestGetStatusSuccess(t *testing.T) {
	const jsonBody = `{ "status": "InProgress" }`
	resp := &http.Response{
		Body: io.NopCloser(strings.NewReader(jsonBody)),
	}
	status, err := GetStatus(resp)
	require.NoError(t, err)
	require.Equal(t, "InProgress", status)
}

func TestGetNoBody(t *testing.T) {
	resp := &http.Response{
		Body: http.NoBody,
	}
	status, err := GetStatus(resp)
	require.ErrorIs(t, err, ErrNoBody)
	require.Empty(t, status)
	status, err = GetProvisioningState(resp)
	require.ErrorIs(t, err, ErrNoBody)
	require.Empty(t, status)
}

func TestGetStatusError(t *testing.T) {
	resp := &http.Response{
		Body: io.NopCloser(strings.NewReader("{}")),
	}
	status, err := GetStatus(resp)
	require.NoError(t, err)
	require.Empty(t, status)
}

func TestGetProvisioningState(t *testing.T) {
	const jsonBody = `{ "properties": { "provisioningState": "Canceled" } }`
	resp := &http.Response{
		Body: io.NopCloser(strings.NewReader(jsonBody)),
	}
	state, err := GetProvisioningState(resp)
	require.NoError(t, err)
	require.Equal(t, "Canceled", state)
}

func TestGetResourceLocation(t *testing.T) {
	resp := &http.Response{
		Body: http.NoBody,
	}
	resLoc, err := GetResourceLocation(resp)
	require.Error(t, err)
	require.Empty(t, resLoc)
	resp.Body = io.NopCloser(strings.NewReader(`{"status": "succeeded"}`))
	resLoc, err = GetResourceLocation(resp)
	require.NoError(t, err)
	require.Empty(t, resLoc)
	resp.Body = io.NopCloser(strings.NewReader(`{"resourceLocation": 123}`))
	resLoc, err = GetResourceLocation(resp)
	require.Error(t, err)
	require.Empty(t, resLoc)
	resp.Body = io.NopCloser(strings.NewReader(`{"resourceLocation": "here"}`))
	resLoc, err = GetResourceLocation(resp)
	require.NoError(t, err)
	require.Equal(t, "here", resLoc)
}

func TestGetProvisioningStateError(t *testing.T) {
	resp := &http.Response{
		Body: io.NopCloser(strings.NewReader("{}")),
	}
	state, err := GetProvisioningState(resp)
	require.NoError(t, err)
	require.Empty(t, state)
}

func TestNopPoller(t *testing.T) {
	resp := &http.Response{
		StatusCode: http.StatusNoContent,
		Body:       http.NoBody,
	}
	np, err := NewNopPoller[struct{}](resp)
	require.NoError(t, err)
	require.NotNil(t, np)
	require.True(t, np.Done())
	pollResp, err := np.Poll(context.Background())
	require.NoError(t, err)
	require.Equal(t, resp, pollResp)
	var result struct{}
	err = np.Result(context.Background(), &result)
	require.NoError(t, err)

	resp.StatusCode = http.StatusOK
	np, err = NewNopPoller[struct{}](resp)
	require.NoError(t, err)
	require.NotNil(t, np)
	require.True(t, np.Done())
	pollResp, err = np.Poll(context.Background())
	require.NoError(t, err)
	require.Equal(t, resp, pollResp)
	err = np.Result(context.Background(), &result)
	require.NoError(t, err)

	resp.Body = io.NopCloser(strings.NewReader(`"value"`))
	np2, err := NewNopPoller[string](resp)
	require.NoError(t, err)
	require.NotNil(t, np2)
	require.True(t, np2.Done())
	pollResp, err = np2.Poll(context.Background())
	require.NoError(t, err)
	require.Equal(t, resp, pollResp)
	var result2 string
	err = np2.Result(context.Background(), &result2)
	require.NoError(t, err)
	require.Equal(t, "value", result2)
}

func TestPollHelper(t *testing.T) {
	const fakeEndpoint = "https://fake.polling/endpoint"
	err := PollHelper(context.Background(), "invalid endpoint", exported.Pipeline{}, func(*http.Response) (string, error) {
		t.Fatal("shouldn't have been called")
		return "", nil
	})
	require.Error(t, err)

	pl := exported.NewPipeline(shared.TransportFunc(func(*http.Request) (*http.Response, error) {
		return nil, errors.New("failed")
	}))
	err = PollHelper(context.Background(), fakeEndpoint, pl, func(*http.Response) (string, error) {
		t.Fatal("shouldn't have been called")
		return "", nil
	})
	require.Error(t, err)

	require.Error(t, err)
	pl = exported.NewPipeline(shared.TransportFunc(func(*http.Request) (*http.Response, error) {
		return &http.Response{
			StatusCode: http.StatusNotFound,
			Body:       http.NoBody,
		}, nil
	}))
	err = PollHelper(context.Background(), fakeEndpoint, pl, func(*http.Response) (string, error) {
		return "", errors.New("failed")
	})
	require.Error(t, err)

	require.Error(t, err)
	pl = exported.NewPipeline(shared.TransportFunc(func(*http.Request) (*http.Response, error) {
		return &http.Response{
			StatusCode: http.StatusOK,
			Body:       http.NoBody,
		}, nil
	}))
	err = PollHelper(context.Background(), fakeEndpoint, pl, func(*http.Response) (string, error) {
		return "inProgress", nil
	})
	require.NoError(t, err)
}

type widget struct {
	Result        string
	Precalculated int
}

func TestResultHelper(t *testing.T) {
	resp := &http.Response{
		StatusCode: http.StatusNoContent,
		Body:       http.NoBody,
	}
	var result string
	err := ResultHelper(resp, false, &result)
	require.NoError(t, err)
	require.Empty(t, result)

	resp.StatusCode = http.StatusBadRequest
	resp.Body = io.NopCloser(strings.NewReader(`{ "code": "failed", "message": "bad stuff" }`))
	err = ResultHelper(resp, false, &result)
	var respErr *exported.ResponseError
	require.ErrorAs(t, err, &respErr)
	require.Equal(t, "failed", respErr.ErrorCode)
	require.Empty(t, result)

	resp.StatusCode = http.StatusOK
	resp.Body = http.NoBody
	err = ResultHelper(resp, false, &result)
	require.NoError(t, err)
	require.Empty(t, result)

	resp.Body = io.NopCloser(strings.NewReader(`{ "Result": "happy" }`))
	widgetResult := widget{Precalculated: 123}
	err = ResultHelper(resp, false, &widgetResult)
	require.NoError(t, err)
	require.Equal(t, "happy", widgetResult.Result)
	require.Equal(t, 123, widgetResult.Precalculated)
}


text:
var common = require('./common.js');

var BUILTIN_TYPES = [
    "boolean",
    "number",
    "string",
    "function",
    "object", // This will refer to ACTUAL objects
    "array"
];

var types = {};

//
// Public functions
//
function getTypes() {
    return types;
}
module.exports.getTypes = getTypes;

function registerType(name, fields) {
    function validateFields(fields) {
        var isEmpty = true;
        for (var fieldName in fields) {
            isEmpty = false;
            if (typeof fields[fieldName] === "string") {
                var isBuiltinType = BUILTIN_TYPES.indexOf(fields[fieldName]) !== -1;
                var isRegisteredType = types.hasOwnProperty(fields[fieldName]);
                if (!isBuiltinType && !isRegisteredType) {
                    throw "Type " + fields[fieldName] + " not recognized.";
                }
            } else if (common.isRealObject(fields[fieldName])) {
                // Recursively check this field's fields
                validateFields(fields[fieldName]);
            } else {
                throw "Field type for " + fieldName + " must be a string or compatible object.";
            }
        }
        if (isEmpty) {
            throw "Fields cannot be an empty object.";
        }
    }

    if (typeof name !== "string") {
        name = name + "";
    }
    if (BUILTIN_TYPES.indexOf(name) !== -1) {
        throw name + " is already a built-in type.";
    }
    validateFields(fields);

    types[name] = fields;
}
module.exports.registerType = registerType;

function isValidInstance(object, type, exceptions) {
    if (!common.isRealObject(object)) {
        throw "isValidInstance can only be used to validate objects";
    }

    if (typeof exceptions !== "boolean") {
        exceptions = false; // This will also handle undefined
    }

    function failWithMessage(message) {
        if (exceptions) {
            throw message;
        }
        return false;
    }

    if (typeof type === "string") {
        if (!types.hasOwnProperty(type)) {
            throw "Type " + type + " was not registered.";
        }
        type = types[type];
    }

    for (var fieldName in type) {
        if (!object.hasOwnProperty(fieldName)) {
            return failWithMessage("Object did not have field " + fieldName);
        }

        var fieldType = type[fieldName];

        if (typeof fieldType === "string") {
            if (types.hasOwnProperty(fieldType)) {
                if (!isValidInstance(object[fieldName], fieldType, exceptions)) {
                    return false;
                }
            } else if (fieldType === "object") {
                if (object[fieldName] === null) {
                    return failWithMessage("Value for key " + fieldName + " expected to be object, was null");
                }
                if (Array.isArray(object[fieldName])) {
                    return failWithMessage("Value for key " + fieldName + " expected to be object, was array");
                }
            } else if (fieldType === "array") {
                if (!Array.isArray(object[fieldName])) {
                    return failWithMessage("Value for key " + fieldName + " expected to be array, was " + object[fieldName]);
                }
            } else {
                if (typeof object[fieldName] !== fieldType) {
                    return failWithMessage("Value for key " + fieldName + " expected to be " + fieldType + ", was " + object[fieldName]);
                }
            }
        } else if (typeof fieldType === "object") {
            if (!isValidInstance(object[fieldName], type[fieldName], exceptions)) {
                return false;
            }
        }
    }
    for (var fieldName in object) {
        if (!type.hasOwnProperty(fieldName)) {
            return failWithMessage("Object had field " + fieldName + " which was not in type");
        }
    }
    return true;
}
module.exports.isValidInstance = isValidInstance;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Demo01_Proxy.BaseClass;

namespace Demo01_Proxy.DerivedClass
{
    /// <summary>
    /// Proxy类
    /// <remarks>保存一个引用使得代理可以访问的实体,并提供一个与Subject的接口相同的接口,这样代理就可以用来代替真实实体了.</remarks>
    /// </summary>
    public class Proxy : Subject
    {
        public RealSubject RealSubject;
        public override void Request()
        {
            if (RealSubject == null)
            {
                RealSubject = new RealSubject();
            }
            RealSubject.Request(); ;
        }
    }
}


text:
package org.wildfly.camel.test.rest.dsl;

import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.RestConfiguration;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.camel.test.common.http.HttpRequest.HttpRequestBuilder;
import org.wildfly.camel.test.common.http.HttpRequest.HttpResponse;
import org.wildfly.extension.camel.CamelAware;

@CamelAware
@RunWith(Arquillian.class)
public abstract class AbstractRestDslIntegrationTest {

    private static final String[] CORS_HEADERS = { "Access-Control-Allow-Origin", "Access-Control-Allow-Methods",
        "Access-Control-Allow-Headers", "Access-Control-Max-Age" };

    @ArquillianResource
    protected Deployer deployer;

    protected HttpClient client;

    @Before
    public void setUp() {
        this.client = createHttpClient();
    }

    @Test
    public void testRestDsl() throws Exception {
        CamelContext camelctx = new DefaultCamelContext();
        camelctx.setRestConfiguration(createRestConfiguration());
        camelctx.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                rest()
                    .get("/test")
                        .route()
                            .setBody(constant("GET: /test"))
                        .endRest()

                    .get("/foo/bar")
                        .route()
                           .setBody(constant("GET: /foo/bar"))
                        .endRest()

                    .get("/test/{id}")
                        .route()
                            .setBody(simple("GET: /test/${header.id}"))
                        .endRest()

                    .post("/test")
                        .route()
                            .setBody(constant("POST: /test"))
                        .endRest()

                    .put("/test/{id}")
                        .route()
                            .setBody(simple("PUT: /test/${header.id}"))
                        .endRest()

                    .delete("/test/{id}")
                        .route()
                            .setBody(simple("DELETE: /test/${header.id}"))
                        .endRest();
            }
        });
        camelctx.start();
        try {
            String body = client.getResponse("test", "GET").getBody();
            Assert.assertEquals("GET: /test", body);

            body = client.getResponse("foo/bar", "GET").getBody();
            Assert.assertEquals("GET: /foo/bar", body);

            body = client.getResponse("test/1", "GET").getBody();
            Assert.assertEquals("GET: /test/1", body);

            body = client.getResponse("test", "POST").getBody();
            Assert.assertEquals("POST: /test", body);

            body = client.getResponse("test/1", "PUT").getBody();
            Assert.assertEquals("PUT: /test/1", body);

            body = client.getResponse("test/1", "DELETE").getBody();
            Assert.assertEquals("DELETE: /test/1", body);

            int statusCode = client.getResponse("test/foo/bar", "GET").getStatusCode();
            Assert.assertEquals(404, statusCode);
        } finally {
            camelctx.close();
        }
    }

    @Test
    public void testRestDslWithContextPath() throws Exception {
        CamelContext camelctx = new DefaultCamelContext();
        camelctx.setRestConfiguration(createRestConfiguration("camel-rest-dsl-tests"));
        camelctx.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                rest("/test")
                    .get("/")
                        .route()
                            .setBody(constant("GET: /test"))
                        .endRest()

                    .get("/foo/bar")
                        .route()
                            .setBody(constant("GET: /test/foo/bar"))
                        .endRest()

                    .get("/{id}")
                        .route()
                            .setBody(simple("GET: /test/${header.id}"))
                        .endRest()

                    .post("/")
                        .route()
                            .setBody(constant("POST: /test"))
                        .endRest()

                    .put("/{id}")
                        .route()
                            .setBody(simple("PUT: /test/${header.id}"))
                        .endRest()

                    .delete("/{id}")
                        .route()
                            .setBody(simple("DELETE: /test/${header.id}"))
                        .endRest();
            }
        });

        camelctx.start();
        try {
            String body = client.getResponse("camel-rest-dsl-tests/test", "GET").getBody();
            Assert.assertEquals("GET: /test", body);

            body = client.getResponse("camel-rest-dsl-tests/test/foo/bar", "GET").getBody();
            Assert.assertEquals("GET: /test/foo/bar", body);

            body = client.getResponse("camel-rest-dsl-tests/test/1", "GET").getBody();
            Assert.assertEquals("GET: /test/1", body);

            body = client.getResponse("camel-rest-dsl-tests/test", "POST").getBody();
            Assert.assertEquals("POST: /test", body);

            body = client.getResponse("camel-rest-dsl-tests/test/1", "PUT").getBody();
            Assert.assertEquals("PUT: /test/1", body);

            body = client.getResponse("camel-rest-dsl-tests/test/1", "DELETE").getBody();
            Assert.assertEquals("DELETE: /test/1", body);

            int statusCode = client.getResponse("camel-rest-dsl-tests/foo/bar", "GET").getStatusCode();
            Assert.assertEquals(404, statusCode);
        } finally {
            camelctx.close();
        }
    }

    @Test
    public void testRestDslRequestWithInvalidMethod() throws Exception {
        CamelContext camelctx = new DefaultCamelContext();
        camelctx.setRestConfiguration(createRestConfiguration());
        camelctx.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                rest()
                    .get("/foo/bar")
                        .route()
                            .setBody(constant("GET: /test"))
                        .endRest();
            }
        });

        camelctx.start();
        try {
            int statusCode = client.getResponse("foo/bar", "DELETE").getStatusCode();
            Assert.assertEquals(405, statusCode);
        } finally {
            camelctx.close();
        }
    }

    @Test
    public void testRestDslCorsEnabled() throws Exception {
        RestConfiguration restConfiguration = createRestConfiguration();
        restConfiguration.setEnableCORS(true);

        CamelContext camelctx = new DefaultCamelContext();
        camelctx.setRestConfiguration(restConfiguration);
        camelctx.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                rest()
                    .get("/test")
                        .route()
                            .setBody(constant("GET: /test"))
                        .endRest();
            }
        });

        camelctx.start();
        try {
            Map<String, String> headers = client.getResponse("test", "OPTIONS").getHeaders();
            for (String header : CORS_HEADERS) {
                Assert.assertTrue("Expected HTTP response header: " + header, headers.containsKey(header));
            }
        } finally {
            camelctx.close();
        }
    }

    @Test
    public void testRestDslCorsDisabled() throws Exception {
        RestConfiguration restConfiguration = createRestConfiguration();
        restConfiguration.setEnableCORS(false);

        CamelContext camelctx = new DefaultCamelContext();
        camelctx.setRestConfiguration(createRestConfiguration());
        camelctx.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                rest()
                    .get("/test")
                        .route()
                            .setBody(constant("GET: /test"))
                        .endRest();
            }
        });

        camelctx.start();
        try {
            Map<String, String> headers = client.getResponse("test", "OPTIONS").getHeaders();
            for (String header : CORS_HEADERS) {
                Assert.assertFalse(headers.containsKey(header));
            }
        } finally {
            camelctx.close();
        }
    }

    protected abstract String getComponentName();

    protected String getDefaultContextPath() {
        return "/";
    }

    protected HttpClient createHttpClient() {
        return new HttpClient() {
            @Override
            public HttpResponse getResponse(String url, String method) throws Exception {
                return new HttpRequestBuilder(getEndpointUrl(url), method)
                    .throwExceptionOnFailure(false)
                    .getResponse();
            }
        };
    }

    protected int getPort() {
        return 8080;
    }

    private String getEndpointUrl(String path) {
        return String.format("http://localhost:%d%s%s", getPort(), getDefaultContextPath(), path);
    }

    private RestConfiguration createRestConfiguration() {
        return createRestConfiguration(null);
    }

    private RestConfiguration createRestConfiguration(String contextPath) {
        RestConfiguration configuration = new RestConfiguration();
        configuration.setComponent(getComponentName());
        configuration.setHost("localhost");
        configuration.setPort(getPort());

        // camel-servlet always requires a context path
        if (getComponentName().equals("servlet")) {
            configuration.setContextPath(getDefaultContextPath());
        } else {
            configuration.setContextPath(contextPath);
        }

        return configuration;
    }

    protected interface HttpClient {
        HttpResponse getResponse(String url, String method) throws Exception;
    }
}


text:
<?php

return [
    'select.category' => 'select category'
];


text:
package org.apache.ignite.internal.visor.cache;

import org.apache.ignite.*;
import org.apache.ignite.cache.*;
import org.apache.ignite.compute.*;
import org.apache.ignite.internal.processors.task.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.apache.ignite.internal.visor.*;
import org.apache.ignite.lang.*;
import org.apache.ignite.resources.*;

/**
 * Task that clears specified caches on specified node.
 */
@GridInternal
public class VisorCacheClearTask extends VisorOneNodeTask<String, IgniteBiTuple<Integer, Integer>> {
    /** */
    private static final long serialVersionUID = 0L;

    /** {@inheritDoc} */
    @Override protected VisorCacheClearJob job(String arg) {
        return new VisorCacheClearJob(arg, debug);
    }

    /**
     * Job that clear specified caches.
     */
    private static class VisorCacheClearJob extends VisorJob<String, IgniteBiTuple<Integer, Integer>> {
        /** */
        private static final long serialVersionUID = 0L;

        /** */
        @JobContextResource
        private ComputeJobContext jobCtx;

        /** */
        private final IgniteInClosure<IgniteFuture<Integer>> lsnr;

        /** */
        private final IgniteFuture<Integer>[] futs = new IgniteFuture[3];

        /** */
        private final String cacheName;

        /**
         * Create job.
         *
         * @param cacheName Cache name to clear.
         * @param debug Debug flag.
         */
        private VisorCacheClearJob(String cacheName, boolean debug) {
            super(cacheName, debug);

            this.cacheName = cacheName;

            lsnr = new IgniteInClosure<IgniteFuture<Integer>>() {
                @Override public void apply(IgniteFuture<Integer> f) {
                    assert futs[0].isDone();
                    assert futs[1] == null || futs[1].isDone();
                    assert futs[2] == null || futs[2].isDone();

                    jobCtx.callcc();
                }
            };
        }

        /**
         * @param subJob Sub job to execute asynchronously.
         * @param idx Index.
         * @return {@code true} If subJob was not completed and this job should be suspended.
         */
        private boolean callAsync(IgniteCallable<Integer> subJob, int idx) {
            IgniteCompute compute = ignite.compute(ignite.cluster().forCacheNodes(cacheName)).withAsync();

            compute.call(subJob);

            IgniteFuture<Integer> fut = compute.future();

            futs[idx] = fut;

            if (fut.isDone())
                return false;

            jobCtx.holdcc();

            fut.listen(lsnr);

            return true;
        }

        /** {@inheritDoc} */
        @Override protected IgniteBiTuple<Integer, Integer> run(final String cacheName) {
            if (futs[0] == null || futs[1] == null || futs[2] == null) {
                IgniteCache cache = ignite.cache(cacheName);

                if (futs[0] == null && callAsync(new VisorCacheSizeCallable(cache), 0))
                    return null;

                if (futs[1] == null && callAsync(new VisorCacheClearCallable(cache), 1))
                    return null;

                if (futs[2] == null && callAsync(new VisorCacheSizeCallable(cache), 2))
                    return null;
            }

            assert futs[0].isDone() && futs[1].isDone() && futs[2].isDone();

            return new IgniteBiTuple<>(futs[0].get(), futs[2].get());
        }

        /** {@inheritDoc} */
        @Override public String toString() {
            return S.toString(VisorCacheClearJob.class, this);
        }
    }

    /**
     * Callable to get cache size.
     */
    @GridInternal
    private static class VisorCacheSizeCallable implements IgniteCallable<Integer> {
        /** */
        private static final long serialVersionUID = 0L;

        /** */
        private final IgniteCache cache;

        /**
         * @param cache Cache to take size from.
         */
        private VisorCacheSizeCallable(IgniteCache cache) {
            this.cache = cache;
        }

        /** {@inheritDoc} */
        @Override public Integer call() throws Exception {
            return cache.size(CachePeekMode.PRIMARY);
        }
    }

    /**
     * Callable to clear cache.
     */
    @GridInternal
    private static class VisorCacheClearCallable implements IgniteCallable<Integer> {
        /** */
        private static final long serialVersionUID = 0L;

        /** */
        private final IgniteCache cache;

        /**
         * @param cache Cache to clear.
         */
        private VisorCacheClearCallable(IgniteCache cache) {
            this.cache = cache;
        }

        /** {@inheritDoc} */
        @Override public Integer call() throws Exception {
            cache.clear();

            return 0;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <color name="actionbar_separator">#000</color>
    <color name="actionbar_title">#000</color>
    <color name="actionbar_background_start">#00cbe86b</color>
    <color name="actionbar_background_end">#00cbe86b</color>
    <color name="actionbar_background_item_pressed_start">#44ffffff</color>
    <color name="actionbar_background_item_pressed_end">#44ffffff</color>
    <color name="list_background">#1C140D</color>
    <color name="slot_right_pane">#9c000000</color>
    <color name="slot_right_pane_text_color">#3e3e3e</color>
    <color name="navigation_item_text_color">#3e3e3e</color>
    <color name="navigation_item_seperator">#88ffffff</color>
    <color name="slot_right_pane_secondary_text_color">#424242</color>
    <color name="slot_item_title_color">#000</color>
    <color name="slot_item_desc_color">#454545</color>
    <color name="session_title_color">#000</color>
    <color name="session_author_color">#454545</color>
    <color name="slot_time_background_pressed_color">#dddddd</color>
    <color name="slot_time_background_normal_color">#525252</color>

    <color name="slot_time_background_stroke_pressed_color">#00ffffff</color>
    <color name="slot_time_background_stroke_normal_color">#00ffffff</color>

    <color name="session_slot_title_background_normal_color">#fed904</color>
    <color name="session_slot_title_background_pressed_color">#E3C207</color>

    <color name="session_slot_desc_background_normal_color">#ffffff</color>
    <color name="session_slot_desc_background_pressed_color">#E3E3E3</color>

    <color name="updatelist_top_item">#444</color>
    <color name="updatelist_below_item">#444</color>

</resources>


text:
package org.mearnag.est;

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

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;

public class Locations extends SQLiteOpenHelper {
	public Locations(Context context) {
		super(context, "est_meta.db", null, 1);
	}
	public static final String TAG = "Locations";
	public static final String TABLE = "est_locations";
	public static final String TS = "ts";
	public static final String NAME = "name";
	public static final String TYPE = "location_type";
	public static final String ICON = "icon";
	public static final String[] COLUMNS = {TS,NAME,TYPE};

	@Override
	public void onCreate(SQLiteDatabase db) {
		String sql = "create table est_locations ( " + BaseColumns._ID
		+ " integer primary key autoincrement, ts integer key, name varchar(100), location_type varchar(100), icon varchar(150));";

		Log.v(TAG, "onCreate: executing:" + sql);
		db.execSQL(sql);
		//db.close();
		insertDefault(db,"Home","room","home");
		insertDefault(db,"Home (leaving)","room","home");
		insertDefault(db,"In Transit","non-place","transit");
		insertDefault(db,"Work","room","work");
		insertDefault(db,"Grocery Store","building","store");

	}
	public void insertDefault(SQLiteDatabase db, String name, String type, String icon) {
		Log.v(TAG,"insert("+name+","+type+","+icon+")");
		ContentValues values = new ContentValues();
		values.put("name", name);
		values.put("location_type", type);
		values.put("icon", icon);
		db.insert(TABLE, null, values);
	}
	public void insert(String name, String type, String icon) {
		Log.v(TAG,"insert("+name+","+type+","+icon+")");
		SQLiteDatabase db = getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("name", name);
		values.put("location_type", type);
		values.put("icon", icon);
		db.insert(TABLE, null, values);
	}
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		//Log.v(TAG, "onUpgrade!? oldVersion:" + oldVersion + " newVersion:" + newVersion);
	}
	//public List<String> locations() {
	public String[] locations() {
		SQLiteDatabase db = getReadableDatabase();
		Cursor cursor = db.query(TABLE, COLUMNS, null, null, null, null, null);
		String loc;
		//List<String> locs = new ArrayList<String>();
		String[] locs = new String[cursor.getCount()];
		if (cursor.getCount() == 0) {
			Log.e(TAG,"locations found nothing!");
		} else {
			cursor.moveToFirst();
			int location_i = cursor.getColumnIndex(NAME);
			loc = cursor.getString(location_i);
			Log.v(TAG,"loc:"+loc+" count:"+cursor.getCount());
			//locs.add(loc);
			locs[cursor.getPosition()] = loc;
			while (cursor.moveToNext()) {
				loc = cursor.getString(location_i);
				Log.v(TAG,"loc:"+loc+" count:"+cursor.getCount());
				locs[cursor.getPosition()] = loc;
				//locs.add(loc);
			}
		}
    	cursor.close();
    	db.close();
    	return locs;
	}
}


text:
package com.breadwallet.presenter.entities;

import android.view.View;

public class BRSettingsItem {

    public boolean isSection;
    public String title;
    public String addonText;
    public View.OnClickListener listener;

    public BRSettingsItem(String title, String addonText, View.OnClickListener listener, boolean isSection) {
        this.title = title;
        this.addonText = addonText;
        this.listener = listener;
        this.isSection = isSection;
    }

}


text:
import * as $ from 'jquery';
import addFlashMessage from './addFlashMessage';

$(() => {
  const flashUl = document.querySelector('.teams__flashMessages') as HTMLUListElement;
  const changeRoleLinks = document.querySelectorAll('.teams__changeMemberRole');
  changeRoleLinks.forEach(item => {
    item.addEventListener('mousedown', (event) => {
      const target = event.target as HTMLAnchorElement;
      const roleName = target.getAttribute('data-role');
      const parentElement = target.closest('div');
      if (roleName === null) return;
      if (parentElement === null) return;

      if (parentElement.getAttribute('data-url')) {
        const parent = target.closest('td') as HTMLTableDataCellElement;
        const name = (parent?.previousElementSibling?.previousElementSibling?.textContent)?.trim() || '';
        const closeText = flashUl.getAttribute('data-close') || 'Close';
        const changeRoleText = flashUl.getAttribute('data-roleChange') || `Role changed to ${roleName}`;
        const url = parentElement!.getAttribute('data-url')?.replace('stand-in', roleName) || '';

        fetch(url)
          .then(response => response.json())
          .then(data => {
            if (data !== 'ok') {
              addFlashMessage(flashUl, data, 'error', closeText);
              return;
            }
            const message = changeRoleText.replace('<role>', roleName).replace('<name>', name);
            addFlashMessage(flashUl, message, 'info', closeText);
            parent.querySelectorAll('span').forEach(role => {
              role.classList.add('hidden');
            });
            const newRole = parent.querySelector(`.role__${roleName}`);
            if (newRole) newRole.classList.remove('hidden');
          })
          .catch(error => {
            addFlashMessage(flashUl, error.message, 'error', closeText);
          });
      } else {
        const parent = target.closest('.roles') as HTMLDivElement;
        const field = parent.querySelector('input');
        if (!field) return;
        field.setAttribute('value', roleName);
        parent.querySelectorAll('span').forEach(role => {
          role.classList.add('hidden');
        });
        const newRole = parent.querySelector(`.role__${roleName}`);
        if (newRole) newRole.classList.remove('hidden');
      }
    });
  });
});


text:
var configuration = GetConfiguration();

Log.Logger = CreateSerilogLogger(configuration);

try
{
    Log.Information("Configuring web host ({ApplicationContext})...", Program.AppName);
    var host = BuildWebHost(configuration, args);

    LogPackagesVersionInfo();

    Log.Information("Starting web host ({ApplicationContext})...", Program.AppName);
    host.Run();

    return 0;
}
catch (Exception ex)
{
    Log.Fatal(ex, "Program terminated unexpectedly ({ApplicationContext})!", Program.AppName);
    return 1;
}
finally
{
    Log.CloseAndFlush();
}

IWebHost BuildWebHost(IConfiguration configuration, string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .CaptureStartupErrors(false)
        .ConfigureAppConfiguration(x => x.AddConfiguration(configuration))
        .UseStartup<Startup>()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseSerilog()
        .Build();

Serilog.ILogger CreateSerilogLogger(IConfiguration configuration)
{
    var seqServerUrl = configuration["Serilog:SeqServerUrl"];
    var logstashUrl = configuration["Serilog:LogstashgUrl"];
    return new LoggerConfiguration()
        .MinimumLevel.Verbose()
        .Enrich.WithProperty("ApplicationContext", Program.AppName)
        .Enrich.FromLogContext()
        .WriteTo.Console()
        .WriteTo.Seq(string.IsNullOrWhiteSpace(seqServerUrl) ? "http://seq" : seqServerUrl)
        .WriteTo.Http(string.IsNullOrWhiteSpace(logstashUrl) ? "http://logstash:8080" : logstashUrl)
        .ReadFrom.Configuration(configuration)
        .CreateLogger();
}

IConfiguration GetConfiguration()
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddEnvironmentVariables();

    var config = builder.Build();

    if (config.GetValue<bool>("UseVault", false))
    {
        TokenCredential credential = new ClientSecretCredential(
            config["Vault:TenantId"],
            config["Vault:ClientId"],
            config["Vault:ClientSecret"]);
        builder.AddAzureKeyVault(new Uri($"https://{config["Vault:Name"]}.vault.azure.net/"), credential);
    }

    return builder.Build();
}

string GetVersion(Assembly assembly)
{
    try
    {
        return $"{assembly.GetCustomAttribute<AssemblyFileVersionAttribute>()?.Version} ({assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion.Split()[0]})";
    }
    catch
    {
        return string.Empty;
    }
}

void LogPackagesVersionInfo()
{
    var assemblies = new List<Assembly>();

    foreach (var dependencyName in typeof(Program).Assembly.GetReferencedAssemblies())
    {
        try
        {
            // Try to load the referenced assembly...
            assemblies.Add(Assembly.Load(dependencyName));
        }
        catch
        {
            // Failed to load assembly. Skip it.
        }
    }

    var versionList = assemblies.Select(a => $"-{a.GetName().Name} - {GetVersion(a)}").OrderBy(value => value);

    Log.Logger.ForContext("PackageVersions", string.Join("\n", versionList)).Information("Package versions ({ApplicationContext})", Program.AppName);
}

public partial class Program
{
    private static readonly string _namespace = typeof(Startup).Namespace;
    public static readonly string AppName = _namespace;
}


text:
#import <DVTFoundation/DTDKTeamBasedService.h>

@interface DTDKDeleteShoeboxIDService : DTDKTeamBasedService
{
}

+ (id)serviceForTeam:(id)arg1 andPlatform:(id)arg2 andShoeboxIdId:(id)arg3;

@end


text:
/*
 * Spring ESPN
 */
package com.infinitemule.espn.common.lang;

/**
 * Common functionality for working with Number types
 */
public class Numbers {

  /**
   *
   */
  public static Boolean isPresent(Integer i) {

    if(i == null) {
      return false;
    }

    return  true;
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>de.uni-wuerzburg.info3</groupId>
    <artifactId>ofcprobe</artifactId>
    <version>1.0.5-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>14.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.servicemix.bundles</groupId>
            <artifactId>org.apache.servicemix.bundles.snmp4j</artifactId>
            <version>2.1.0_2</version>
            <exclusions>
                <exclusion>
                    <artifactId>log4j</artifactId>
                    <groupId>log4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-math3</artifactId>
            <version>3.2</version>
        </dependency>
        <dependency>
            <groupId>org.jdom</groupId>
            <artifactId>jdom2</artifactId>
            <version>2.0.5</version>
        </dependency>
        <dependency>
            <groupId>org.openflow</groupId>
            <artifactId>openflowj</artifactId>
            <version>1.0.2</version>
        </dependency>
        <dependency>
            <groupId>cn.seed.pcap</groupId>
            <artifactId>pcapsimpleparser</artifactId>
            <version>BETA1.0</version>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <netbeans.hint.license>gpl30</netbeans.hint.license>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>de.uniwuerzburg.info3.ofcprobe.vswitch.main.Main</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>

            <plugin>
                <groupId>com.jolira</groupId>
                <artifactId>onejar-maven-plugin</artifactId>
                <version>1.4.4</version>
                <executions>
                    <execution>
                        <configuration>
                            <!-- Optional, default is false -->
                            <attachToBuild>true</attachToBuild>
                            <!-- Optional, default is "onejar" -->
                            <classifier>onejar</classifier>
                        </configuration>
                        <goals>
                            <goal>one-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>ofcproberepo</id>
            <name>Project internal repo</name>
            <url>file://${project.basedir}/lib</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>onejar-maven-plugin.googlecode.com</id>
            <url>http://onejar-maven-plugin.googlecode.com/svn/mavenrepo</url>
        </pluginRepository>
    </pluginRepositories>
</project>


text:
This is a bug fix release.

Check out the [0.7.1 milestone](https://github.com/HubSpot/Singularity/issues?q=milestone%3A0.7.1+is%3Aclosed) to see bugfixes in detail.

- [#1034](https://github.com/HubSpot/Singularity/pull/1034) Change package.json 'vex' dependency to 'vex-js'
- [#1049](https://github.com/HubSpot/Singularity/pull/1049) Don't set shell if arguments list is empty, ability to override shell
- [#1050](https://github.com/HubSpot/Singularity/pull/1050) Add polyfills for Object.assign and Promise


text:
package org.intellij.plugins.relaxNG;

import com.intellij.testFramework.fixtures.CodeInsightTestFixture;
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory;
import org.jetbrains.annotations.NotNull;

/*
* Created by IntelliJ IDEA.
* User: sweinreuter
* Date: 04.12.2007
*/
public abstract class AbstractIndexTest extends HighlightingTestBase {

  @Override
  protected final CodeInsightTestFixture createFixture(@NotNull IdeaTestFixtureFactory factory) {
    return createContentFixture(factory);
  }
}


text:
#ifndef BaseLib_Network_Session_h
#define BaseLib_Network_Session_h

#include "BaseLib/Network/AbstractConnection.h"
#include "BaseLib/Network/UdpConnection.h"
#include "BaseLib/Network/TcpConnection.h"
#include "BaseLib/Functors/Enumerator.h"
#include "BaseLib/Functors/Functor3.h"
#include <map>
#include <set>

namespace BaseLib {
namespace Network {

using BaseLib::Functors::Enumerator;
using BaseLib::Functors::Functor3;
using BaseLib::Functors::FunctionFunctor3;
using BaseLib::Functors::MethodFunctor3;
using BaseLib::Containers::Array;

/**

Protocol:

+-----------+
| uint32    | byteCount
+-----------+
| int16     | messageType
+-----------+
| int16     | requestId
+-----------+
| uint16    | sessionId
+-----------+
| uint16    | userId
+-----------+
|           |
| byteCount | sessionMessage
| -6 bytes  |
|           |
+-----------+

*/
class BL_EXPORT Session : public NonCopyable {
public:

	//                     userId messageSize messageDataInputStream
	typedef Functor3<void, int,   int,        const BinaryInputStream&> MessageListenerFunctor;

	typedef FunctionFunctor3<void, int, int, const BinaryInputStream&> MessageListenerFunctionFunctor;

	template<class C>
	class BL_EXPORT MessageListenerMethodFunctor : public MethodFunctor3<C, void, int, int, const BinaryInputStream&> {
	public:
		MessageListenerMethodFunctor(C* atObject, Method forMethod)
			: MethodFunctor3(atObject, forMethod)
		{
		}
	};

	Session(uint16 port, double defaultTimeout = 1.0);
	~Session();

	inline double getTimeout() const
	{
		return timeout;
	}

	void setTimeout(double newTimeout);

	// While not connected

	void addPotentialPeerAddress(const String& address);
	inline bool isActingAsGateway() const
	{
		return actingAsGateway;
	}
	void setActingAsGateway(bool actAsGateway = true);

	void findPeers();
	void findSessions();
	void enumSessionIds(const Enumerator<int>& enumerator) const;
	String getSessionName(int idOfSession) const;
	String getSessionType(int idOfSession) const;
	bool isSessionPasswordProtected(int idOfSession) const;

	void joinSession(int idOfSession, const String& ownUserName, const String& password = Empty());
	void startSession(const String& sessionName, const String& sessionType, const String& sessionPassword, const String& ownUserName);

	inline bool isConnected() const
	{
		return sessionId != 0 && userId != 0;
	}

	// While connected

	double getSessionTimeInSeconds() const;
	int getSessionId() const; // 0 if not joined
	String getSessionName() const;
	String getSessionType() const;

	inline int getUserId() const
	{
		return userId;
	}
	inline String getUserName() const
	{
		return userName;
	}

	void enumSessionUserIds(const Enumerator<int>& enumerator) const;
	String getSessionUserName(int forUserId) const;

	int beginSendMessage(int targetUserId, int messageType, int messageSize) const; // returns requestId
	int beginBroadcastMessage(int messageType, int messageSize) const; // returns requestId
	BinaryOutputStream& outputStream();
	const BinaryOutputStream& outputStream() const;
	void endSendMessage() const;

	bool beginReceiveMessage(int& sourceUserId, int& requestId, int& messageType, int& messageSize) const;
	BinaryInputStream& inputStream();
	const BinaryInputStream& inputStream() const;
	void readMessageToVoid(int messageSize) const;
	void endReceiveMessage() const;

	void setMessageListener(int messageType, const MessageListenerFunctor& functor);
	void receiveMessages() const;
	void receiveMessages(double maxTime) const;

	void kickSessionUser(int userId);
	void bannSessionUser(int userId);
	void leaveSession();

	inline double getSecondsBetweenIsAlivePings() const
	{
		return secondsBetweenIsAlivePings;
	}

	void setSecondsBetweenIsAlivePings(double newSecondsBetweenIsAlivePings);

private:

	// Peers

	typedef Array<IpAddress> PotentialPeerAddresses;
	PotentialPeerAddresses potentialPeerAddresses;

	enum PeerType {
		PEER_TYPE_BROADCASTABLE_UDP,
		PEER_TYPE_NON_BROADCASTABLE_UDP,
		PEER_TYPE_TCP
	};
	typedef std::map<IpAddress, PeerType> Peers;
	Peers peers;

	typedef std::set<IpAddress> Gateways;
	Gateways gateways;

	struct UserInfo {
		String name;
		IpAddress ipAddress;

		UserInfo(const String& newName = Empty(), const IpAddress& newIpAddress = IpAddress())
			: name(newName)
			, ipAddress(newIpAddress)
		{
		}
	};
	typedef std::map<uint16, UserInfo> UserInfos;

	struct SessionInfo {
		String name;
		String type;
		bool passwordProtected;

		UserInfos userInfos;

		SessionInfo(const String& newName = Empty(), const String& newType = Empty(), bool isPasswordProtected = false)
			: name(newName)
			, type(newType)
			, passwordProtected(isPasswordProtected)
			, userInfos()
		{
		}
	};
	typedef std::map<uint16, SessionInfo> SessionInfos;
	mutable SessionInfos sessionInfos;

	double timeForIsAlivePing;
	uint16 requestIdOfLastIsAlivePing;
	IpAddress ipAddressOfLastIsAlivePing;
	double secondsBetweenIsAlivePings;

	// Self

	uint16 port;
	double timeout;
	bool actingAsGateway;

	inline uint16 getNewRequestId() const
	{
		static uint16 requestId = 0;
		return requestId++;
	}

	int sessionId;
	int userId;
	String userName;
	SessionInfo currentSessionInfo;
	String sessionPassword;

	// Messages

	static const int PING_REQUEST_MESSAGE_SIZE;
	static const int PING_RESPONSE_MESSAGE_SIZE;
	static const int LEAVE_SESSION_MESSAGE_SIZE;
	static const int CHECK_PASSWORD_RESPONSE_MESSAGE_SIZE;

	enum MessageType {
		PING_REQUEST = -1, // void
		PING_RESPONSE = -2, // bool8 isGateway
		ENUM_SESSIONS_REQUEST = -3, // void
		ENUM_SESSIONS_RESPONSE = -4, // uint16 sessionCount[uint16 sessionId, char16 * sessionName, char16 * sessionType, bool8 passwordProtected, uint16 userCount[uint16 userId, char16 * userName, char16 * ipAddress]]
		CHECK_PASSWORD_REQUEST = -5, // char16 * password
		CHECK_PASSWORD_RESPONSE = -6, // bool8 passwordOk
		JOINING_SESSION_MESSAGE = -7, // char16 * userName
		LEAVING_SESSION_MESSAGE = -8, // void
		NEW_SESSION_STARTED_MESSAGE = -9 // uint16 sessionId, char16 * sessionName, char16 * sessionType, bool8 passwordProtected, char16 * startingUserName
	};

	UdpConnection broadcastUdpConnection;
	mutable AbstractConnection* currentInputConnection;

	typedef std::map<int, AbstractConnection*> SessionConnections; // int -> userId
	SessionConnections sessionConnections;

	typedef Array<AbstractConnection*> ConnectionsArray;
	ConnectionsArray broadcastConnections;
	ConnectionsArray receiveConnections;

	typedef Array<MessageListenerFunctor*> MessageListenerFunctors;
	MessageListenerFunctors messageListenerFunctors;

	mutable int currentSendConnectionsCount;
	mutable const AbstractConnection* const* currentSendConnections;
	mutable BinaryOutputStream currentOutputStream;

	// Utility

	struct Header {
		int16 messageType;
		uint16 requestId;
		uint16 sessionId;
		uint16 userId;

		Header(int16 newMessageType = 0, uint16 newRequestId = 0, uint16 newSessionId = 0, uint16 newUserId = 0)
			: messageType(newMessageType)
			, requestId(newRequestId)
			, sessionId(newSessionId)
			, userId(newUserId)
		{
		}
	};

	mutable int lastPeerIndex;
	AbstractConnection* createRandomSessionConnection(Socket::ProtocolType protocolType, uint16 idOfSession = 0) const;
	AbstractConnection* createRandomConnection(Socket::ProtocolType protocolType) const;
	AbstractConnection* createNextConnection(Socket::ProtocolType protocolType) const;
	bool isAddressInPeersMap(const IpAddress& ipAddress) const;
	void removePeer(int peerIndex);
	void removePeer(const IpAddress& peerIpAddress);
	void removeUserConnections(uint16 userIdToRemove, const IpAddress& peerIpAddress);
	void handleIsAlivePing(int messageSize, const Header& header);
	void respondToSessionMessages(int messageSize, Header& header);

	void beginSendMessageInternal(const AbstractConnection& connection, const Header& header, uint32 messageSize) const;
	int beginReceiveMessageInternal(const AbstractConnection& connection, Header& header) const;
	void readMessageToVoid(const BinaryInputStream& inputStream, int messageSize) const;

	uint16 getUnusedUserId() const;
	uint16 getUnusedSessionId() const;

};

} // namespace Network
} // namespace BaseLib

#endif // #ifndef BaseLib_Network_Session_h