text:
package integration_test

import (
	"archive/tar"
	"compress/gzip"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gbytes"
	"github.com/onsi/gomega/gexec"
	"github.com/onsi/gomega/ghttp"
	"github.com/vito/go-sse/sse"

	"github.com/concourse/atc"
	"github.com/concourse/atc/event"
)

var _ = Describe("Fly CLI", func() {
	var tmpdir string
	var buildDir string
	var taskConfigPath string

	var streaming chan struct{}
	var events chan atc.Event
	var uploadingBits <-chan struct{}
	var outputDir string

	var expectedPlan atc.Plan

	BeforeEach(func() {
		var err error
		tmpdir, err = ioutil.TempDir("", "fly-build-dir")
		Expect(err).NotTo(HaveOccurred())

		outputDir, err = ioutil.TempDir("", "fly-task-output")
		Expect(err).NotTo(HaveOccurred())

		buildDir = filepath.Join(tmpdir, "fixture")

		err = os.Mkdir(buildDir, 0755)
		Expect(err).NotTo(HaveOccurred())

		taskConfigPath = filepath.Join(buildDir, "task.yml")

		err = ioutil.WriteFile(
			taskConfigPath,
			[]byte(`---
platform: some-platform

image: ubuntu

inputs:
- name: fixture

outputs:
- name: some-dir

params:
  FOO: bar
  BAZ: buzz
  X: 1

run:
  path: /bin/sh
  args:
    - -c
    - echo some-content > some-dir/a-file

`),
			0644,
		)
		Expect(err).NotTo(HaveOccurred())

		streaming = make(chan struct{})
		events = make(chan atc.Event)

		planFactory := atc.NewPlanFactory(0)

		expectedPlan = planFactory.NewPlan(atc.EnsurePlan{
			Step: planFactory.NewPlan(atc.DoPlan{
				planFactory.NewPlan(atc.AggregatePlan{
					planFactory.NewPlan(atc.GetPlan{
						Name: filepath.Base(buildDir),
						Type: "archive",
						Source: atc.Source{
							"uri": atcServer.URL() + "/api/v1/pipes/input-pipe-id",
						},
					}),
				}),
				planFactory.NewPlan(atc.TaskPlan{
					Name: "one-off",
					Config: &atc.TaskConfig{
						Platform: "some-platform",
						Image:    "ubuntu",
						Inputs: []atc.TaskInputConfig{
							{Name: "fixture"},
						},
						Outputs: []atc.TaskOutputConfig{
							{Name: "some-dir"},
						},
						Params: map[string]string{
							"FOO": "bar",
							"BAZ": "buzz",
							"X":   "1",
						},
						Run: atc.TaskRunConfig{
							Path: "/bin/sh",
							Args: []string{"-c", "echo some-content > some-dir/a-file"},
						},
					},
				}),
			}),
			Next: planFactory.NewPlan(atc.AggregatePlan{
				planFactory.NewPlan(atc.PutPlan{
					Name: "some-dir",
					Type: "archive",
					Source: atc.Source{
						"uri": atcServer.URL() + "/api/v1/pipes/output-pipe-id",
					},
					Params: atc.Params{
						"directory": "some-dir",
					},
				}),
			}),
		})
	})

	AfterEach(func() {
		err := os.RemoveAll(tmpdir)
		Expect(err).NotTo(HaveOccurred())

		err = os.RemoveAll(outputDir)
		Expect(err).NotTo(HaveOccurred())
	})

	JustBeforeEach(func() {
		uploading := make(chan struct{})
		uploadingBits = uploading

		atcServer.AppendHandlers(
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("POST", "/api/v1/pipes"),
				ghttp.RespondWithJSONEncoded(http.StatusCreated, atc.Pipe{
					ID:       "input-pipe-id",
					ReadURL:  atcServer.URL() + "/api/v1/pipes/input-pipe-id",
					WriteURL: atcServer.URL() + "/api/v1/pipes/input-pipe-id",
				}),
			),
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("POST", "/api/v1/pipes"),
				ghttp.RespondWithJSONEncoded(http.StatusCreated, atc.Pipe{
					ID:       "output-pipe-id",
					ReadURL:  atcServer.URL() + "/api/v1/pipes/output-pipe-id",
					WriteURL: atcServer.URL() + "/api/v1/pipes/output-pipe-id",
				}),
			),
		)
		atcServer.RouteToHandler("POST", "/api/v1/builds",
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("POST", "/api/v1/builds"),
				VerifyPlan(expectedPlan),
				func(w http.ResponseWriter, r *http.Request) {
					http.SetCookie(w, &http.Cookie{
						Name:    "Some-Cookie",
						Value:   "some-cookie-data",
						Path:    "/",
						Expires: time.Now().Add(1 * time.Minute),
					})
				},
				ghttp.RespondWith(201, `{"id":128}`),
			),
		)
		atcServer.RouteToHandler("GET", "/api/v1/builds/128/events",
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/api/v1/builds/128/events"),
				func(w http.ResponseWriter, r *http.Request) {
					flusher := w.(http.Flusher)

					w.Header().Add("Content-Type", "text/event-stream; charset=utf-8")
					w.Header().Add("Cache-Control", "no-cache, no-store, must-revalidate")
					w.Header().Add("Connection", "keep-alive")

					w.WriteHeader(http.StatusOK)

					flusher.Flush()

					close(streaming)

					id := 0

					for e := range events {
						payload, err := json.Marshal(event.Message{Event: e})
						Expect(err).NotTo(HaveOccurred())

						event := sse.Event{
							ID:   fmt.Sprintf("%d", id),
							Name: "event",
							Data: payload,
						}

						err = event.Write(w)
						Expect(err).NotTo(HaveOccurred())

						flusher.Flush()

						id++
					}

					err := sse.Event{
						Name: "end",
					}.Write(w)
					Expect(err).NotTo(HaveOccurred())
				},
			),
		)
		atcServer.RouteToHandler("PUT", "/api/v1/pipes/input-pipe-id",
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("PUT", "/api/v1/pipes/input-pipe-id"),
				func(w http.ResponseWriter, req *http.Request) {
					close(uploading)

					gr, err := gzip.NewReader(req.Body)
					Expect(err).NotTo(HaveOccurred())

					tr := tar.NewReader(gr)

					hdr, err := tr.Next()
					Expect(err).NotTo(HaveOccurred())

					Expect(hdr.Name).To(Equal("./"))

					hdr, err = tr.Next()
					Expect(err).NotTo(HaveOccurred())

					Expect(hdr.Name).To(MatchRegexp("(./)?task.yml$"))
				},
				ghttp.RespondWith(200, ""),
			),
		)
		atcServer.RouteToHandler("GET", "/api/v1/pipes/output-pipe-id",
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/api/v1/pipes/output-pipe-id"),
				func(w http.ResponseWriter, req *http.Request) {
					gw := gzip.NewWriter(w)

					tw := tar.NewWriter(gw)

					tarContents := []byte("tar-contents")

					err := tw.WriteHeader(&tar.Header{
						Name: "some-file",
						Mode: 0644,
						Size: int64(len(tarContents)),
					})
					Expect(err).NotTo(HaveOccurred())

					_, err = tw.Write(tarContents)
					Expect(err).NotTo(HaveOccurred())

					err = tw.Close()
					Expect(err).NotTo(HaveOccurred())

					err = gw.Close()
					Expect(err).NotTo(HaveOccurred())
				},
			),
		)
	})

	Context("when running with --output", func() {
		Context("when the task specifies those outputs", func() {
			It("downloads the tasks output to the directory provided", func() {
				flyCmd := exec.Command(flyPath, "-t", targetName, "e", "-c", taskConfigPath, "--output", "some-dir="+outputDir)
				flyCmd.Dir = buildDir

				sess, err := gexec.Start(flyCmd, GinkgoWriter, GinkgoWriter)
				Expect(err).NotTo(HaveOccurred())

				// sync with after create
				Eventually(streaming, 5.0).Should(BeClosed())

				close(events)

				<-sess.Exited
				Expect(sess.ExitCode()).To(Equal(0))

				outputFiles, err := ioutil.ReadDir(outputDir)
				Expect(err).NotTo(HaveOccurred())

				Expect(outputFiles).To(HaveLen(1))
				Expect(outputFiles[0].Name()).To(Equal("some-file"))

				data, err := ioutil.ReadFile(filepath.Join(outputDir, outputFiles[0].Name()))
				Expect(err).NotTo(HaveOccurred())
				Expect(data).To(Equal([]byte("tar-contents")))
			})
		})

		Context("when the task does not specify those outputs", func() {
			It("exits 1", func() {
				flyCmd := exec.Command(flyPath, "-t", targetName, "e", "-c", taskConfigPath, "-o", "wrong-output=wrong-path")
				flyCmd.Dir = buildDir

				sess, err := gexec.Start(flyCmd, GinkgoWriter, GinkgoWriter)
				Expect(err).NotTo(HaveOccurred())

				Eventually(sess.Err).Should(gbytes.Say("error: unknown output 'wrong-output'"))

				<-sess.Exited
				Expect(sess.ExitCode()).To(Equal(1))
			})
		})
	})
})


text:
package links_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"testing"
)

func TestLinks(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Links Suite")
}

redpajama_set_name: RedPajamaGithub


text:
from six import PY3

from functools import wraps

from datetime import datetime, timedelta, tzinfo

ZERO = timedelta(0)

__all__ = ['tzname_in_python2', 'enfold']

def tzname_in_python2(namefunc):
    """Change unicode output into bytestrings in Python 2

    tzname() API changed in Python 3. It used to return bytes, but was changed
    to unicode strings
    """
    def adjust_encoding(*args, **kwargs):
        name = namefunc(*args, **kwargs)
        if name is not None and not PY3:
            name = name.encode()

        return name

    return adjust_encoding

# The following is adapted from Alexander Belopolsky's tz library
# https://github.com/abalkin/tz
if hasattr(datetime, 'fold'):
    # This is the pre-python 3.6 fold situation
    def enfold(dt, fold=1):
        """
        Provides a unified interface for assigning the ``fold`` attribute to
        datetimes both before and after the implementation of PEP-495.

        :param fold:
            The value for the ``fold`` attribute in the returned datetime. This
            should be either 0 or 1.

        :return:
            Returns an object for which ``getattr(dt, 'fold', 0)`` returns
            ``fold`` for all versions of Python. In versions prior to
            Python 3.6, this is a ``_DatetimeWithFold`` object, which is a
            subclass of :py:class:`datetime.datetime` with the ``fold``
            attribute added, if ``fold`` is 1.

        .. versionadded:: 2.6.0
        """
        return dt.replace(fold=fold)

else:
    class _DatetimeWithFold(datetime):
        """
        This is a class designed to provide a PEP 495-compliant interface for
        Python versions before 3.6. It is used only for dates in a fold, so
        the ``fold`` attribute is fixed at ``1``.

        .. versionadded:: 2.6.0
        """
        __slots__ = ()

        def replace(self, *args, **kwargs):
            """
            Return a datetime with the same attributes, except for those
            attributes given new values by whichever keyword arguments are
            specified. Note that tzinfo=None can be specified to create a naive
            datetime from an aware datetime with no conversion of date and time
            data.

            This is reimplemented in ``_DatetimeWithFold`` because pypy3 will
            return a ``datetime.datetime`` even if ``fold`` is unchanged.
            """
            argnames = (
                'year', 'month', 'day', 'hour', 'minute', 'second',
                'microsecond', 'tzinfo'
            )

            for arg, argname in zip(args, argnames):
                if argname in kwargs:
                    raise TypeError('Duplicate argument: {}'.format(argname))

                kwargs[argname] = arg

            for argname in argnames:
                if argname not in kwargs:
                    kwargs[argname] = getattr(self, argname)

            dt_class = self.__class__ if kwargs.get('fold', 1) else datetime

            return dt_class(**kwargs)

        @property
        def fold(self):
            return 1

    def enfold(dt, fold=1):
        """
        Provides a unified interface for assigning the ``fold`` attribute to
        datetimes both before and after the implementation of PEP-495.

        :param fold:
            The value for the ``fold`` attribute in the returned datetime. This
            should be either 0 or 1.

        :return:
            Returns an object for which ``getattr(dt, 'fold', 0)`` returns
            ``fold`` for all versions of Python. In versions prior to
            Python 3.6, this is a ``_DatetimeWithFold`` object, which is a
            subclass of :py:class:`datetime.datetime` with the ``fold``
            attribute added, if ``fold`` is 1.

        .. versionadded:: 2.6.0
        """
        if getattr(dt, 'fold', 0) == fold:
            return dt

        args = dt.timetuple()[:6]
        args += (dt.microsecond, dt.tzinfo)

        if fold:
            return _DatetimeWithFold(*args)
        else:
            return datetime(*args)

def _validate_fromutc_inputs(f):
    """
    The CPython version of ``fromutc`` checks that the input is a ``datetime``
    object and that ``self`` is attached as its ``tzinfo``.
    """
    @wraps(f)
    def fromutc(self, dt):
        if not isinstance(dt, datetime):
            raise TypeError("fromutc() requires a datetime argument")
        if dt.tzinfo is not self:
            raise ValueError("dt.tzinfo is not self")

        return f(self, dt)

    return fromutc

class _tzinfo(tzinfo):
    """
    Base class for all ``dateutil`` ``tzinfo`` objects.
    """

    def is_ambiguous(self, dt):
        """
        Whether or not the "wall time" of a given datetime is ambiguous in this
        zone.

        :param dt:
            A :py:class:`datetime.datetime`, naive or time zone aware.

        :return:
            Returns ``True`` if ambiguous, ``False`` otherwise.

        .. versionadded:: 2.6.0
        """

        dt = dt.replace(tzinfo=self)

        wall_0 = enfold(dt, fold=0)
        wall_1 = enfold(dt, fold=1)

        same_offset = wall_0.utcoffset() == wall_1.utcoffset()
        same_dt = wall_0.replace(tzinfo=None) == wall_1.replace(tzinfo=None)

        return same_dt and not same_offset

    def _fold_status(self, dt_utc, dt_wall):
        """
        Determine the fold status of a "wall" datetime, given a representation
        of the same datetime as a (naive) UTC datetime. This is calculated based
        on the assumption that ``dt.utcoffset() - dt.dst()`` is constant for all
        datetimes, and that this offset is the actual number of hours separating
        ``dt_utc`` and ``dt_wall``.

        :param dt_utc:
            Representation of the datetime as UTC

        :param dt_wall:
            Representation of the datetime as "wall time". This parameter must
            either have a `fold` attribute or have a fold-naive
            :class:`datetime.tzinfo` attached, otherwise the calculation may
            fail.
        """
        if self.is_ambiguous(dt_wall):
            delta_wall = dt_wall - dt_utc
            _fold = int(delta_wall == (dt_utc.utcoffset() - dt_utc.dst()))
        else:
            _fold = 0

        return _fold

    def _fold(self, dt):
        return getattr(dt, 'fold', 0)

    def _fromutc(self, dt):
        """
        Given a timezone-aware datetime in a given timezone, calculates a
        timezone-aware datetime in a new timezone.

        Since this is the one time that we *know* we have an unambiguous
        datetime object, we take this opportunity to determine whether the
        datetime is ambiguous and in a "fold" state (e.g. if it's the first
        occurence, chronologically, of the ambiguous datetime).

        :param dt:
            A timezone-aware :class:`datetime.datetime` object.
        """

        # Re-implement the algorithm from Python's datetime.py
        dtoff = dt.utcoffset()
        if dtoff is None:
            raise ValueError("fromutc() requires a non-None utcoffset() "
                             "result")

        # The original datetime.py code assumes that `dst()` defaults to
        # zero during ambiguous times. PEP 495 inverts this presumption, so
        # for pre-PEP 495 versions of python, we need to tweak the algorithm.
        dtdst = dt.dst()
        if dtdst is None:
            raise ValueError("fromutc() requires a non-None dst() result")
        delta = dtoff - dtdst

        dt += delta
        # Set fold=1 so we can default to being in the fold for
        # ambiguous dates.
        dtdst = enfold(dt, fold=1).dst()
        if dtdst is None:
            raise ValueError("fromutc(): dt.dst gave inconsistent "
                             "results; cannot convert")
        return dt + dtdst

    @_validate_fromutc_inputs
    def fromutc(self, dt):
        """
        Given a timezone-aware datetime in a given timezone, calculates a
        timezone-aware datetime in a new timezone.

        Since this is the one time that we *know* we have an unambiguous
        datetime object, we take this opportunity to determine whether the
        datetime is ambiguous and in a "fold" state (e.g. if it's the first
        occurance, chronologically, of the ambiguous datetime).

        :param dt:
            A timezone-aware :class:`datetime.datetime` object.
        """
        dt_wall = self._fromutc(dt)

        # Calculate the fold status given the two datetimes.
        _fold = self._fold_status(dt, dt_wall)

        # Set the default fold value for ambiguous dates
        return enfold(dt_wall, fold=_fold)

class tzrangebase(_tzinfo):
    """
    This is an abstract base class for time zones represented by an annual
    transition into and out of DST. Child classes should implement the following
    methods:

        * ``__init__(self, *args, **kwargs)``
        * ``transitions(self, year)`` - this is expected to return a tuple of
          datetimes representing the DST on and off transitions in standard
          time.

    A fully initialized ``tzrangebase`` subclass should also provide the
    following attributes:
        * ``hasdst``: Boolean whether or not the zone uses DST.
        * ``_dst_offset`` / ``_std_offset``: :class:`datetime.timedelta` objects
          representing the respective UTC offsets.
        * ``_dst_abbr`` / ``_std_abbr``: Strings representing the timezone short
          abbreviations in DST and STD, respectively.
        * ``_hasdst``: Whether or not the zone has DST.

    .. versionadded:: 2.6.0
    """
    def __init__(self):
        raise NotImplementedError('tzrangebase is an abstract base class')

    def utcoffset(self, dt):
        isdst = self._isdst(dt)

        if isdst is None:
            return None
        elif isdst:
            return self._dst_offset
        else:
            return self._std_offset

    def dst(self, dt):
        isdst = self._isdst(dt)

        if isdst is None:
            return None
        elif isdst:
            return self._dst_base_offset
        else:
            return ZERO

    @tzname_in_python2
    def tzname(self, dt):
        if self._isdst(dt):
            return self._dst_abbr
        else:
            return self._std_abbr

    def fromutc(self, dt):
        """ Given a datetime in UTC, return local time """
        if not isinstance(dt, datetime):
            raise TypeError("fromutc() requires a datetime argument")

        if dt.tzinfo is not self:
            raise ValueError("dt.tzinfo is not self")

        # Get transitions - if there are none, fixed offset
        transitions = self.transitions(dt.year)
        if transitions is None:
            return dt + self.utcoffset(dt)

        # Get the transition times in UTC
        dston, dstoff = transitions

        dston -= self._std_offset
        dstoff -= self._std_offset

        utc_transitions = (dston, dstoff)
        dt_utc = dt.replace(tzinfo=None)

        isdst = self._naive_isdst(dt_utc, utc_transitions)

        if isdst:
            dt_wall = dt + self._dst_offset
        else:
            dt_wall = dt + self._std_offset

        _fold = int(not isdst and self.is_ambiguous(dt_wall))

        return enfold(dt_wall, fold=_fold)

    def is_ambiguous(self, dt):
        """
        Whether or not the "wall time" of a given datetime is ambiguous in this
        zone.

        :param dt:
            A :py:class:`datetime.datetime`, naive or time zone aware.

        :return:
            Returns ``True`` if ambiguous, ``False`` otherwise.

        .. versionadded:: 2.6.0
        """
        if not self.hasdst:
            return False

        start, end = self.transitions(dt.year)

        dt = dt.replace(tzinfo=None)
        return (end <= dt < end + self._dst_base_offset)

    def _isdst(self, dt):
        if not self.hasdst:
            return False
        elif dt is None:
            return None

        transitions = self.transitions(dt.year)

        if transitions is None:
            return False

        dt = dt.replace(tzinfo=None)

        isdst = self._naive_isdst(dt, transitions)

        # Handle ambiguous dates
        if not isdst and self.is_ambiguous(dt):
            return not self._fold(dt)
        else:
            return isdst

    def _naive_isdst(self, dt, transitions):
        dston, dstoff = transitions

        dt = dt.replace(tzinfo=None)

        if dston < dstoff:
            isdst = dston <= dt < dstoff
        else:
            isdst = not dstoff <= dt < dston

        return isdst

    @property
    def _dst_base_offset(self):
        return self._dst_offset - self._std_offset

    __hash__ = None

    def __ne__(self, other):
        return not (self == other)

    def __repr__(self):
        return "%s(...)" % self.__class__.__name__

    __reduce__ = object.__reduce__


text:
/**
 *
Immutable POJOs which provide native object representation of the JSON
 * returned by remote API calls.

 *
 *
All classes must implement the
 * {@link travel.izi.api.model.IZITravelEntity} interface.

 */
package travel.izi.api.model.entity;


text:
package org.kuali.rice.xml.config.spring;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.kuali.common.util.metainf.model.MetaInfContext;
import org.kuali.common.util.metainf.model.MetaInfResource;
import org.kuali.common.util.metainf.model.MetaInfResourcePathComparator;
import org.kuali.common.util.metainf.service.MetaInfUtils;
import org.kuali.common.util.metainf.spring.MetaInfConfigUtils;
import org.kuali.common.util.metainf.spring.MetaInfContextsConfig;
import org.kuali.common.util.metainf.spring.MetaInfDataLocation;
import org.kuali.common.util.metainf.spring.MetaInfDataType;
import org.kuali.common.util.metainf.spring.MetaInfExecutableConfig;
import org.kuali.common.util.metainf.spring.MetaInfGroup;
import org.kuali.common.util.nullify.NullUtils;
import org.kuali.common.util.project.ProjectUtils;
import org.kuali.common.util.project.model.Build;
import org.kuali.common.util.project.model.Project;
import org.kuali.common.util.project.spring.AutowiredProjectConfig;
import org.kuali.common.util.spring.SpringUtils;
import org.kuali.common.util.spring.env.EnvironmentService;
import org.kuali.common.util.spring.service.SpringServiceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.io.File;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * Defines the configuration for creating the xml property files that define how the database is created.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
@Configuration
@Import({ AutowiredProjectConfig.class, MetaInfExecutableConfig.class, SpringServiceConfig.class })
public class RiceXmlConfig implements MetaInfContextsConfig {

    private static final Boolean DEFAULT_GENERATE_RELATIVE_PATHS = Boolean.TRUE;
    private static final String RELATIVE_KEY = MetaInfUtils.PROPERTY_PREFIX + ".xml.relative";
    private static final String PREFIX = "xml";
    private static final String INGEST_FILENAME = "ingest";

    // All paths must have the hardcoded separator to be consistent for deployment
    private static final String PATH_SEPARATOR = "/";

    private static final String INITIAL_XML_PATH = "initial-xml" + PATH_SEPARATOR + "2.3.0";
    private static final String UPGRADE_XML_PATH = "upgrades" + PATH_SEPARATOR + "*";
    private static final String ALL_XML_PATH = "**" + PATH_SEPARATOR + "*.xml";

    /**
     * The Spring environment.
     */
    @Autowired
    EnvironmentService env;

    /**
     * The Rice Maven project.
     */
    @Autowired
    Project project;

    /**
     * The build information.
     */
    @Autowired
    Build build;

    /**
     * {@inheritDoc}
     */
    @Override
    @Bean
    public List<MetaInfContext> metaInfContexts() {
        List<MetaInfContext> metaInfContexts = Lists.newArrayList();

        List<MetaInfDataType> types = Lists.newArrayList(MetaInfDataType.BOOTSTRAP, MetaInfDataType.DEMO, MetaInfDataType.TEST);
        List<String> qualifiers = Lists.newArrayList(INITIAL_XML_PATH, UPGRADE_XML_PATH);

        for (MetaInfDataType type : types) {
            for (String qualifier : qualifiers) {
                List<MetaInfContext> contexts = getMetaInfContexts(MetaInfGroup.OTHER, qualifier, type);
                metaInfContexts.addAll(contexts);
            }
        }

        return ImmutableList.copyOf(metaInfContexts);
    }

    /**
     * Creates a list of META-INF contexts for the given {@code group}, {@code qualifier}, and {@code type}.
     *
     * @param group the group of the data to create the contexts for
     * @param qualifier the prefix to add to the initial resource path
     * @param type the type of data to create the contexts for
     *
     * @return a list of META-INF contexts
     */
    protected List<MetaInfContext> getMetaInfContexts(MetaInfGroup group, String qualifier, MetaInfDataType type) {
        List<MetaInfContext> metaInfContexts = Lists.newArrayList();

        File scanDir = build.getOutputDir();
        String encoding = build.getEncoding();

        Comparator<MetaInfResource> comparator = new MetaInfResourcePathComparator();

        String includesKey = MetaInfConfigUtils.getIncludesKey(group, PREFIX);
        String excludesKey = MetaInfConfigUtils.getExcludesKey(group, PREFIX);

        Boolean relativePaths = env.getBoolean(RELATIVE_KEY, DEFAULT_GENERATE_RELATIVE_PATHS);

        List<String> pathQualifiers = MetaInfUtils.getQualifiers(scanDir, project, Lists.newArrayList(qualifier), Lists.<String> newArrayList());

        for (String pathQualifier : pathQualifiers) {
            File outputFile = MetaInfUtils.getOutputFile(project, build, Optional.of(pathQualifier),
                    Optional.<MetaInfDataLocation> absent(), Optional.of(type), INGEST_FILENAME);

            Map<MetaInfGroup, String> defaultIncludes = getDefaultIncludes(pathQualifier, type);
            Map<MetaInfGroup, String> defaultExcludes = getDefaultExcludes();
            List<String> includes = SpringUtils.getNoneSensitiveListFromCSV(env, includesKey, defaultIncludes.get(group));
            List<String> excludes = SpringUtils.getNoneSensitiveListFromCSV(env, excludesKey, defaultExcludes.get(group));

            MetaInfContext context = MetaInfContext.builder(outputFile, encoding, scanDir).comparator(comparator)
                    .includes(includes).excludes(excludes).relativePaths(relativePaths.booleanValue()).build();
            metaInfContexts.add(context);
        }

        return metaInfContexts;
    }

    /**
     * Generates the default mapping of included paths from the given {@code qualifier} and {@code type}.
     *
     * @param qualifier the prefix to add to the initial resource path
     * @param type the type of data to include
     *
     * @return the map of included paths
     */
    protected Map<MetaInfGroup, String> getDefaultIncludes(String qualifier, MetaInfDataType type) {
        Map<MetaInfGroup, String> defaultIncludes = Maps.newEnumMap(MetaInfGroup.class);

        String resourcePath = ProjectUtils.getResourcePath(project.getGroupId(), project.getArtifactId());
        List<String> paths = Lists.newArrayList(resourcePath, qualifier, type.name().toLowerCase(), ALL_XML_PATH);

        defaultIncludes.put(MetaInfGroup.OTHER, StringUtils.join(paths, PATH_SEPARATOR));

        return defaultIncludes;
    }

    /**
     * Generates the default mapping of excluded paths.
     *
     * @return the map of excluded paths
     */
    protected Map<MetaInfGroup, String> getDefaultExcludes() {
        Map<MetaInfGroup, String> defaultExcludes = Maps.newEnumMap(MetaInfGroup.class);

        defaultExcludes.put(MetaInfGroup.OTHER, NullUtils.NONE);

        return defaultExcludes;
    }

}


text:
package org.metaborg.spoofax.core.context;

import java.io.IOException;

import org.apache.commons.vfs2.FileObject;
import org.metaborg.core.context.ContextIdentifier;
import org.metaborg.core.context.ITemporaryContextInternal;
import org.metaborg.core.language.ILanguageImpl;
import org.metaborg.core.project.IProject;
import org.metaborg.runtime.task.engine.ITaskEngine;
import org.metaborg.util.concurrent.IClosableLock;
import org.metaborg.util.concurrent.NullClosableLock;
import org.spoofax.interpreter.library.index.IIndex;

import com.google.inject.Injector;

public class IndexTaskTemporaryContext implements ITemporaryContextInternal, IIndexTaskContext {
    private final IndexTaskContext context;

    public IndexTaskTemporaryContext(IndexTaskContext context) {
        this.context = context;
        init();
    }

    @Override public ContextIdentifier identifier() {
        return context.identifier();
    }

    @Override public FileObject location() {
        return context.location();
    }

    @Override
    public IProject project() {
        return context.project();
    }

    @Override public ILanguageImpl language() {
        return context.language();
    }

    @Override public Injector injector() {
        return context.injector();
    }

    @Override public IIndex index() {
        return context.index();
    }

    @Override public ITaskEngine taskEngine() {
        return context.taskEngine();
    }

    @Override public IClosableLock read() {
        // Temporary context is not thread-safe, no locking needed.
        return new NullClosableLock();
    }

    @Override public IClosableLock write() {
        // Temporary context is not thread-safe, no locking needed.
        return new NullClosableLock();
    }

    @Override public void persist() throws IOException {
        // Temporary context is not persisted.
    }

    @Override public void reset() throws IOException {
        // Temporary context is not persisted, no cleaning needed.
    }

    @Override public void init() {
        context.init();
    }

    @Override public void load() {
        // Temporary context is not persisted, no loading needed.
    }

    @Override public void unload() {
        context.unload();
    }

    @Override public void close() {
        unload();
    }
}


text:
<template>
    <require from="../../shared/components/poll/poll-component"></require>

    <div class="section--center mdl-grid">
        <poll-component
            class="mdl-card mdl-cell mdl-cell--4-col"
            repeat.for="poll of polls"
            poll.bind="poll"
        ></poll-component>
    </div>
</template>


text:
/*!
 @header       XXBFileHelper.h
 @abstract     只提供复杂的文件操作,简单的操作直接使用NSFileManager
 @author       xiaobing3@staff.sina.com.cn
 */

#import <Foundation/Foundation.h>

@interface XXBFileHelper : NSObject

/*!
 创建文件夹
 @param folderPath 路径
 @return 创建结果
 */
+ (BOOL)createFolder:(NSString *)folderPath;

/*!
 创建文件夹并设置iCloud属性
 @param folderPath      路径
 @param iCloudEnable    iCloud属性
 @return                创建结果
 */
+ (BOOL)createFolder:(NSString *)folderPath iCloudEnable:(BOOL)iCloudEnable;

/*!
 设置文件iCloud属性
 @param enable      iCloud属性
 @param path        路径
 @return            创建结果
 */
+ (BOOL)iCloudEnable:(BOOL)enable atPath:(NSString *)path;

/*!
 根据路径、文件名获得指定文件路径 如没有则创建
 @param rootPath   根路径 document、library、temp、cache等
 @param extendPath 延展路径
 @param fileName   文件名
 @return 指定文件路径
 */
+ (NSString *)getFullPathWithRootPath:(NSString *)rootPath extendPath:(NSString *)extendPath fileName:(NSString *)fileName;

/*!
 获取文件大小
 @param filePath    路径
 @return            文件大小
 */
+ (unsigned long long)getFileSize:(NSString*)filePath;

/*!
 获取剩余空间大小
 @return 剩余空间大小
 */
+ (unsigned long long)getFileSystemFreeSize;

/*!
 获取总空间大小
 @return 总空间大小
 */
+ (unsigned long long)getFileSystemTotalSize;

/*!
 获取文件夹大小
 @param folderPath  路径
 @return            文件夹大小
 */
+ (unsigned long long)getFolderSize:(NSString*)folderPath;

/*!
 查找文件
 @param rootPath    查找路径
 @param fileName    文件名
 @return            文件路径
 */
+ (NSString *)findFile:(NSString *)rootPath fileName:(NSString *)fileName;

/*!
 清空指定文件夹
 @param folderPath  需清空文件夹
 */
+ (void)removeAllFileAtPath:(NSString*)folderPath;
@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace equalizerapo_and_zune
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            // check that the Equalizer APO program is installed
            if (!VerifyRequisiteProgramsInstalled())
            {
                return;
            }

            // reset the filter upon exiting the program
            Application.ApplicationExit += ApplicationEnd;

            // start the program
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new form_main());
        }

        private static void ApplicationEnd(object sender, EventArgs e)
        {
            equalizerapo_api.UnsetEqualizer();
        }

        private static bool VerifyRequisiteProgramsInstalled()
        {
            try
            {
                File.GetEqualizerAPOPath();
            }
            catch (System.IO.FileNotFoundException e)
            {
                string message = "The application can't be opened. Requisite applications must first be installed.\n\n" +
                    "\"" + e.Message + "\"" +
                    "\n\nWould you like to go to this website now?";
                string caption = "Unable to start EqualizerAPO and Zune";
                DialogResult result =
                    MessageBox.Show(message, caption, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                if (result == DialogResult.OK)
                {
                    System.Diagnostics.Process.Start(
                        "http://sourceforge.net/projects/equalizerapo/");
                }
                return false;
            }
            return true;
        }
    }
}


text:
require 'flic/protocol/primitives'
require 'flic/protocol/primitives/enum'

module Flic
  module Protocol
    module Primitives
      # [:disconnected] Not currently an established connection, but will connect as soon as the button is pressed and it is in range as long as the connection channel hasn't been removed (and unless maximum number of concurrent connections has been reached or the bluetooth controller has been detached).
      # [:connected] The physical bluetooth connection has just been established and the server and the button are currently verifying each other. As soon as this is done, it will switch to the ready status.
      # [:ready] The verification is done and button events may now arrive.
    class ConnectionStatus < Enum
        option :disconnected
        option :connected
        option :ready
      end
    end
  end
end


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView android:text="@string/hello_world" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView" />

    <TextView android:text="@string/text_version" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textView"
        android:id="@+id/textVersion" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_call"
        android:id="@+id/button_call"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_helpdesk"
        android:id="@+id/button_helpdesk"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="147dp"
        android:onClick="contactHelpdesk"/>

</RelativeLayout>


text:
using System.Text.RegularExpressions;
using Glimpse.Core.Configuration;
using Xunit;

namespace Glimpse.Test.Core.Configuration
{
    public class RegexConverterShould
    {
        [Fact]
        public void ConvertStringToRegex()
        {
            var rString = ".+";

            var converter = new RegexConverter();

            var result = converter.ConvertFrom(rString);

            var rResult = result as Regex;

            Assert.NotNull(rResult);
            Assert.Equal(rString, rResult.ToString());
        }

        [Fact]
        public void ConvertRegexToString()
        {

            var rString = ".+";
            var regex = new Regex(rString);

            var converter = new RegexConverter();

            var result = converter.ConvertTo(regex, typeof (string));
            var sResult = result as string;

            Assert.False(string.IsNullOrEmpty(sResult));
            Assert.Equal(rString, sResult);
        }
    }
}


text:
package com.cube.storm.message.lib.receiver;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.cube.storm.MessageSettings;
import com.cube.storm.message.lib.resolver.MessageResolver;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

/**
 * Receiver class for receiving messages from Storm CMS. You should register a resolver via {@link MessageSettings#messageResolvers} using type
 * rather than override this class.
 *

 * Messages sent with the same "id" are ignored within the lifecycle of the application.
 *

 * You must include this class (or subclass of this class) in your application manifest to receive notifications.
 *

 *	<service
 *		android:name="com.cube.storm.message.lib.receiver.MessageReceiver"
 *		android:exported="false"
 *	>
 *		<intent-filter>
 *			<action android:name="com.google.firebase.MESSAGING_EVENT" />
 *		</intent-filter>
 *	</service>
 *

 *
 * @author Callum Taylor
 * @project LightningMessage
 */
public class MessageReceiver extends FirebaseMessagingService
{
	/**
	 * List of previously sent notification IDs to prevent duplicates from being shown
	 */
	protected static final Set<String> RECEIVED_IDS = new LinkedHashSet<String>();

	/**
	 * Default notification type with a simple message
	 */
	public static final String TYPE_DEFAULT = "default";

	@Override public void onMessageReceived(RemoteMessage remoteMessage)
	{
		super.onMessageReceived(remoteMessage);

		String type = remoteMessage.getData().get("type");
		handleNotification(type, remoteMessage.getData());
	}

	/**
	 * Implement this to handle the notifications sent from the server
	 *
	 * @param type The type of alert
	 * @param data The bundle data with the alert
	 *
	 * @return True if the notification was handled, false if not
	 */
	public boolean handleNotification(String type, Map<String, String> data)
	{
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

		if (prefs.contains("notifications_enabled") && !prefs.getBoolean("notifications_enabled", true))
		{
			return true;
		}

		if (data.containsKey("id"))
		{
			if (RECEIVED_IDS.contains(data.get("id")))
			{
				return true;
			}

			RECEIVED_IDS.add(data.get("id"));
		}

		try
		{
			MessageResolver messageResolver = MessageSettings.getInstance().getMessageResolvers().get(type);

			if (messageResolver != null)
			{
				return messageResolver.resolve(getApplicationContext(), data);
			}
		}
		catch (IllegalAccessError iar)
		{
			return false;
		}

		return false;
	}
}


text:
import { hasPermissions } from '@strapi/helper-plugin';
import getPluginSectionLinks from '../getPluginSectionLinks';

jest.mock('@strapi/helper-plugin');

describe('getPluginSectionLinks', () => {
  beforeEach(() => {
    hasPermissions.mockImplementation(() => Promise.resolve(true));
  });

  afterEach(() => {
    jest.resetAllMocks();
  });

  it('creates an array of boolean corresponding to the permission state', async () => {
    const userPermissions = [
      {
        id: 458,
        action: 'plugin::i18n.locale.read',
        subject: null,
        properties: {},
        conditions: [],
      },
      {
        id: 459,
        action: 'plugin::content-manager.explorer.create',
        subject: 'api::article.article',
        properties: {
          fields: ['Name'],
          locales: ['en'],
        },
        conditions: [],
      },
      {
        id: 460,
        action: 'plugin::content-manager.explorer.read',
        subject: 'api::article.article',
        properties: {
          fields: ['Name'],
          locales: ['en'],
        },
        conditions: [],
      },
      {
        id: 461,
        action: 'plugin::content-manager.explorer.read',
        subject: 'api::article.article',
        properties: {
          fields: ['Name'],
          locales: ['fr-FR'],
        },
        conditions: [],
      },
      {
        id: 462,
        action: 'plugin::content-manager.explorer.update',
        subject: 'api::article.article',
        properties: {
          fields: ['Name'],
          locales: ['fr-FR'],
        },
        conditions: [],
      },
    ];

    const pluginsSectionRawLinks = [
      {
        destination: '/plugins/content-type-builder',
        icon: 'paint-brush',
        label: {
          id: 'content-type-builder.plugin.name',
          defaultMessage: 'Content-Types Builder',
        },
        permissions: [
          {
            action: 'plugin::content-type-builder.read',
            subject: null,
          },
        ],
        isDisplayed: false,
      },
      {
        destination: '/plugins/upload',
        icon: 'cloud-upload-alt',
        label: {
          id: 'upload.plugin.name',
          defaultMessage: 'Media Library',
        },
        permissions: [
          {
            action: 'plugin::upload.read',
            subject: null,
          },
          {
            action: 'plugin::upload.assets.create',
            subject: null,
          },
          {
            action: 'plugin::upload.assets.update',
            subject: null,
          },
        ],
        isDisplayed: false,
      },
    ];

    const expected = [
      {
        destination: '/plugins/content-type-builder',
        icon: 'paint-brush',
        isDisplayed: false,
        label: { defaultMessage: 'Content-Types Builder', id: 'content-type-builder.plugin.name' },
        permissions: [{ action: 'plugin::content-type-builder.read', subject: null }],
      },
      {
        destination: '/plugins/upload',
        icon: 'cloud-upload-alt',
        isDisplayed: false,
        label: { defaultMessage: 'Media Library', id: 'upload.plugin.name' },
        permissions: [
          { action: 'plugin::upload.read', subject: null },
          { action: 'plugin::upload.assets.create', subject: null },
          { action: 'plugin::upload.assets.update', subject: null },
        ],
      },
    ];
    const actual = await getPluginSectionLinks(userPermissions, pluginsSectionRawLinks);

    expect(actual).toEqual(expected);
  });
});


text:
from __future__ import division, print_function, unicode_literals

__doc__="""

Copy a background to a new layer and open it, so you can compare back and foreground side by side.

"""

font = Glyphs.font
glyphs = font.glyphs

# get active layer
layer = font.selectedLayers[0]
bg_layer = layer.background

# get glyph of this layer
glyph = layer.parent
glyph_name = str(glyph.name)

bg_layer = layer.background
new_layer = GSLayer()
new_layer.name = "background_copy"

# you may set the master ID that this layer will be associated with, otherwise the first master will be used
new_layer.associatedMasterId = font.masters[-1].id # attach to last master
glyph.layers.append(new_layer)

for path in bg_layer.paths:
	new_path = path.copy()
	new_layer.paths.append(new_path)

tab_text = glyph_name*2

if tab_text:
    font.newTab(tab_text)


text:
package ca.ulaval.ift.graal.pagerank.drivers;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobStatus;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ca.ulaval.ift.graal.Util;
import ca.ulaval.ift.graal.pagerank.mapreduce.PagerankMapper;
import ca.ulaval.ift.graal.pagerank.mapreduce.PagerankReducer;
import ca.ulaval.ift.graal.pagerank.parseurl.mapreduce.ParseUrlMapper;
import ca.ulaval.ift.graal.pagerank.parseurl.mapreduce.ParseUrlReducer;
import ca.ulaval.ift.graal.pagerank.topk.TopKMapper;
import ca.ulaval.ift.graal.pagerank.topk.TopKReducer;

public class PagerankMRDriver extends Configured implements Tool {
    private static final Logger LOG = LoggerFactory.getLogger(PagerankMRDriver.class);

    private static final String DATA_PATH = "data/pagerank/parsed_crawl_data.seq";
    private static final float DEFAULT_DAMPING_FACTOR = 0.85f;
    private static final int MAX_ITERATIONS = 50;
    private static final int INPUT_SIZE = 100;
    private static final int DEFAULT_ROUNDING_PRECISION = 8;

    // TODO figure out how to check for convergence
    // private static final float DEFAULT_CONVERGENCE_THRESHOLD = 0.0001f;

    public static void main(String[] args) throws Exception {
        int exitCode = ToolRunner.run(new PagerankMRDriver(), args);
        System.exit(exitCode);
    }

    @Override
    public int run(String[] arg0) throws IOException, ClassNotFoundException, InterruptedException {
        LOG.info("Demo for Pagerank Job -- run()");

        Configuration conf = getConf();
        FileSystem fs = FileSystem.get(conf);

        conf.setFloat("damping.factor", DEFAULT_DAMPING_FACTOR);
        conf.setInt("input.size", INPUT_SIZE);
        conf.setInt("rounding.precision", DEFAULT_ROUNDING_PRECISION);

        Path parsedIntputPath = new Path(DATA_PATH);
        Path parsedOutputPath = new Path("data/pagerank/parsed_output");
        if (fs.exists(parsedOutputPath))
            fs.delete(parsedOutputPath, true);

        Job parseJob = new Job(conf, "Pagerank: Parse URL data job");
        parseJob.setJarByClass(getClass());
        runParseUrlJob(parseJob, parsedIntputPath, parsedOutputPath);

        int iterationCount = 1;
        Path inputPath = parsedOutputPath;
        while (iterationCount < MAX_ITERATIONS) {
            LOG.info("ITERATION #" + iterationCount);

            Path outputPath = new Path("data/pagerank/depth_" + iterationCount);
            if (fs.exists(outputPath))
                fs.delete(outputPath, true);

            Job pargerankJob = new Job(conf, "Pagerank computation job iteration " + iterationCount);
            pargerankJob.setJarByClass(getClass());
            runPagerankIterationJob(pargerankJob, inputPath, outputPath);

            iterationCount++;
            fs.delete(inputPath, true);
            inputPath = outputPath;
        }

        Path topkOutputPath = new Path("data/pagerank/topk");
        if (fs.exists(topkOutputPath)) {
            fs.delete(topkOutputPath, true);
        }
        Job topkJob = new Job(conf, "Pagerank topK job");
        topkJob.setJarByClass(getClass());
        runTopKJob(topkJob, inputPath, topkOutputPath);

        fs.delete(inputPath, true);

        Util.showSequenceFile(conf, topkOutputPath);

        return JobStatus.SUCCEEDED;
    }

    private boolean runParseUrlJob(Job job, Path input, Path output) throws IOException,
            InterruptedException, ClassNotFoundException {
        job.setMapperClass(ParseUrlMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);
        job.setInputFormatClass(SequenceFileInputFormat.class);
        FileInputFormat.addInputPath(job, input);

        job.setReducerClass(ParseUrlReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        job.setOutputFormatClass(SequenceFileOutputFormat.class);
        SequenceFileOutputFormat.setOutputPath(job, output);

        return job.waitForCompletion(true);
    }

    private boolean runPagerankIterationJob(Job job, Path input, Path output) throws IOException,
            InterruptedException, ClassNotFoundException {
        job.setMapperClass(PagerankMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);
        job.setInputFormatClass(SequenceFileInputFormat.class);
        FileInputFormat.addInputPath(job, input);

        job.setReducerClass(PagerankReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        job.setOutputFormatClass(SequenceFileOutputFormat.class);
        SequenceFileOutputFormat.setOutputPath(job, output);

        return job.waitForCompletion(true);
    }

    private boolean runTopKJob(Job job, Path input, Path output) throws IOException,
            InterruptedException, ClassNotFoundException {
        job.setMapperClass(TopKMapper.class);
        job.setMapOutputKeyClass(NullWritable.class);
        job.setMapOutputValueClass(Text.class);
        job.setInputFormatClass(SequenceFileInputFormat.class);
        FileInputFormat.addInputPath(job, input);

        job.setReducerClass(TopKReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        job.setOutputFormatClass(SequenceFileOutputFormat.class);
        SequenceFileOutputFormat.setOutputPath(job, output);

        return job.waitForCompletion(true);
    }
}


text:
package download;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

/**
 * Downloads a file from a given URL.
 *

 * If the downloaded file is compressed, then it will get automatically
 * unpacked. Supported arhive types: zip, tgz, tar.gz, tbz2, tar.bz2, gz, bz2.
 * Password protected files are not supported yet.
 *
 * @author Michael Jedich
 * @version 0.7.0
 */
public class Downloader {

  private static final int DOWNLOAD_TIMEOUT = 60000;

  /**
   * Downloads a file from a given URL.
   *

   * If the downloaded file is compressed, then it will get automatically
   * unpacked. Supported archive types: zip, tgz, tar.gz, tbz2, tar.bz2, gz, bz2.
   * Password protected files are not supported yet.
   *

   * A monitor-thread will be started to monitor download-progress.
   *
   * @param url
   *          URL-String to download from
   * @throws Exception
   */
  public void downloadFile(final String url, final File destination)
      throws Exception {
    if (url == null || url.trim().isEmpty() || destination == null) {
      throw new IllegalArgumentException("URL OR DESTINATION FILE IS INVALID!");
    }

    if (destination.isDirectory()) {
      throw new IllegalArgumentException("DESTINATION FILE IS A DIRECTORY!");
    }

    InputStream inputStream = null;
    FileOutputStream fileOutputStream = null;
    DownloadMonitor downloadMonitor = null;
    Thread monitorThread = null;
    int fileSizeFromHeader = -1;
    boolean errorOccured = false;

    try {
      URL resourceToDownload = new URL(url);
      URLConnection connection = resourceToDownload.openConnection();
      connection.setConnectTimeout(DOWNLOAD_TIMEOUT);
      connection.setReadTimeout(DOWNLOAD_TIMEOUT);

      if (connection != null) {
        inputStream = resourceToDownload.openStream();
        fileSizeFromHeader = connection.getContentLength();

        downloadMonitor = new DownloadMonitor(destination, inputStream,
            fileSizeFromHeader);
        monitorThread = new Thread(downloadMonitor);
        monitorThread.start();

        ReadableByteChannel readableByteChannel = Channels
            .newChannel(inputStream);
        fileOutputStream = new FileOutputStream(destination);
        fileOutputStream.getChannel().transferFrom(readableByteChannel, 0,
            Long.MAX_VALUE);
      }
    } catch (UnknownHostException e) {
      errorOccured = true;
      throw e;
    } catch (FileNotFoundException e) {
      errorOccured = true;
      throw e;
    } catch (Exception e) {
      errorOccured = true;
      throw e;
    } finally {
      try {
        if (downloadMonitor != null) {
          downloadMonitor.close(errorOccured);
          monitorThread.join();
        }
        if (inputStream != null) {
          inputStream.close();
        }
        if (fileOutputStream != null) {
          fileOutputStream.close();
        }
      } catch (IOException e) {
        throw e;
      } catch (InterruptedException e) {
        throw e;
      }
    }
  }
}


text:
require 'optparse'
require 'fileutils'
require 'httparty'
require 'digest'
require 'gems'
require 'time'

include Origen::Utility::InputCapture

options = {}

opt_parser = OptionParser.new do |opts|
  opts.banner = <<-END
Generate a new Origen application.

This runs the Origen App Generators plugin to generate the new application, this provides many
engineering domain specific application shells as well as a generic application shell.

By default this will always run the latest and greatest production release of the application
generators regardless of the base Origen version that this command is being launched from.

See the website for more details:

http://origen-sdk.org/origen_app_generators

Usage: origen new [APP_NAME] [options]
END
  opts.on('-d', '--debugger', 'Enable the debugger') {  options[:debugger] = true }
  opts.on('-f', '--fetch', 'Fetch the latest versions of the app generators, otherwise happens every 24hrs') { options[:fetch] = true }
  opts.separator ''
  opts.on('-h', '--help', 'Show this message') { puts opts; exit }
end

opt_parser.orig_parse! ARGV
options[:patterns] = ARGV

dir = ARGV.first

unless dir
  puts 'You must supply a path to the workspace you wish to create'
  exit 1
end

unless Dir["#{dir}/*"].empty?
  puts 'The requested workspace is not empty, please delete it and try again, or select a different path.'
  exit 1
end

generators_dir = "#{Origen.home}/app_generators"
update_required = false

# Update the generators every 24hrs unless specifically requested
if options[:fetch] || !File.exist?(generators_dir)
  update_required = true
else
  if Origen.session.app_generators[generators_dir]
    if Time.now - Origen.session.app_generators[generators_dir] > 60 * 60 * 24
      update_required = true
    end
  else
    update_required = true
  end
end

generators = [['https://rubygems.org', 'origen_app_generators']] + Array(Origen.site_config.app_generators)

def use_packaged_generators
  FileUtils.cp_r Origen.top.join('origen_app_generators').to_s, '.'
  FileUtils.mv 'origen_app_generators', '0'
end

if update_required
  puts 'Fetching the latest app generators...'
  FileUtils.rm_rf(generators_dir) if File.exist?(generators_dir)
  FileUtils.mkdir_p(generators_dir)

  Dir.chdir generators_dir do
    generators.each_with_index do |gen, i|
      # If a reference to a gem from a gem server
      if gen.is_a?(Array)
        begin
          response = HTTParty.get("#{gen[0]}/api/v1/dependencies.json?gems=#{gen[1]}", timeout: 2)

          if response.success?
            latest_version = JSON.parse(response.body).map { |v| v['number'] }.max

            response = HTTParty.get("#{gen[0]}/gems/#{gen[1]}-#{latest_version}.gem", timeout: 5)
            if response.success?
              File.open("#{gen[1]}-#{latest_version}.gem", 'wb') do |f|
                f.write response.parsed_response
              end

              `gem unpack #{gen[1]}-#{latest_version}.gem`
              FileUtils.rm_rf("#{gen[1]}-#{latest_version}.gem")
              FileUtils.mv("#{gen[1]}-#{latest_version}", i.to_s)
            else
              use_packaged_generators if i == 0
            end
          else
            use_packaged_generators if i == 0
          end
        rescue
          use_packaged_generators if i == 0
        end

      # If a reference to a git repo
      elsif gen.to_s =~ /\.git$/
        begin
          Origen::RevisionControl.new(remote: gen, local: i.to_s).checkout(version: 'master', force: true)
        rescue
          # Better for the user not to crash here, not much we can do otherwise
        end

      # Assume a reference to a folder
      else
        begin
          FileUtils.cp_r(gen, i.to_s) if File.exist?(gen)
        rescue
          # Better for the user not to crash here, not much we can do otherwise
        end
      end
    end

    Origen.session.app_generators[generators_dir] = Time.now
  end
end

generators.each_with_index do |gen, i|
  lib = "#{generators_dir}/#{i}/lib"
  $LOAD_PATH.unshift(lib)
end

Origen.with_boot_environment do
  require 'origen_app_generators'
  generators.each_with_index do |gen, i|
    loader = "#{generators_dir}/#{i}/config/load_generators.rb"
    require loader if File.exist?(loader)
  end
  OrigenAppGenerators.invoke(dir)
end


text:
FROM clojure
RUN echo "{:user {:plugins [[lein-exec \"0.3.1\"]]}}" >> ~/.lein/profiles.clj
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY project.clj /usr/src/app/
RUN lein deps
COPY . /usr/src/app
CMD lein exec rna_transcription_test.clj


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="com.suleiman.material">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/MyTheme">
        <activity
            android:name=".activities.LaunchScreenActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.MainActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/app_name"/>
        <activity
            android:name=".activities.FabHideActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/title_fab_animations"/>
        <activity
            android:name=".activities.ToolbarOverlayActivity"
            android:label="@string/title_activity_toolbar_test"/>
        <activity
            android:name=".activities.NavDrawerActivity"
            android:label="@string/title_activity_nav_drawer"
            android:theme="@style/MyTheme.Detail"/>
        <activity
            android:name=".activities.AnimateToolbar"
            android:configChanges="orientation|screenSize"
            android:theme="@style/MyTheme.Detail"/>
        <activity
            android:name=".activities.TabAnimationActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/title_activity_tab_animation"/>
        <activity
            android:name=".activities.NestedToolbarActivity"
            android:label="@string/title_activity_nested_toolbar"/>
        <activity
            android:name=".activities.QuickReturnActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/title_quick_return"/>
        <activity
            android:name=".activities.RevealAnimation"
            android:label="@string/title_activity_reveal_animation"/>
        <activity
            android:name=".activities.GmailStyleActivity"
            android:label="@string/title_activity_gmail_style"/>
        <activity
            android:name=".activities.TabsHeaderActivity"
            android:label="@string/title_activity_tabs_header"
            android:theme="@style/MyTheme.Detail"/>
        <activity
            android:name=".activities.PagerActivity"
            android:theme="@style/MyTheme.Detail"/>
        <activity android:name=".activities.BottomBarActivity">
        </activity>
    </application>

</manifest>


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

  <meta http-equiv="Content-Language" content="en-us" />
  <meta http-equiv="Content-Type" content="text/html; charset=us-ascii" />
  <link rel="stylesheet" type="text/css" href=
  "../../../doc/src/boostbook.css" />

  <title>Libary Status</title>

Generating Library Status Tables

Purpose
Any time one considers using a library as large and complex
  as the Boost libraries, he must have a way of validating the the library
  functions in his environment. This should be done when the library is
  installed and anytime questions are raised regarding its applicabililty
  and/or its usage.

The procedures described here permit a user to run any combination of
  tests on any or all libraries and generate a set of convenient tables which
  show which libraries pass which tests under what conditions.

Preliminaries
Generating these tables requires a couple of utility
  programs: process_jam_log and library_status.
  These can be built by moving to the directory
  tools/regression/build and invoking bjam. If all goes well
  these utility programs will be found in the directory
  dist/bin. From there they should be moved to a place in the
  current path.

Running Tests for One Library

Start from your command line environment.

set the current directory to:../libs/<library name>/test

Invoke one of the following:

../../../tools/regression/src/library_test (*nix).

..\..\..\tools\regression\src\library_test
        (windows).

This will display short help message describing the how to set the
    command line arguments for the compilers and variants you want to appear
    in the final table.

Setting these arguments requires rudimentary knowledge of bjam usage.
    Hopefully, if you've arrived at this page you've gained the required
    knowledge during the installation and library build process.

Rerun the abve command with the argument set accordingly.

When the command terminates, there should be a file named
    "library_status.html" in the current directory.

Display this file with any web browser.

There should appear a table similar to the following for the regex
  library.

      Test Name

      msvc-7.1

      debug

      release

      link-static

      threading-multi

      link-static

      threading-multi

      threading-multi

      threading-multi

      bad_expression_test

      Missing

      Warn

      Missing

      Warn

      captures

      Missing

      Fail

      Missing

      Fail

      captures_test

      Missing

      Warn

      Missing

      Warn

      concept_check

      Missing

      Pass

      Missing

      Pass

      icu_concept_check

      Missing

      Pass

      Missing

      Pass

      object_cache_test

      Missing

      Warn

      Missing

      Warn

      posix_api_check

      Missing

      Warn

      Missing

      Warn

      posix_api_check_cpp

      Missing

      Pass

      Missing

      Pass

      recursion_test

      Missing

      Warn

      Missing

      Warn

      regex_config_info

      Missing

      Pass

      Missing

      Pass

      regex_dll_config_info

      Missing

      Pass

      Missing

      Pass

      regex_regress

      Pass*

      Missing

      Pass*

      Missing

      regex_regress_dll

      Missing

      Pass*

      Missing

      Pass*

      regex_regress_threaded

      Missing

      Pass

      Missing

      Pass

      static_mutex_test

      Missing

      Pass

      Missing

      Pass

      test_collate_info

      Missing

      Warn

      Missing

      Warn

      unicode_iterator_test

      Missing

      Warn

      Missing

      Warn

      wide_posix_api_check_c

      Missing

      Warn

      Missing

      Warn

      wide_posix_api_check_cpp

      Missing

      Warn

      Missing

      Warn

This table was generated by invoking the following command line:

../../../tools/regression/src/library_test --toolset=msvc-7.1
  variant=debug,release

from within the .../libs/regex/test directory.

This table shows the regex test results for both debug and release
  versions of the library. Also it displays the fact that one of the tests is
  run specifically with the static linking/multi-threading versions of the
  runtime libraries. The cells marked "Missing" correspond to tests that were
  not run for some reason or another. This is usually because the
  corresponding Jamfile.v2 excludes this test for the given
  combination of compiler and build attributes. In this example, all tests
  were run with the same compiler. If additional compilers were used, they
  would appear as more columns in the table.

The table above is just an illustration so the links don't actually
  point to anything. In the table you generated, the links will display a
  page describing any errors, warnings or other available information about
  the tests. If the test passes, usually, there is no additional information
  and hence no link.

The tables are cumulative. That is, if you run one set of tests now and
  tests with different attributes later, the table will contain all the
  results to date. The test results are stored in
  ../bin.v2/libs/test/<library%gt;/.... To reinitialize the
  test results to empty, delete the corresponding files in this
  directory.

The procedure above assumes that the table are generated within the
  directory ../libs/<library>/test. This is the most
  common case since this directory contains the Jamfile.v2 as
  well as the source code that is used by official boost testers. However,
  this is just a convention. The table can be generated for other directories
  within the libary. One possiblity would be to generate the table for all
  the examples in ../libs/%lt;library%gt;/example. Or one might
  have a special directory of performance tests which take a long time to run
  and hence are not suitable for running by official boost testers. Just
  remember that library status table is generated in the directory from which
  the library_test command is invoked.

Running Tests for All Libraries
For those with *nix or cygwin
  command line shells, there is shell script that can be run from the boost
  root directory:

tools/regression/src/library_test_all

The command line arguments are the same as for running the test for one
  library. This script creates all the html files in all the test directories
  as well as an html page in the status directory named
  library_status_summary.html. This can be used to browse
  through all test results for all test in all libraries.

Copyright 2011 Bryce Lelbach.

Copyright 2007-2011 Robert Ramey.

Distributed under the Boost Software
  License, Version 1.0. (See accompanying file LICENSE_1_0.txt or
  http://www.boost.org/LICENSE_1_0.txt)

Revised $Date: 2011-10-06 11:41:40 -0400 (Thu, 06 Oct 2011) $


text:
<?php
namespace ZenOAuth2;

class WeiboClient extends Client{
	/**
	 * Set up the API root URL.
	 *
	 * @ignore
	 */
	public $host = "https://api.weibo.com/2/";

	/**
	 *
	 * @var string
	 */
	public $remote_ip = null;

	protected function _additionalHeaders(){
		$headers = array();

		if ($this->access_token)
			$headers[] = "Authorization: OAuth2 ".$this->access_token;

		if (isset($this->remote_ip))
			$headers[] = "API-RemoteIP: " . $this->remote_ip;
		elseif(isset($_SERVER['REMOTE_ADDR']))
			$headers[] = "API-RemoteIP: " . $_SERVER['REMOTE_ADDR'];

		return $headers;
	}

	/**
	 *
	 * @param string $clientId
	 */
	public static function createByClientId($clientId){
		$instance = new self(null);
		$instance->client_id = $clientId;

		return $instance;
	}

	public function realUrl($url){
		if (strrpos($url, 'https://') !== 0 && strrpos($url, 'https://') !== 0) {
			$url = $this->host . $url . '.' . $this->format;
		}

		return $url;
	}
}


text:
using gpcodegen::CodegenInterface;

// Initalization of unique counter
unsigned CodegenInterface::unique_counter_ = 0;

std::string CodegenInterface::GenerateUniqueName(
    const std::string& orig_func_name) {
  return orig_func_name + std::to_string(unique_counter_++);
}


text:
package com.codepath.apps.restclienttemplate.models;

import android.os.Parcelable;
import android.os.Parcelable.Creator;
import org.parceler.Generated;
import org.parceler.IdentityCollection;
import org.parceler.ParcelWrapper;
import org.parceler.ParcelerRuntimeException;

@Generated(value = "org.parceler.ParcelAnnotationProcessor", date = "2017-07-07T17:49-0700")
@SuppressWarnings({
    "unchecked",
    "deprecation"
})
public class Tweet$$Parcelable
    implements Parcelable, ParcelWrapper<com.codepath.apps.restclienttemplate.models.Tweet>
{

    private com.codepath.apps.restclienttemplate.models.Tweet tweet$$0;
    @SuppressWarnings("UnusedDeclaration")
    public final static Creator<Tweet$$Parcelable>CREATOR = new Creator<Tweet$$Parcelable>() {

        @Override
        public Tweet$$Parcelable createFromParcel(android.os.Parcel parcel$$2) {
            return new Tweet$$Parcelable(read(parcel$$2, new IdentityCollection()));
        }

        @Override
        public Tweet$$Parcelable[] newArray(int size) {
            return new Tweet$$Parcelable[size] ;
        }

    }
    ;

    public Tweet$$Parcelable(com.codepath.apps.restclienttemplate.models.Tweet tweet$$2) {
        tweet$$0 = tweet$$2;
    }

    @Override
    public void writeToParcel(android.os.Parcel parcel$$0, int flags) {
        write(tweet$$0, parcel$$0, flags, new IdentityCollection());
    }

    public static void write(com.codepath.apps.restclienttemplate.models.Tweet tweet$$1, android.os.Parcel parcel$$1, int flags$$0, IdentityCollection identityMap$$0) {
        int identity$$0 = identityMap$$0 .getKey(tweet$$1);
        if (identity$$0 != -1) {
            parcel$$1 .writeInt(identity$$0);
        } else {
            parcel$$1 .writeInt(identityMap$$0 .put(tweet$$1));
            parcel$$1 .writeLong(tweet$$1 .uid);
            parcel$$1 .writeString(tweet$$1 .createdAt);
            parcel$$1 .writeInt(tweet$$1 .replyCount);
            parcel$$1 .writeInt(tweet$$1 .likeCount);
            parcel$$1 .writeString(tweet$$1 .body);
            com.codepath.apps.restclienttemplate.models.User$$Parcelable.write(tweet$$1 .user, parcel$$1, flags$$0, identityMap$$0);
            parcel$$1 .writeString(tweet$$1 .media_url);
            parcel$$1 .writeInt(tweet$$1 .retweetCount);
            parcel$$1 .writeInt((tweet$$1 .favorited? 1 : 0));
            parcel$$1 .writeInt((tweet$$1 .retweeted? 1 : 0));
        }
    }

    @Override
    public int describeContents() {
        return  0;
    }

    @Override
    public com.codepath.apps.restclienttemplate.models.Tweet getParcel() {
        return tweet$$0;
    }

    public static com.codepath.apps.restclienttemplate.models.Tweet read(android.os.Parcel parcel$$3, IdentityCollection identityMap$$1) {
        int identity$$1 = parcel$$3 .readInt();
        if (identityMap$$1 .containsKey(identity$$1)) {
            if (identityMap$$1 .isReserved(identity$$1)) {
                throw new ParcelerRuntimeException("An instance loop was detected whild building Parcelable and deseralization cannot continue.  This error is most likely due to using @ParcelConstructor or @ParcelFactory.");
            }
            return identityMap$$1 .get(identity$$1);
        } else {
            com.codepath.apps.restclienttemplate.models.Tweet tweet$$4;
            int reservation$$0 = identityMap$$1 .reserve();
            tweet$$4 = new com.codepath.apps.restclienttemplate.models.Tweet();
            identityMap$$1 .put(reservation$$0, tweet$$4);
            tweet$$4 .uid = parcel$$3 .readLong();
            tweet$$4 .createdAt = parcel$$3 .readString();
            tweet$$4 .replyCount = parcel$$3 .readInt();
            tweet$$4 .likeCount = parcel$$3 .readInt();
            tweet$$4 .body = parcel$$3 .readString();
            User user$$0 = com.codepath.apps.restclienttemplate.models.User$$Parcelable.read(parcel$$3, identityMap$$1);
            tweet$$4 .user = user$$0;
            tweet$$4 .media_url = parcel$$3 .readString();
            tweet$$4 .retweetCount = parcel$$3 .readInt();
            tweet$$4 .favorited = (parcel$$3 .readInt() == 1);
            tweet$$4 .retweeted = (parcel$$3 .readInt() == 1);
            com.codepath.apps.restclienttemplate.models.Tweet tweet$$3 = tweet$$4;
            identityMap$$1 .put(identity$$1, tweet$$3);
            return tweet$$3;
        }
    }

}


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/graph_algorithms_test.dir/graph_algorithms_test.cc.o"
  "../../bin/graph_algorithms_test.pdb"
  "../../bin/graph_algorithms_test"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
  INCLUDE(CMakeFiles/graph_algorithms_test.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)


text:
// Only modify this file to include
// - function definitions (prototypes)
// - include files
// - extern variable definitions
// In the appropriate section

#ifndef Quad2_H_
#define Quad2_H_
#include "Arduino.h"
//add your includes for the project Quad2 here

// external libraries
#include <Wire.h>

// main
#include "compFilter.h"
#include "flightCommand.h"
#include "flightControl.h"

// libraries
#include "globals.h"
#include "PID.h"
#include "ITG3200.h"
#include "ADXL345.h"
#include "HMC5883L.h"
#include "receiver.h"
#include "telemetry.h"
#include "LED.h"

//end of add your includes here
#ifdef __cplusplus
extern "C" {
#endif
void loop();
void setup();
#ifdef __cplusplus
} // extern "C"
#endif

//add your function definitions for the project Quad2 here

//Do not add code below this line
#endif /* Quad2_H_ */


text:
'use strict';

import ES6PromiseProvider from './../promises/ES6PromiseProvider.js';
import Utils from './../utils/Utils.js';
import Account from './../models/Account.js';
import Mailbox from './../models/Mailbox.js';
import MessageList from './../models/MessageList.js';
import Thread from './../models/Thread.js';
import Message from './../models/Message.js';
import OutboundMessage from './../models/OutboundMessage.js';
import CreateMessageAck from './../models/CreateMessageAck.js';
import MessagesSet from './../models/MessagesSet.js';
import MailboxRole from './../models/MailboxRole.js';
import AuthContinuation from './../models/AuthContinuation.js';
import AuthAccess from './../models/AuthAccess.js';
import Constants from '../utils/Constants.js';

export default class Client {
  /**
   * The {@link Client} class is the main entry point for sending JMAP requests to a remote server.

   * It uses a fluent API so that it's easy to chain calls. JMAP requests are sent using one of the _getXXX_ methods
   * that map to their equivalent in the JMAP specification. For instance, if you want to do a _getAccounts_ request,
   * you'll use the {@link Client#getAccounts} method.
   *
   * @param transport {Transport} The {@link Transport} instance used to send HTTP requests.
   * @param [promiseProvider={@link ES6PromiseProvider}] {PromiseProvider} The {@link PromiseProvider} implementation to use.
   */
  constructor(transport, promiseProvider) {
    Utils.assertRequiredParameterIsPresent(transport, 'transport');

    this.transport = transport;
    this.transport.promiseProvider = promiseProvider || new ES6PromiseProvider();
  }

  /**
   * Registers an authentication URL, that will be used as the endpoint to send authentication requests to the server.

   *

   * The URL will be exposed as the `authenticationUrl` property afterwards.
   *
   * @param url {String} The authentication url to use in JMAP requests.
   *
   * @return {Client} This Client instance.
   */
  withAuthenticationUrl(url) {
    this.authenticationUrl = url;
    return this;
  }

  /**
   * Registers an authentication token, obtained by an external mechanism from the target JMAP server.

   * This token will then be used as the `Authorization` header, as per {@link http://jmap.io/spec.html#authenticating-http-requests}.

   *

   * The token will be exposed as the `authToken` property afterwards.
   *
   * @param token {String} The authentication token to use in JMAP requests.
   *
   * @return {Client} This Client instance.
   */
  withAuthenticationToken(token) {
    this.authToken = token;
    return this;
  }

  /**
   * Sets the API URL of the target JMAP server. All JMAP requests will be sent to this URL.

   *

   * The URL will be exposed as the `apiUrl` property afterwards.
   *
   * @param url {String} The API URL of the JMAP server.
   *
   * @return {Client} This Client instance.
   */
  withAPIUrl(url) {
    this.apiUrl = url;
    return this;
  }

  /**
   * Sets the download URL, i.e.: the URL used to download attachments to {@link Message}s.

   *

   * The URL will be exposed as the `downloadUrl` property afterwards.
   *
   * @param url {String} The download URL of the JMAP server.
   *
   * @return {Client} This Client instance.
   */
  withDownloadUrl(url) {
    this.downloadUrl = url;
    return this;
  }

  /**
   * Implement the 2-step JMAP authentication protocol.

   * This method abstract the two authentication steps:
   *
   * 1. query the JMAP server to get a continuation token
   * 2. query the JMAP server with the continuation token (and password), to get the final accessToken.
   *
   * @param username {String} The username to authenticate with
   * @param deviceName {String} A unique device name
   * @param continuationCallback {Function} A function that takes an {@link AuthContinuation}
   *   object as argument, and should return a promise, that will eventually resolve with an
   *   object denoting the chosen authentication method and the optional password (if method == password).
   *
   * @return {Promise} A {@link Promise} that will eventually be resovled with a {@link AuthAccess} object
   */
  authenticate(username, deviceName, continuationCallback) {
    var authContinuation;
    return this.transport
      .post(this.authenticationUrl, this._defaultNonAuthenticatedHeaders(), {
        username: username,
        deviceName: deviceName,
        clientName: Constants.CLIENT_NAME,
        clientVersion: Constants.VERSION
      })
      .then((data) => {
        authContinuation = new AuthContinuation(data);
        return authContinuation;
      })
      .then((authContinuation) => continuationCallback(authContinuation))
      .then((continueData) => {
        if (authContinuation.methods.indexOf(continueData.method) < 0) {
          throw new Error('The "' + continueData.method + '" authentication protocol is not supported by the server.');
        }
        let param = {
          token: authContinuation.continuationToken,
          method: continueData.method,
        };
        if (continueData.password) {
          param.password = continueData.password;
        }
        return this.transport
          .post(this.authenticationUrl, this._defaultNonAuthenticatedHeaders(), param);
      })
      .then((data) => new AuthAccess(data));
  }

  /**
   * Implement the JMAP external authentication protocol.

   * This method abstract the two authentication steps:
   *
   * 1. query the JMAP server to get a continuation token
   * 2. query the JMAP server with the continuation token, to get the final accessToken.
   *
   *

   * Between those two steps, a user provided function wil be called to handle the external
   * authentication part.
   *

   * This method returns a promise that will eventually be resovled with a {@link AuthAccess} object.
   * It's the responsability of the caller to then set the AuthToken using for example:
   *

   *
   *     client.withAuthenticationToken(authAccess.accessToken);
   *
   * @param username {String} The username of the user to authenticate.
   * @param deviceName {String} A unique device name
   * @param continuationCallback {Function} A function that takes an {@link AuthContinuation} object as argument, and should return a promise, that will resolve once the external authentication is complete.
   *
   * @return {Promise} A {@link Promise} that will eventually be resovled with a {@link AuthAccess} object
   */
  authExternal(username, deviceName, continuationCallback) {
    return this.authenticate(username, deviceName, function(authContinuation) {
      // wrap the continuationCallback to resolve with method:'external'
      return continuationCallback(authContinuation).then(() => {
        return { method: 'external' };
      });
    });
  }

  /**
   * Implement the JMAP password authentication protocol.

   * This method abstract the two authentication steps:
   *
   * 1. query the JMAP server to get a continuation token
   * 2. query the JMAP server with the continuation token and the password, to get the final accessToken.
   *
   * @param username {String} The username of the user to authenticate
   * @param password {String} The password of the user to authenticate
   * @param deviceName {String} A unique device name
   *
   * @return {Promise} A {@link Promise} that will eventually be resovled with a {@link AuthAccess} object
   */
  authPassword(username, password, deviceName) {
    return this.authenticate(username, deviceName, function(authContinuation) {
      return { method: 'password', password: password };
    });
  }

  /**
   * Sends a _getAccounts_ JMAP request.
   *
   * @param [options=null] {Object} The options to the _getAccounts_ JMAP request.
   *
   * @return {Promise} A {@link Promise} that eventually resolves to an array of {@link Account} objects.
   *
   * @see http://jmap.io/spec.html#getaccounts
   */
  getAccounts(options) {
    return this._jmapRequest('getAccounts', options);
  }

  /**
   * Sends a _getMailboxes_ JMAP request.
   *
   * @param [options=null] {Object} The options to the _getMailboxes_ JMAP request.
   *
   * @return {Promise} A {@link Promise} that eventually resolves to an array of {@link Mailbox} objects.
   *
   * @see http://jmap.io/spec.html#getmailboxes
   */
  getMailboxes(options) {
    return this._jmapRequest('getMailboxes', options);
  }

  /**
   * Finds a {@link Mailbox} with the given role.

   * This will issue a _getMailboxes_ JMAP request and search for the mailbox in the returned list.
   *
   * @param role {MailboxRole|String} The desired mailbox role.
   * @param [options=null] {Object} The options to the implicit _getMailboxes_ JMAP request.
   *
   * @return {Promise} A {@link Promise} that eventually resolves to the {@link Mailbox} if found.
   *
   * @see MailboxRole
   */
  getMailboxWithRole(role, options) {
    if (!(role instanceof MailboxRole)) {
      role = MailboxRole.fromRole(role);
    }

    if (role === MailboxRole.UNKNOWN) {
      throw new Error('A valid role is required to find a mailbox by role');
    }

    return this._jmapRequest('getMailboxes', options)
      .then((mailboxes) => {
        for (let i = 0; i < mailboxes.length; i++) {
          if (mailboxes[i].role === role) {
            return mailboxes[i];
          }
        }

        throw new Error('Cannot find a mailbox with role ' + role.role);
      });
  }

  /**
   * Sends a _getMessageList_ JMAP request.
   *
   * @param [options=null] {Object} The options to the _getMessageList_ JMAP request.
   *
   * @return {Promise} A {@link Promise} that eventually resolves to a {@link MessageList} object.
   *
   * @see http://jmap.io/spec.html#getmessagelist
   */
  getMessageList(options) {
    return this._jmapRequest('getMessageList', options);
  }

  /**
   * Sends a _getThreads_ JMAP request.
   *
   * @param [options=null] {Object} The options to the _getThreads_ JMAP request.
   *
   * @return {Promise} A {@link Promise} that eventually resolves to an array of {@link Thread} objects.
   *
   * @see http://jmap.io/spec.html#getthreads
   */
  getThreads(options) {
    return this._jmapRequest('getThreads', options);
  }

  /**
   * Sends a _getMessages_ JMAP request.
   *
   * @param [options=null] {Object} The options to the _getMessages_ JMAP request.
   *
   * @return {Promise} A {@link Promise} that eventually resolves to an array of {@link Message} objects.
   *
   * @see http://jmap.io/spec.html#getmessages
   */
  getMessages(options) {
    return this._jmapRequest('getMessages', options);
  }

  /**
   * Sends a _setMessages_ JMAP request.
   *
   * @param [options=null] {Object} The options to the _setMessages_ JMAP request.
   *
   * @return {Promise} A {@link Promise} that eventually resolves to a {@link MessagesSet} object.
   *
   * @see http://jmap.io/spec.html#setmessages
   */
  setMessages(options) {
    return this._jmapRequest('setMessages', options);
  }

  /**
   * Save a message as draft by sending a _setMessages_ JMAP request.

   * The _mailboxIds_ and _isDraft_ properties of the given _message_ will be overridden by this method.
   *
   * @param message {OutboundMessage} The message to save.
   *
   * @return {Promise} A {@link Promise} that eventually resolves to a {@link CreateMessageAck}.
   *
   * @see http://jmap.io/spec.html#saving-a-draft
   */
  saveAsDraft(message) {
    Utils.assertRequiredParameterHasType(message, 'message', OutboundMessage);

    var clientId = this._generateClientId();
    return this
      .getMailboxWithRole(MailboxRole.DRAFTS)
      .then(mailbox => {
        message.mailboxIds = [mailbox.id];
        message.isDraft = true;

        return this.setMessages({
          create: {
            [clientId]: message.toJSONObject()
          }
        });
      }).then(response => {
        if (!response.created[clientId]) {
          throw new Error('Failed to save the message as draft, clientId: ' + clientId + ', message: ' + (response.notCreated[clientId] || 'none'));
        }
        return new CreateMessageAck(this, response.created[clientId]);
      });
  }

  /**
   * Moves a {@link Message} to a different set of mailboxes.

   * This will issue a {@link Client#setMessages} JMAP request under the hoods, passing the correct options.
   *
   * @param id {String} The id of the {@link Message} to move.
   * @param mailboxIds {String[]} The identifiers of the target mailboxes for the message.
   *
   * @return {Promise} A {@link Promise} that eventually resolves to nothing if the message was moved successfully.
   *
   * @see Client#setMessages
   */
  moveMessage(id, mailboxIds) {
    Utils.assertRequiredParameterIsPresent(id, 'id');
    Utils.assertRequiredParameterIsArrayWithMinimumLength(mailboxIds, 'mailboxIds', 1);

    return this.setMessages({
      update: {
        [id]: {
          mailboxIds: mailboxIds
        }
      }
    }).then(function(messagesSet) {
      if (messagesSet.updated.indexOf(id) < 0) {
        throw new Error('Failed to move message ' + id + ', reason is ' + messagesSet.notUpdated[id]);
      }
    });
  }

  _generateClientId() {
    return Date.now();
  }

  _defaultNonAuthenticatedHeaders() {
    return {
      Accept: 'application/json; charset=UTF-8',
      'Content-Type': 'application/json; charset=UTF-8'
    };
  }

  _defaultHeaders() {
    return {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      Authorization: this.authToken
    };
  }

  _jmapRequest(command, options) {
    return this.transport
      .post(this.apiUrl, this._defaultHeaders(), [[command, options || {}, '#0']])
      .then(Utils.assertValidJMAPResponse.bind(null, command))
      .then((data) => {
        return data.map(this._handleResponse.bind(this));
      })
      .then(function(responses) {
        return responses.length > 1 ? responses : responses[0];
      });
  }

  _handleResponse(response) {
    let name = response[0],
        fn = this['_handle' + Utils.capitalize(name) + 'Response'];

    // This will return the "raw" data if the command is unknown to the client
    return fn ? fn.bind(this)(response) : response[1];
  }

  _handleListResponse(response, Model) {
    return Utils._jsonArrayToModelList(this, Model, response[1].list);
  }

  _handleAccountsResponse(response) {
    return this._handleListResponse(response, Account);
  }

  _handleThreadsResponse(response) {
    return this._handleListResponse(response, Thread);
  }

  _handleMessagesResponse(response) {
    return this._handleListResponse(response, Message);
  }

  _handleMailboxesResponse(response) {
    return this._handleListResponse(response, Mailbox);
  }

  _handleMessageListResponse(response) {
    return MessageList.fromJSONObject(this, response[1]);
  }

  _handleMessagesSetResponse(response) {
    return MessagesSet.fromJSONObject(this, response[1]);
  }
}


text:
package ca.ubc.cs411.abe.value;

import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;

public class NValTest {
    @Test
    public void toBool() {
        NVal val = new NVal(5);
        try {
            val.toBool();
            fail("NVal.toBool() should throw an Error");
        } catch (Error e) {
            assertThat(e.getMessage()).isEqualTo("toBool: NVal(5) is not a boolean");
        }
    }

    @Test
    public void toNum() {
        int intVal = 5;
        NVal val = new NVal(intVal);
        assertThat(val.toNum()).isEqualTo(intVal);
    }

    @Test
    public void isNotEqualToNonNVal() {
        int innerIntVal = 5;
        NVal nVal = new NVal(innerIntVal);
        Integer nInt = new Integer(innerIntVal);
        assertThat(nVal).isNotEqualTo(nInt);
    }

    @Test
    public void isNotEqualToNValWithDiffVal() {
        NVal nVal = new NVal(-1);
        NVal otherNVal = new NVal(1);
        assertThat(nVal).isNotEqualTo(otherNVal);
    }

    @Test
    public void isEqualToNValWithSameVal() {
        int innerIntVal = 5;
        NVal nVal = new NVal(innerIntVal);
        NVal otherNVal = new NVal(innerIntVal);
        assertThat(nVal).isEqualTo(otherNVal);
    }

    @Test
    public void isEqualToSelf() {
        NVal nVal = new NVal(5);
        assertThat(nVal).isEqualTo(nVal);
    }
}


text:
if [[ -z $GRAPHITE_PREFIX ]] #default graphite prefix
then
export GRAPHITE_PREFIX=$HOSTNAME
fi

######## If using BF with docker-compose / linking with C* and ES containers #######
if [[ -n "$CASSANDRA_PORT_9160_TCP_ADDR" ]]
then
export CASSANDRA_HOST="$CASSANDRA_PORT_9160_TCP_ADDR"
fi

if [[ -n "$ELASTICSEARCH_PORT_9300_TCP_ADDR" ]]
then
export ELASTICSEARCH_HOST="$ELASTICSEARCH_PORT_9300_TCP_ADDR"
fi

######## Connecting to Cassandra and loading Blueflood's schema #######
CASSCOUNTER=0
trap "exit" INT
while [[ $CASSCOUNTER -lt 180 ]];  #Wait for 180 seconds for cassandra to get ready.
do
        let CASSCOUNTER=CASSCOUNTER+2
	nc -z $CASSANDRA_HOST 9160 > /dev/null
	if [ $? == 0 ]
		then
                echo "Connected to Cassandra at $CASSANDRA_HOST"
		break
	elif [[ $CASSCOUNTER == 180 ]]
                then
                echo "Error connecting to Cassandra"
                exit 1
        else
		echo "Waiting for Cassandra..."
	fi
	sleep 2
done

export CASSANDRA_HOSTS="$CASSANDRA_HOST:9160"

cqlsh $CASSANDRA_HOST -f blueflood.cdl

######## Connecting to Elasticsearch #######
ESCOUNTER=0
trap "exit" INT
while [[ $ESCOUNTER -lt 120 ]];  #Wait for 120 seconds for elasticsearch to get ready.
do
        let ESCOUNTER=ESCOUNTER+2
        nc -z $ELASTICSEARCH_HOST 9300 > /dev/null
        if [ $? == 0 ]
                then
                echo "Connected to Elasticsearch at $ELASTICSEARCH_HOST"
                break
        elif [[ $ESCOUNTER == 120 ]]
                then
                echo "Error connecting to Elasticsearch"
                exit 2
        else
                echo "Waiting for ElasticSearch..."
        fi
        sleep 2
done

export ELASTICSEARCH_HOSTS="$ELASTICSEARCH_HOST:9300"

cd ES-Setup
./init-es.sh -u $ELASTICSEARCH_HOST:9200
cd ..

printenv > blueflood.conf

cat > blueflood-log4j.properties << EOL
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %-20.20c{1}:%-3L - %m%n
log4j.logger.com.rackspacecloud.blueflood=$LOG_LEVEL # Change to DEBUG for more output from Blueflood
log4j.logger.httpclient.wire.header=WARN
log4j.logger.httpclient.wire.content=WARN
log4j.logger.org.apache.http.client.protocol=INFO
log4j.logger.org.apache.http.wire=INFO
log4j.logger.org.apache.http.impl=INFO
log4j.logger.org.apache.http.headers=INFO
log4j.rootLogger=INFO, console
EOL

/usr/bin/java \
        -Dblueflood.config=file:./blueflood.conf \
        -Dlog4j.configuration=file:./blueflood-log4j.properties \
        -Xms$MIN_HEAP_SIZE \
        -Xmx$MAX_HEAP_SIZE \
        -Dcom.sun.management.jmxremote.authenticate=false \
        -Dcom.sun.management.jmxremote.ssl=false \
        -Djava.rmi.server.hostname=localhost \
        -Dcom.sun.management.jmxremote.port=9180 \
        -classpath blueflood-all-2.0.0-SNAPSHOT-jar-with-dependencies.jar com.rackspacecloud.blueflood.service.BluefloodServiceStarter 2>&1


text:
<?php
/**
 * Created by PhpStorm.
 * User: lucius
 * Date: 28.02.17
 * Time: 13:53
 */

namespace HitobitoConnector\Exception;

class HttpException extends \Exception
{

}


text:
CREATE PROCEDURE [dbo].[uspNegotiationStatusInsert]
  @StatusID uniqueidentifier,
    @StatusDescription nvarchar(50)
AS
	SET NOCOUNT ON
	SET XACT_ABORT ON

	BEGIN TRAN

	INSERT INTO [dbo].[NegotiationStatus] ([StatusID], [StatusDescription])
	SELECT @StatusID, @StatusDescription

	-- Begin Return Select <- do not remove
	SELECT [StatusID], [StatusDescription]
	FROM   [dbo].[NegotiationStatus]
	WHERE  [StatusID] = @StatusID
	-- End Return Select <- do not remove

	COMMIT