text:
import React, { type Node } from 'react'
import { ThemeProvider } from 'next-themes'

import Layout from 'src/components/Layout'
import 'src/utils/theme/theme.css'

type Props = { Component: typeof React.Component, pageProps: Object }

const App = (props: Props): Node => (
  <ThemeProvider>
    <Layout>
      <props.Component {...props.pageProps} />
    </Layout>
  </ThemeProvider>
)

export default App

redpajama_set_name: RedPajamaGithub


text:
package com.moosemorals.calculator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.xml.stream.XMLStreamException;

import com.moosemorals.calculator.xml.XML;
import com.moosemorals.calculator.xml.XMLable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Osric Wilkinson <osric@fluffypeople.com>
 */
public class Config implements XMLable {

    private final Logger log = LoggerFactory.getLogger(Config.class);
    private final List<Button> buttons;
    private final int cols;
    private final int rows;
    private final int size;

    private Config(int cols, int rows, int size, List<Button> buttons) {
        this.cols = cols;
        this.rows = rows;
        this.size = size;
        this.buttons = buttons;
    }

    public int getCols() {
        return cols;
    }

    public int getRows() {
        return rows;
    }

    public int getSize() {
        return size;
    }

    public int getButtonCount() {
        return buttons.size();
    }

    public Button getButton(int index) {
        return buttons.get(index);
    }

    @Override
    public void toXML(XML xml) throws XMLStreamException {
        xml.start("calculator");
        xml.start("config");
        xml.add("size", size);
        xml.end();
        xml.start("buttons");

        xml.add("buttons", buttons);

        xml.end();
        xml.end();
    }

    public static class Builder {

        private int cols = 0;
        private int rows = 0;
        private int size = 48;
        private final List<Button> buttons = new ArrayList<>();

        public Builder setSize(int size) {
            this.size = size;
            return this;
        }

        public Builder addButtons(List<Button> buttons) {
            this.buttons.addAll(buttons);
            return this;
        }

        public Config build() {

            cols = 0;
            rows = 0;

            buttons.forEach((Button b) -> {
                if (b.getX() + b.getWidth() > cols) {
                    cols = b.getX() + b.getWidth();
                }
                if (b.getY() + b.getHeight() > rows) {
                    rows = b.getY() + b.getHeight();
                }
            });

            // Sort buttons so that the button in the top-left comes first,
            // then top-right, then bottom-left, finaly bottom right.
            buttons.sort((Button left, Button right) -> {
                if (left.getY() == right.getY()) {
                    return (left.getX() - right.getX());
                } else {
                    return left.getY() - right.getY();
                }
            });

            return new Config(cols, rows, size, buttons);
        }

    }

}


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

<TITLE>
net.floodlightcontroller.hub
</TITLE>

<META NAME="date" CONTENT="2013-08-27">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

net.floodlightcontroller.hub

Classes

Hub

HubTest


text:
package org.gradle.api.internal.tasks.compile.incremental.recomp;

import org.gradle.api.internal.tasks.compile.incremental.classpath.ClasspathSnapshot;
import org.gradle.api.internal.tasks.compile.incremental.deps.DependentsSet;
import org.gradle.api.tasks.incremental.InputFileDetails;

public class ClasspathEntryChangeProcessor {

    private final ClasspathChangeDependentsFinder dependentsFinder;

    public ClasspathEntryChangeProcessor(ClasspathSnapshot classpathSnapshot, PreviousCompilation previousCompilation) {
        this.dependentsFinder = new ClasspathChangeDependentsFinder(classpathSnapshot, previousCompilation);
    }

    public void processChange(InputFileDetails input, RecompilationSpec spec) {
        DependentsSet actualDependents = dependentsFinder.getActualDependents(input, input.getFile());
        if (actualDependents.isDependencyToAll()) {
            spec.setFullRebuildCause(actualDependents.getDescription(), input.getFile());
            return;
        }
        spec.getClassesToCompile().addAll(actualDependents.getDependentClasses());
    }
}


text:
import pytest

from azure.mixedreality.authentication._utils import generate_cv_base, retrieve_jwt_expiration_timestamp

class TestUtils:
    def test_generate_cv_base(self):
        cv = generate_cv_base()

        assert cv is not None
        assert len(cv) == 22

    def test_generate_cv_base_are_random(self):
        cv1 = generate_cv_base()
        cv2 = generate_cv_base()

        assert cv1 is not None
        assert cv2 is not None
        assert cv1 != cv2

    def test_retrieve_jwt_expiration_timestamp_with_padding(self):
        # Note: The trailing "." on the end indicates an empty signature indicating that this JWT is not signed.
        jwt_value = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYxMDgxMjI1MCIsIm5iZiI6IjE2MTA4MTI1NTAiLCJleHAiOiIxNjEwODk4NjUwIn0=."
        expected_expiration_timestamp = 1610898650 # 1/17/2021 3:50:50 PM UTC

        actual = retrieve_jwt_expiration_timestamp(jwt_value)

        assert actual is not None
        assert actual == expected_expiration_timestamp

    def test_retrieve_jwt_expiration_timestamp_no_padding(self):
        # Note: The trailing "." on the end indicates an empty signature indicating that this JWT is not signed.
        #       The trailing "=" has been removed to test without base64 padding, which is apparently expected for JWT.
        jwt_value = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYxMDgxMjI1MCIsIm5iZiI6IjE2MTA4MTI1NTAiLCJleHAiOiIxNjEwODk4NjUwIn0."
        expected_expiration_timestamp = 1610898650 # 1/17/2021 3:50:50 PM UTC

        actual = retrieve_jwt_expiration_timestamp(jwt_value)

        assert actual is not None
        assert actual == expected_expiration_timestamp

    def test_retrieve_jwt_expiration_timestamp_invalid_parameter(self):
        with pytest.raises(ValueError):
            retrieve_jwt_expiration_timestamp(None)

    def test_retrieve_jwt_expiration_timestamp_invalid_structure(self):
        # JWT value with missing signature section on the end.
        jwt_value = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYxMDgxMjI1MCIsIm5iZiI6IjE2MTA4MTI1NTAiLCJleHAiOiIxNjEwODk4NjUwIn0="

        with pytest.raises(ValueError):
            retrieve_jwt_expiration_timestamp(jwt_value)

    def test_retrieve_jwt_expiration_timestamp_invalid_payload(self):
        # JWT value with missing payload.
        jwt_value = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.."

        with pytest.raises(ValueError):
            retrieve_jwt_expiration_timestamp(jwt_value)

    def test_retrieve_jwt_expiration_timestamp_invalid_exp(self):
        # JWT value with missing expiration field.
        jwt_value = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYxMDgxMjI1MCIsIm5iZiI6IjE2MTA4MTI1NTAifQ==."

        with pytest.raises(ValueError):
            retrieve_jwt_expiration_timestamp(jwt_value)


text:
declare const styles: {
    root: string;
    rootIsSelectAllHidden: string;
    cell: string;
    cellIsCheck: string;
    rootIsAllSelected: string;
    cellWrapper: string;
    cellIsActionable: string;
    cellIsSizer: string;
    cellIsEmpty: string;
    cellIsResizing: string;
    collapseButton: string;
    collapseButtonIsCollapsed: string;
    nearIcon: string;
    filterChevron: string;
    sizingOverlay: string;
};
export = styles;


text:
"""Extension of the built-in unittest framework for floating-point comparisons.

Specific Extensions:

assertFloatEqual, assertFloatEqualAbs, and assertFloatEqualRel give fine-
grained control over how floating point numbers (or lists thereof) are tested
for equality.

assertContains and assertNotContains give more helpful error
messages when testing whether an observed item is present or absent in a set
of possiblities. Ditto assertGreaterThan, assertLessThan, assertBetween, and
assertIsProb (which is a special case of assertBetween requiring the result
to between 0 and 1).

assertSameItems and assertEqualItems test the items in a list
for pairwise identity and equality respectively (i.e. the observed and
expected values must have the same number of each item, though the order can
differ); assertNotEqualItems verifies that two lists do not contain equal sets
of items.

assertSimilarMeans and assertSimilarFreqs allow you to test stochastic results
by setting an explicit P-value and checking that the result is not improbable
given the expected P-value. Please use these instead of guessing confidence
intervals! The major advantage is that you can reset the P-value gloabally over
the whole test suite, so that rare failures don't occur every time.

assertIsPermutation checks that you get a permutation of an expected result that
differs from the original result, repeating the test a specified number of times
before giving up and assuming that the result is always the same.

"""
#from contextlib import contextmanager
import numpy; from numpy import testing, array, asarray, ravel, zeros, \
        logical_and, logical_or, isfinite
from unittest import main, TestCase as orig_TestCase, TestSuite, findTestCases
from cogent.util.misc import recursive_flatten
from cogent.maths.stats.test import t_two_sample, G_ind

__author__ = "Rob Knight"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__credits__ = ["Rob Knight", "Peter Maxwell", "Sandra Smit",
                    "Zongzhi Liu", "Micah Hamady", "Daniel McDonald"]
__license__ = "GPL"
__version__ = "1.5.3"
__maintainer__ = "Rob Knight"
__email__ = "rob@spot.colorado.edu"
__status__ = "Production"

## SUPPORT2425
#@contextmanager
#def numpy_err(**kw):
#    """a numpy err context manager.

#    **kw: pass to numpy.seterr(all=None, divide=None, over=None, under=None,
#    invalid=None)

#    Example:
#    with numpy_err(divide='raise'):
#        self.assertRaises(FloatingPointError, log, 0)
#    """
#    ori_err = numpy.geterr()
#    numpy.seterr(**kw)
#    try: yield None
#    finally: numpy.seterr(**ori_err)

class FakeRandom(object):
    """Drop-in substitute for random.random that provides items from list."""

    def __init__(self, data, circular=False):
        """Returns new FakeRandom object, using list of items in data.

        circular: if True (default is False), wraps the list around. Otherwise,
        raises IndexError when we run off the end of the list.

        WARNING: data must always be iterable, even if it's a single item.
        """
        self._data = data
        self._ptr = -1
        self._circular = circular

    def __call__(self, *args, **kwargs):
        """Returns next item from the list in self._data.

        Raises IndexError when we run out of data.
        """
        self._ptr += 1
        #wrap around if circular
        if self._circular:
            if self._ptr >= len(self._data):
                self._ptr = 0
        return self._data[self._ptr]

class TestCase(orig_TestCase):
    """Adds some additional utility methods to unittest.TestCase.

    Notably, adds facilities for dealing with floating point numbers,
    and some common templates for replicated tests.

    BEWARE: Do not start any method with 'test' unless you want it to actually
    run as a test suite in every instance!
    """
    _suite_pvalue = None # see TestCase._set_suite_pvalue()

    def _get_values_from_matching_dicts(self, d1, d2):
        """Gets corresponding values from matching dicts"""
        if set(d1) != set (d2):
            return None
        return d1.values(), [d2[k] for k in d1] #might not be in same order

    def errorCheck(self, call, known_errors):
        """Applies function to (data, error) tuples, checking for error
        """
        for (data, error) in known_errors:
            self.assertRaises(error, call, data)

    def valueCheck(self, call, known_values, arg_prefix='', eps=None):
        """Applies function to (data, expected) tuples, treating data as args
        """
        for (data, expected) in known_values:
                observed = eval('call(' + arg_prefix + 'data)')
                try:
                    allowed_diff = float(eps)
                except TypeError:
                    self.assertEqual(observed, expected)
                else:
                    self.assertFloatEqual(observed, expected, allowed_diff)

    def assertFloatEqualRel(self, obs, exp, eps=1e-6):
        """Tests whether two floating point numbers/arrays are approx. equal.

        Checks whether the distance is within epsilon relative to the value
        of the sum of observed and expected. Use this method when you expect
        the difference to be small relative to the magnitudes of the observed
        and expected values.

        Note: for arbitrary objects, need to compare the specific attribute
        that's numeric, not the whole object, using this method.
        """
        #do array check first
        #note that we can't use array ops to combine, because we need to check
        #at each element whether the expected is zero to do the test to avoid
        #floating point error.
        #WARNING: numpy iterates over objects that are not regular Python
        #floats/ints, so need to explicitly catch scalar values and prevent
        #cast to array if we want the exact object to print out correctly.
        is_array = False
        if hasattr(obs, 'keys') and hasattr(exp, 'keys'):   #both dicts?
            result = self._get_values_from_matching_dicts(obs, exp)
            if result:
                obs, exp = result
        else:
            try:
                iter(obs)
                iter(exp)
            except TypeError:
                obs = [obs]
                exp = [exp]
            else:
                try:
                    arr_obs = array(obs)
                    arr_exp = array(exp)
                    arr_diff = arr_obs - arr_exp
                    if arr_obs.shape != arr_exp.shape:
                        self.fail("Wrong shape: Got %s, but expected %s" % \
                            (`obs`, `exp`))
                    obs = arr_obs.ravel()
                    exp = arr_exp.ravel()
                    is_array=True
                except (TypeError, ValueError):
                    pass

        # shape mismatch can still get by...
        # explict cast is to work around bug in certain versions of numpy
        # installed version on osx 10.5
        if asarray(obs, object).shape != asarray(exp, object).shape:
            self.fail("Wrong shape: Got %s, but expected %s" % (obs, exp))

        for observed, expected in zip(obs, exp):
            #try the cheap comparison first
            if observed == expected:
                continue
            try:
                sum = float(observed + expected)
                diff = float(observed - expected)
                if (sum == 0):
                    if is_array:
                        self.failIf(abs(diff) > abs(eps), \
                            "Got %s, but expected %s (diff was %s)" % \
                            (`arr_obs`, `arr_exp`, `arr_diff`))
                    else:
                        self.failIf(abs(diff) > abs(eps), \
                            "Got %s, but expected %s (diff was %s)" % \
                            (`observed`, `expected`, `diff`))

                else:
                    if is_array:
                        self.failIf(abs(diff/sum) > abs(eps), \
                            "Got %s, but expected %s (diff was %s)" % \
                            (`arr_obs`, `arr_exp`, `arr_diff`))
                    else:
                        self.failIf(abs(diff/sum) > abs(eps), \
                            "Got %s, but expected %s (diff was %s)" % \
                            (`observed`, `expected`, `diff`))
            except (TypeError, ValueError, AttributeError, NotImplementedError):
                self.fail("Got %s, but expected %s" % \
                    (`observed`, `expected`))

    def assertFloatEqualAbs(self, obs, exp, eps=1e-6):
        """
        Tests whether two floating point numbers are approximately equal.

        Checks whether the absolute value of (a - b) is within epsilon. Use
        this method when you expect that one of the values should be very
        small, and the other should be zero.
        """
        #do array check first
        #note that we can't use array ops to combine, because we need to check
        #at each element whether the expected is zero to do the test to avoid
        #floating point error.
        if hasattr(obs, 'keys') and hasattr(exp, 'keys'):   #both dicts?
            result = self._get_values_from_matching_dicts(obs, exp)
            if result:
                obs, exp = result
        else:
            try:
                iter(obs)
                iter(exp)
            except TypeError:
                obs = [obs]
                exp = [exp]
            else:
                try:
                    arr_obs = array(obs)
                    arr_exp = array(exp)
                    if arr_obs.shape != arr_exp.shape:
                        self.fail("Wrong shape: Got %s, but expected %s" % \
                            (`obs`, `exp`))
                    diff = arr_obs - arr_exp
                    self.failIf(abs(diff).max() > eps, \
                        "Got %s, but expected %s (diff was %s)" % \
                        (`obs`, `exp`, `diff`))
                    return
                except (TypeError, ValueError):
                    pass
        #only get here if array comparison failed
        for observed, expected in zip(obs, exp):
            #cheap comparison first
            if observed == expected:
                continue
            try:
                diff = observed - expected
                self.failIf(abs(diff) > abs(eps),
                        "Got %s, but expected %s (diff was %s)" % \
                        (`observed`, `expected`, `diff`))
            except (TypeError, ValueError, AttributeError, NotImplementedError):
                self.fail("Got %s, but expected %s" % \
                    (`observed`, `expected`))

    def assertFloatEqual(self, obs, exp, eps=1e-6, rel_eps=None, \
                         abs_eps=None):
        """Tests whether two floating point numbers are approximately equal.

        If one of the arguments is zero, tests the absolute magnitude of the
        difference; otherwise, tests the relative magnitude.

        Use this method as a reasonable default.
        """
        obs = numpy.asarray(obs, dtype='O')
        exp = numpy.asarray(exp, dtype='O')
        obs = numpy.ravel(obs)
        exp = numpy.ravel(exp)

        if obs.shape != exp.shape:
            self.fail("Shape mismatch. Got, %s but expected %s" % (obs, exp))

        for observed, expected in zip(obs, exp):
            if self._is_equal(observed, expected):
                continue
            try:
                rel_eps = rel_eps or eps
                abs_eps = abs_eps or eps
                if (observed == 0) or (expected == 0):
                    self.assertFloatEqualAbs(observed, expected, abs_eps)
                else:
                    self.assertFloatEqualRel(observed, expected, rel_eps)
            except (TypeError, ValueError, AttributeError, NotImplementedError):
                self.fail("Got %s, but expected %s" % \
                        (`observed`, `expected`))

    def _is_equal(self, observed, expected):
        """Returns True if observed and expected are equal, False otherwise."""
        #errors to catch: TypeError when obs is None
        tolist_errors = (AttributeError, ValueError, TypeError)

        try:
            obs = observed.tolist()
        except tolist_errors:
            obs = observed
        try:
            exp = expected.tolist()
        except tolist_errors:
            exp = expected
        return obs == exp

    def failUnlessEqual(self, observed, expected, msg=None):
        """Fail if the two objects are unequal as determined by !=

        Overridden to make error message enforce order of observed, expected.
        Use numpy.testing.assert_equal if ValueError, TypeError raised.
        """
        try:
            if not self._is_equal(observed, expected):
                raise self.failureException, \
                (msg or 'Got %s, but expected %s' % (`observed`, `expected`))
        except (ValueError, TypeError), e:
            #The truth value of an array with more than one element is
            #ambiguous. Use a.any() or a.all()
            #descriptor 'tolist' of 'numpy.generic' object needs an argument
            testing.assert_equal(observed, expected)

    def failIfEqual(self, observed, expected, msg=None):
        """Fail if the two objects are equal as determined by =="""
        try:
            self.failUnlessEqual(observed, expected)
        except self.failureException:
            pass
        else:
            raise self.failureException, \
            (msg or 'Observed %s and expected %s: shouldn\'t test equal'\
                % (`observed`, `expected`))

        #following needed to get our version instead of unittest's
    assertEqual = assertEquals = failUnlessEqual

    assertNotEqual = assertNotEquals = failIfEqual

    def assertEqualItems(self, observed, expected, msg=None):
        """Fail if the two items contain unequal elements"""
        obs_items = list(observed)
        exp_items = list(expected)
        if len(obs_items) != len(exp_items):
            raise self.failureException, \
            (msg or 'Observed and expected are different lengths: %s and %s' \
            % (len(obs_items), len(exp_items)))

        obs_items.sort()
        exp_items.sort()
        for index, (obs, exp) in enumerate(zip(obs_items, exp_items)):
            if obs != exp:
                raise self.failureException, \
                (msg or 'Observed %s and expected %s at sorted index %s' \
                % (obs, exp, index))

    def assertSameItems(self, observed, expected, msg=None):
        """Fail if the two items contain non-identical elements"""
        obs_items = list(observed)
        exp_items = list(expected)
        if len(obs_items) != len(exp_items):
            raise self.failureException, \
            (msg or 'Observed and expected are different lengths: %s and %s' \
            % (len(obs_items), len(exp_items)))

        obs_ids = [(id(i), i) for i in obs_items]
        exp_ids = [(id(i), i) for i in exp_items]
        obs_ids.sort()
        exp_ids.sort()
        for index, (obs, exp) in enumerate(zip(obs_ids, exp_ids)):
            o_id, o = obs
            e_id, e = exp
            if o_id != e_id:    #i.e. the ids are different
                raise self.failureException, \
                (msg or \
                'Observed %s <%s> and expected %s <%s> at sorted index %s' \
                % (o, o_id, e, e_id, index))

    def assertNotEqualItems(self, observed, expected, msg=None):
        """Fail if the two items contain only equal elements when sorted"""
        try:
            self.assertEqualItems(observed, expected, msg)
        except:
            pass
        else:
            raise self.failureException, \
            (msg or 'Observed %s has same items as %s'%(`observed`, `expected`))

    def assertContains(self, observed, item, msg=None):
        """Fail if item not in observed"""
        try:
            if item in observed:
                return
        except (TypeError, ValueError):
            pass
        raise self.failureException, \
        (msg or 'Item %s not found in %s' % (`item`, `observed`))

    def assertNotContains(self, observed, item, msg=None):
        """Fail if item in observed"""
        try:
            if item not in observed:
                return
        except (TypeError, ValueError):
            return
        raise self.failureException, \
        (msg or 'Item %s should not have been in %s' % (`item`, `observed`))

    def assertGreaterThan(self, observed, value, msg=None):
        """Fail if observed is <= value"""
        try:
            if value is None or observed is None:
                raise ValueError
            if (asarray(observed) > value).all():
                return
        except:
            pass
        raise self.failureException, \
        (msg or 'Observed %s has elements <= %s' % (`observed`, `value`))

    def assertLessThan(self, observed, value, msg=None):
        """Fail if observed is >= value"""
        try:
            if value is None or observed is None:
                raise ValueError
            if (asarray(observed) < value).all():
                return
        except:
            pass
        raise self.failureException, \
        (msg or 'Observed %s has elements >= %s' % (`observed`, `value`))

    def assertIsBetween(self, observed, min_value, max_value, msg=None):
        """Fail if observed is not between min_value and max_value"""
        try:
            if min_value is None or max_value is None or observed is None:
                raise ValueError

            if min_value >= max_value:
                raise ValueError

            if logical_and(asarray(observed) < max_value,
                           asarray(observed) > min_value).all():
                return
        except:
            pass
        raise self.failureException, \
        (msg or 'Observed %s has elements not between %s, %s' % \
        (`observed`, `min_value`, `max_value`))

    def assertIsNotBetween(self, observed, min_value, max_value, msg=None):
        """Fail if observed is between min_value and max_value"""
        try:
            if min_value is None or max_value is None or observed is None:
                raise ValueError

            if min_value >= max_value:
                raise ValueError

            if logical_or(asarray(observed) >= max_value,
                          asarray(observed) <= min_value).all():
                return
        except:
            pass
        raise self.failureException, \
        (msg or 'Observed %s has elements between %s, %s' % \
        (`observed`, `min_value`, `max_value`))

    def assertIsProb(self, observed, msg=None):
        """Fail is observed is not between 0.0 and 1.0"""
        try:
            if observed is None:
                raise ValueError
            if (asarray(observed) >= 0.0).all() and \
               (asarray(observed) <= 1.0).all():
                return
        except:
            pass
        raise self.failureException, \
        (msg or 'Observed %s has elements that are not probs' % (`observed`))

    def _set_suite_pvalue(self, pvalue):
        """Sets the test suite pvalue to be used in similarity tests

        This value is by default None. The pvalue used in this case is
        specified in the test module itself. The purpose of this method is to
        set the pvalue to be used when running a massive test suite
        """
        self._suite_pvalue = pvalue

    def assertSimilarMeans(self, observed, expected, pvalue=0.01, msg=None):
        """Fail if observed p is lower than pvalue"""
        if self._suite_pvalue:
            pvalue = self._suite_pvalue

        observed, expected = asarray(observed), asarray(expected)

        t, p = t_two_sample(observed, expected)

        if p > pvalue:
            return
        elif p is None or not isfinite(p): #handle case where all elements were the same
            if not observed.shape:
                observed = observed.reshape((1,))
            if not expected.shape:
                expected = expected.reshape((1,))
            if observed[0] == expected[0]:
                return
        else:
            raise self.failureException, \
            (msg or 'p-value %s, t-test p %s' % (`pvalue`, `p`))

    def assertSimilarFreqs(self, observed, expected, pvalue=0.01, msg=None):
        """Fail if observed p is lower than pvalue"""
        if self._suite_pvalue:
            pvalue = self._suite_pvalue

        obs_ravel = ravel(asarray(observed))
        exp_ravel = ravel(asarray(expected))

        m = zeros((2,len(obs_ravel)))
        m[0,:] = obs_ravel
        m[1,:] = exp_ravel

        G, p = G_ind(m)

        if p > pvalue:
            return
        else:
            raise self.failureException, \
            (msg or 'p-value %s, G-test p %s' % (`pvalue`, `p`))

    def assertIsPermutation(self, observed, items, msg=None):
        """Fail if observed is not a permutation of items"""
        try:
            self.assertEqualItems(observed, items)
            self.assertNotEqual(observed, items)
            return
        except:
            pass
        raise self.failureException, \
        (msg or 'Observed %s is not a different permutation of items %s' % \
        (`observed`, `items`))

    def assertSameObj(self, observed, expected, msg=None):
        """Fail if 'observed is not expected'"""
        try:
            if observed is expected:
                return
        except:
            pass
        raise self.failureException, \
        (msg or 'Observed %s is not the same as expected %s' % \
        (`observed`, `expected`))

    def assertNotSameObj(self, observed, expected, msg=None):
        """Fail if 'observed is expected'"""
        try:
            if observed is not expected:
                return
        except:
            pass
        raise self.failureException, \
        (msg or 'Observed %s is the same as expected %s' % \
        (`observed`, `expected`))


text:
mod array_value;
#[deny(missing_docs)]
mod basic_value_use;
#[deny(missing_docs)]
mod call_site_value;
mod callable_value;
mod enums;
mod float_value;
mod fn_value;
mod generic_value;
mod global_value;
mod instruction_value;
mod int_value;
mod metadata_value;
mod phi_value;
mod ptr_value;
mod struct_value;
mod traits;
mod vec_value;

use crate::support::{to_c_str, LLVMString};
pub use crate::values::array_value::ArrayValue;
pub use crate::values::basic_value_use::BasicValueUse;
pub use crate::values::call_site_value::CallSiteValue;
pub use crate::values::callable_value::CallableValue;
pub use crate::values::enums::{AggregateValueEnum, AnyValueEnum, BasicMetadataValueEnum, BasicValueEnum};
pub use crate::values::float_value::FloatValue;
pub use crate::values::fn_value::FunctionValue;
pub use crate::values::generic_value::GenericValue;
pub use crate::values::global_value::GlobalValue;
#[llvm_versions(7.0..=latest)]
pub use crate::values::global_value::UnnamedAddress;
pub use crate::values::instruction_value::{InstructionOpcode, InstructionValue};
pub use crate::values::int_value::IntValue;
pub use crate::values::metadata_value::{MetadataValue, FIRST_CUSTOM_METADATA_KIND_ID};
pub use crate::values::phi_value::PhiValue;
pub use crate::values::ptr_value::PointerValue;
pub use crate::values::struct_value::StructValue;
pub(crate) use crate::values::traits::AsValueRef;
pub use crate::values::traits::{AggregateValue, AnyValue, BasicValue, FloatMathValue, IntMathValue, PointerMathValue};
pub use crate::values::vec_value::VectorValue;
#[cfg(feature = "internal-getters")]
use crate::LLVMReference;

use llvm_sys::core::{
    LLVMDumpValue, LLVMGetFirstUse, LLVMGetSection, LLVMIsAInstruction, LLVMIsConstant, LLVMIsNull, LLVMIsUndef,
    LLVMPrintTypeToString, LLVMPrintValueToString, LLVMReplaceAllUsesWith, LLVMSetSection, LLVMTypeOf,
};
use llvm_sys::prelude::{LLVMTypeRef, LLVMValueRef};

use std::ffi::CStr;
use std::fmt;
use std::marker::PhantomData;

#[derive(PartialEq, Eq, Clone, Copy, Hash)]
struct Value<'ctx> {
    value: LLVMValueRef,
    _marker: PhantomData<&'ctx ()>,
}

impl<'ctx> Value<'ctx> {
    pub(crate) unsafe fn new(value: LLVMValueRef) -> Self {
        debug_assert!(
            !value.is_null(),
            "This should never happen since containing struct should check null ptrs"
        );

        Value {
            value,
            _marker: PhantomData,
        }
    }

    fn is_instruction(self) -> bool {
        unsafe { !LLVMIsAInstruction(self.value).is_null() }
    }

    fn as_instruction(self) -> Option<InstructionValue<'ctx>> {
        if !self.is_instruction() {
            return None;
        }

        unsafe { Some(InstructionValue::new(self.value)) }
    }

    fn is_null(self) -> bool {
        unsafe { LLVMIsNull(self.value) == 1 }
    }

    fn is_const(self) -> bool {
        unsafe { LLVMIsConstant(self.value) == 1 }
    }

    // TODOC: According to https://stackoverflow.com/questions/21593752/llvm-how-to-pass-a-name-to-constantint
    // you can't use set_name name on a constant(by can't, I mean it wont do anything), unless it's also a global.
    // So, you can set names on variables (ie a function parameter)
    // REVIEW: It'd be great if we could encode this into the type system somehow. For example,
    // add a ParamValue wrapper type that always have it but conditional types (IntValue<Variable>)
    // that also have it. This isn't a huge deal though, since it hasn't proven to be UB so far
    fn set_name(self, name: &str) {
        #[cfg(any(feature = "llvm4-0", feature = "llvm5-0", feature = "llvm6-0"))]
        {
            use crate::support::to_c_str;
            use llvm_sys::core::LLVMSetValueName;

            let c_string = to_c_str(name);

            unsafe {
                LLVMSetValueName(self.value, c_string.as_ptr());
            }
        }
        #[cfg(not(any(feature = "llvm4-0", feature = "llvm5-0", feature = "llvm6-0")))]
        {
            use llvm_sys::core::LLVMSetValueName2;

            unsafe { LLVMSetValueName2(self.value, name.as_ptr() as *const ::libc::c_char, name.len()) }
        }
    }

    // get_name should *not* return a LLVMString, because it is not an owned value AFAICT
    // TODO: Should make this take ownership of self. But what is the lifetime of the string? 'ctx?
    fn get_name(&self) -> &CStr {
        #[cfg(any(feature = "llvm4-0", feature = "llvm5-0", feature = "llvm6-0"))]
        let ptr = unsafe {
            use llvm_sys::core::LLVMGetValueName;

            LLVMGetValueName(self.value)
        };
        #[cfg(not(any(feature = "llvm4-0", feature = "llvm5-0", feature = "llvm6-0")))]
        let ptr = unsafe {
            use llvm_sys::core::LLVMGetValueName2;
            let mut len = 0;

            LLVMGetValueName2(self.value, &mut len)
        };

        unsafe { CStr::from_ptr(ptr) }
    }

    fn is_undef(self) -> bool {
        unsafe { LLVMIsUndef(self.value) == 1 }
    }

    fn get_type(self) -> LLVMTypeRef {
        unsafe { LLVMTypeOf(self.value) }
    }

    fn print_to_string(self) -> LLVMString {
        unsafe { LLVMString::new(LLVMPrintValueToString(self.value)) }
    }

    fn print_to_stderr(self) {
        unsafe { LLVMDumpValue(self.value) }
    }

    // REVIEW: I think this is memory safe, though it may result in an IR error
    // if used incorrectly, which is OK.
    fn replace_all_uses_with(self, other: LLVMValueRef) {
        // LLVM may infinite-loop when they aren't distinct, which is UB in C++.
        if self.value != other {
            unsafe { LLVMReplaceAllUsesWith(self.value, other) }
        }
    }

    pub fn get_first_use(self) -> Option<BasicValueUse<'ctx>> {
        let use_ = unsafe { LLVMGetFirstUse(self.value) };

        if use_.is_null() {
            return None;
        }

        unsafe { Some(BasicValueUse::new(use_)) }
    }

    /// Gets the section of the global value
    pub fn get_section(&self) -> Option<&CStr> {
        let ptr = unsafe { LLVMGetSection(self.value) };

        if ptr.is_null() {
            return None;
        }

        // On MacOS we need to remove ',' before section name
        if cfg!(target_os = "macos") {
            Some(unsafe { CStr::from_ptr(ptr.add(1)) })
        } else {
            Some(unsafe { CStr::from_ptr(ptr) })
        }
    }

    /// Sets the section of the global value
    fn set_section(self, section: Option<&str>) {
        #[cfg(target_os = "macos")]
        let section = section.map(|s| format!(",{}", s));

        let c_string = section.as_deref().map(to_c_str);

        unsafe {
            LLVMSetSection(
                self.value,
                // The as_ref call is important here so that we don't drop the cstr mid use
                c_string.as_ref().map(|s| s.as_ptr()).unwrap_or(std::ptr::null()),
            )
        }
    }
}

impl fmt::Debug for Value<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let llvm_value = self.print_to_string();
        let llvm_type = unsafe { CStr::from_ptr(LLVMPrintTypeToString(LLVMTypeOf(self.value))) };
        let name = self.get_name();
        let is_const = self.is_const();
        let is_null = self.is_null();
        let is_undef = self.is_undef();

        f.debug_struct("Value")
            .field("name", &name)
            .field("address", &self.value)
            .field("is_const", &is_const)
            .field("is_null", &is_null)
            .field("is_undef", &is_undef)
            .field("llvm_value", &llvm_value)
            .field("llvm_type", &llvm_type)
            .finish()
    }
}

#[cfg(feature = "internal-getters")]
impl<T> LLVMReference<LLVMValueRef> for T
where
    T: AsValueRef,
{
    unsafe fn get_ref(&self) -> LLVMValueRef {
        self.as_value_ref()
    }
}


text:
<?php
/* SVN FILE: $Id$ */
/**
 * CookieComponentTest file
 *
 * Long description for file
 *
 * PHP versions 4 and 5
 *
 * CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite>
 * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 *
 *  Licensed under The Open Group Test Suite License
 *  Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright     Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 * @link          https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests
 * @package       cake
 * @subpackage    cake.tests.cases.libs.controller.components
 * @since         CakePHP(tm) v 1.2.0.5435
 * @version       $Revision$
 * @modifiedby    $LastChangedBy$
 * @lastmodified  $Date$
 * @license       http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
 */
App::import('Core', array('Component', 'Controller', 'Cookie'));
/**
 * CookieComponentTestController class
 *
 * @package       cake
 * @subpackage    cake.tests.cases.libs.controller.components
 */
class CookieComponentTestController extends Controller {
/**
 * components property
 *
 * @var array
 * @access public
 */
	var $components = array('Cookie');
/**
 * beforeFilter method
 *
 * @access public
 * @return void
 */
	function beforeFilter() {
		$this->Cookie->name = 'CakeTestCookie';
		$this->Cookie->time = 10;
		$this->Cookie->path = '/';
		$this->Cookie->domain = '';
		$this->Cookie->secure = false;
		$this->Cookie->key = 'somerandomhaskey';
	}
}
/**
 * CookieComponentTest class
 *
 * @package       cake
 * @subpackage    cake.tests.cases.libs.controller.components
 */
class CookieComponentTest extends CakeTestCase {
/**
 * Controller property
 *
 * @var CookieComponentTestController
 * @access public
 */
	var $Controller;
/**
 * start
 *
 * @access public
 * @return void
 */
	function start() {
		$this->Controller = new CookieComponentTestController();
		$this->Controller->constructClasses();
		$this->Controller->Component->initialize($this->Controller);
		$this->Controller->beforeFilter();
		$this->Controller->Component->startup($this->Controller);
		$this->Controller->Cookie->destroy();
	}
/**
 * end
 *
 * @access public
 * @return void
 */
	function end() {
		$this->Controller->Cookie->destroy();
	}
/**
 * testCookieName
 *
 * @access public
 * @return void
 */
	function testCookieName() {
		$this->assertEqual($this->Controller->Cookie->name, 'CakeTestCookie');
	}
/**
 * testSettingEncryptedCookieData
 *
 * @access public
 * @return void
 */
	function testSettingEncryptedCookieData() {
		$this->Controller->Cookie->write('Encrytped_array', array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!'));
		$this->Controller->Cookie->write('Encrytped_multi_cookies.name', 'CakePHP');
		$this->Controller->Cookie->write('Encrytped_multi_cookies.version', '1.2.0.x');
		$this->Controller->Cookie->write('Encrytped_multi_cookies.tag', 'CakePHP Rocks!');
	}
/**
 * testReadEncryptedCookieData
 *
 * @access public
 * @return void
 */
	function testReadEncryptedCookieData() {
		$data = $this->Controller->Cookie->read('Encrytped_array');
		$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Encrytped_multi_cookies');
		$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
		$this->assertEqual($data, $expected);
	}
/**
 * testSettingPlainCookieData
 *
 * @access public
 * @return void
 */
	function testSettingPlainCookieData() {
		$this->Controller->Cookie->write('Plain_array', array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!'), false);
		$this->Controller->Cookie->write('Plain_multi_cookies.name', 'CakePHP', false);
		$this->Controller->Cookie->write('Plain_multi_cookies.version', '1.2.0.x', false);
		$this->Controller->Cookie->write('Plain_multi_cookies.tag', 'CakePHP Rocks!', false);
	}
/**
 * testReadPlainCookieData
 *
 * @access public
 * @return void
 */
	function testReadPlainCookieData() {
		$data = $this->Controller->Cookie->read('Plain_array');
		$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Plain_multi_cookies');
		$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
		$this->assertEqual($data, $expected);
	}
/**
 * testWritePlainCookieArray
 *
 * @access public
 * @return void
 */
	function testWritePlainCookieArray() {
		$this->Controller->Cookie->write(array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'), null, false);

		$this->assertEqual($this->Controller->Cookie->read('name'), 'CakePHP');
		$this->assertEqual($this->Controller->Cookie->read('version'), '1.2.0.x');
		$this->assertEqual($this->Controller->Cookie->read('tag'), 'CakePHP Rocks!');

		$this->Controller->Cookie->del('name');
		$this->Controller->Cookie->del('version');
		$this->Controller->Cookie->del('tag');
	}
/**
 * testReadingCookieValue
 *
 * @access public
 * @return void
 */
	function testReadingCookieValue() {
		$data = $this->Controller->Cookie->read();
		$expected = array(
			'Encrytped_array' => array(
				'name' => 'CakePHP',
				'version' => '1.2.0.x',
				'tag' => 'CakePHP Rocks!'),
			'Encrytped_multi_cookies' => array(
				'name' => 'CakePHP',
				'version' => '1.2.0.x',
				'tag' => 'CakePHP Rocks!'),
			'Plain_array' => array(
				'name' => 'CakePHP',
				'version' => '1.2.0.x',
				'tag' => 'CakePHP Rocks!'),
			'Plain_multi_cookies' => array(
				'name' => 'CakePHP',
				'version' => '1.2.0.x',
				'tag' => 'CakePHP Rocks!'));
		$this->assertEqual($data, $expected);
	}
/**
 * testDeleteCookieValue
 *
 * @access public
 * @return void
 */
	function testDeleteCookieValue() {
		$this->Controller->Cookie->del('Encrytped_multi_cookies.name');
		$data = $this->Controller->Cookie->read('Encrytped_multi_cookies');
		$expected = array('version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
		$this->assertEqual($data, $expected);

		$this->Controller->Cookie->del('Encrytped_array');
		$data = $this->Controller->Cookie->read('Encrytped_array');
		$expected = array();
		$this->assertEqual($data, $expected);

		$this->Controller->Cookie->del('Plain_multi_cookies.name');
		$data = $this->Controller->Cookie->read('Plain_multi_cookies');
		$expected = array('version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
		$this->assertEqual($data, $expected);

		$this->Controller->Cookie->del('Plain_array');
		$data = $this->Controller->Cookie->read('Plain_array');
		$expected = array();
		$this->assertEqual($data, $expected);
	}
/**
 * testSettingCookiesWithArray
 *
 * @access public
 * @return void
 */
	function testSettingCookiesWithArray() {
		$this->Controller->Cookie->destroy();

		$this->Controller->Cookie->write(array('Encrytped_array' => array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!')));
		$this->Controller->Cookie->write(array('Encrytped_multi_cookies.name' => 'CakePHP'));
		$this->Controller->Cookie->write(array('Encrytped_multi_cookies.version' => '1.2.0.x'));
		$this->Controller->Cookie->write(array('Encrytped_multi_cookies.tag' => 'CakePHP Rocks!'));

		$this->Controller->Cookie->write(array('Plain_array' => array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!')), null, false);
		$this->Controller->Cookie->write(array('Plain_multi_cookies.name' => 'CakePHP'), null, false);
		$this->Controller->Cookie->write(array('Plain_multi_cookies.version' => '1.2.0.x'), null, false);
		$this->Controller->Cookie->write(array('Plain_multi_cookies.tag' => 'CakePHP Rocks!'), null, false);
	}
/**
 * testReadingCookieArray
 *
 * @access public
 * @return void
 */
	function testReadingCookieArray() {
		$data = $this->Controller->Cookie->read('Encrytped_array.name');
		$expected = 'CakePHP';
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Encrytped_array.version');
		$expected = '1.2.0.x';
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Encrytped_array.tag');
		$expected = 'CakePHP Rocks!';
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Encrytped_multi_cookies.name');
		$expected = 'CakePHP';
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Encrytped_multi_cookies.version');
		$expected = '1.2.0.x';
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Encrytped_multi_cookies.tag');
		$expected = 'CakePHP Rocks!';
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Plain_array.name');
		$expected = 'CakePHP';
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Plain_array.version');
		$expected = '1.2.0.x';
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Plain_array.tag');
		$expected = 'CakePHP Rocks!';
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Plain_multi_cookies.name');
		$expected = 'CakePHP';
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Plain_multi_cookies.version');
		$expected = '1.2.0.x';
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Plain_multi_cookies.tag');
		$expected = 'CakePHP Rocks!';
		$this->assertEqual($data, $expected);
	}
/**
 * testReadingCookieDataOnStartup
 *
 * @access public
 * @return void
 */
	function testReadingCookieDataOnStartup() {
		$this->Controller->Cookie->destroy();

		$data = $this->Controller->Cookie->read('Encrytped_array');
		$expected = array();
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Encrytped_multi_cookies');
		$expected = array();
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Plain_array');
		$expected = array();
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Plain_multi_cookies');
		$expected = array();
		$this->assertEqual($data, $expected);

		$_COOKIE['CakeTestCookie'] = array(
				'Encrytped_array' => $this->__encrypt(array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!')),
				'Encrytped_multi_cookies' => array(
						'name' => $this->__encrypt('CakePHP'),
						'version' => $this->__encrypt('1.2.0.x'),
						'tag' => $this->__encrypt('CakePHP Rocks!')),
				'Plain_array' => 'name|CakePHP,version|1.2.0.x,tag|CakePHP Rocks!',
				'Plain_multi_cookies' => array(
						'name' => 'CakePHP',
						'version' => '1.2.0.x',
						'tag' => 'CakePHP Rocks!'));
		$this->Controller->Cookie->startup();

		$data = $this->Controller->Cookie->read('Encrytped_array');
		$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Encrytped_multi_cookies');
		$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Plain_array');
		$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Plain_multi_cookies');
		$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
		$this->assertEqual($data, $expected);
		$this->Controller->Cookie->destroy();
		unset($_COOKIE['CakeTestCookie']);
	}
/**
 * testReadingCookieDataWithoutStartup
 *
 * @access public
 * @return void
 */
	function testReadingCookieDataWithoutStartup() {
		$data = $this->Controller->Cookie->read('Encrytped_array');
		$expected = array();
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Encrytped_multi_cookies');
		$expected = array();
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Plain_array');
		$expected = array();
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Plain_multi_cookies');
		$expected = array();
		$this->assertEqual($data, $expected);

		$_COOKIE['CakeTestCookie'] = array(
				'Encrytped_array' => $this->__encrypt(array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!')),
				'Encrytped_multi_cookies' => array(
						'name' => $this->__encrypt('CakePHP'),
						'version' => $this->__encrypt('1.2.0.x'),
						'tag' => $this->__encrypt('CakePHP Rocks!')),
				'Plain_array' => 'name|CakePHP,version|1.2.0.x,tag|CakePHP Rocks!',
				'Plain_multi_cookies' => array(
						'name' => 'CakePHP',
						'version' => '1.2.0.x',
						'tag' => 'CakePHP Rocks!'));

		$data = $this->Controller->Cookie->read('Encrytped_array');
		$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Encrytped_multi_cookies');
		$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Plain_array');
		$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
		$this->assertEqual($data, $expected);

		$data = $this->Controller->Cookie->read('Plain_multi_cookies');
		$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
		$this->assertEqual($data, $expected);
		$this->Controller->Cookie->destroy();
		unset($_COOKIE['CakeTestCookie']);
	}
/**
 * encrypt method
 *
 * @param mixed $value
 * @return string
 * @access private
 */
	function __encrypt($value) {
		if (is_array($value)) {
			$value = $this->__implode($value);
		}
		return "Q2FrZQ==." . base64_encode(Security::cipher($value, $this->Controller->Cookie->key));
	}
/**
 * implode method
 *
 * @param array $value
 * @return string
 * @access private
 */
	function __implode($array) {
		$string = '';
		foreach ($array as $key => $value) {
			$string .= ',' . $key . '|' . $value;
		}
		return substr($string, 1);
	}
}
?>


text:
require 'spec_helper'

RSpec.describe ::GeoWorks::GeoWorksShowPresenter do
  let(:solr_document) { SolrDocument.new(attributes) }
  let(:ability) { nil }

  describe "delegated methods" do
    let(:attributes)  { { "geo_mime_type_tesim" => ['image/tiff; gdal-format=GTiff'] } }
    subject { described_class.new(solr_document, ability) }

    describe "#first" do
      it "delegates to solr document" do
        expect(subject.first('geo_mime_type_tesim')).to eq('image/tiff; gdal-format=GTiff')
      end
    end

    describe "#has?" do
      it "delegates to solr document" do
        expect(subject.has?('geo_mime_type_tesim')).to be_truthy
      end
    end
  end

  describe "#attribute_to_html" do
    let(:attributes) { FactoryGirl.create(:raster_work).to_solr }
    let(:attribute_renderer) { double('attribute_renderer') }
    let(:coverage_renderer) { double('coverage_renderer') }

    subject { described_class.new(solr_document, ability) }

    before do
      allow(Hyrax::Renderers::AttributeRenderer).to receive(:new).and_return(attribute_renderer)
      allow(GeoWorks::CoverageRenderer).to receive(:new).and_return(coverage_renderer)
    end

    it "uses a CoverageRenderer when the field is coverage" do
      expect(coverage_renderer).to receive(:render)
      subject.attribute_to_html(:coverage)
    end

    it "uses an AttributeRenderer when the field is not coverage" do
      expect(attribute_renderer).to receive(:render)
      subject.attribute_to_html(:language)
    end
  end
end


text:
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>

#include "../libutils/strutils.h"
#include "IPConnection.h"
#include "IPSupervisor.h"

#ifdef WIN32
#define SHUT_RDWR SD_BOTH
//	#define EAGAIN WSAEWOULDBLOCK
//	#define EWOULDBLOCK WSAEWOULDBLOCK
#endif

CIPConnection::CIPConnection(SOCKET socket, string Name)
{
	m_Socket = socket;
	m_Connected = (socket!=INVALID_SOCKET);
	m_ConnectString = "@"+Name+"{"+itoa(socket)+"}";
}

CIPConnection::~CIPConnection(void)
{
	CLog::Default()->Printf(5, "Delete %s connection %p", (m_Socket == INVALID_SOCKET ? "closed":"active"), this);

	if (m_Socket != INVALID_SOCKET)
		Disconnect();

}

void CIPConnection::Connect(string ConnectString)
{
	m_ConnectString = ConnectString;
	string addr, port;
	int pos = ConnectString.find(':');
	if (pos==string::npos)
		throw CHaException(CHaException::ErrConnectStringError, "Bad connect string (%s)", ConnectString.c_str());

	addr = ConnectString.substr(0, pos);
	port = ConnectString.substr(pos+1);

	//----------------------
	// Create a SOCKET for connecting to server
	m_Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (m_Socket == INVALID_SOCKET)
		throw CHaException(CHaException::ErrCreateSocketError, "Error at socket(): %ld", WSAGetLastError());

	//----------------------
	// The sockaddr_in structure specifies the address family,
	// IP address, and port of the server to be connected to.
	sockaddr_in clientService;
	clientService.sin_family = AF_INET;
	clientService.sin_port = htons( atoi(port.c_str()) );

// If the user input is an alpha name for the host, use gethostbyname()
// If not, get host by addr (assume IPv4)
    if (isalpha(addr.c_str()[0]))
	{        /* host address is a name */
		//getaddrinfo()
		struct hostent *remoteHost = gethostbyname(addr.c_str());
		if (remoteHost == NULL)
		{
			throw CHaException(CHaException::ErrConnectError, "Cannot resolve <%s>", addr.c_str());
		}

		if (remoteHost->h_addrtype!= AF_INET)
		{
			throw CHaException(CHaException::ErrConnectError, "Invalid address type <%s>", addr.c_str());
		}

		clientService.sin_addr.s_addr = *(u_long *) remoteHost->h_addr_list[0];
    }
	else
	{
        clientService.sin_addr.s_addr = inet_addr(addr.c_str());
        if (clientService.sin_addr.s_addr == INADDR_NONE)
			throw CHaException(CHaException::ErrConnectError, "The IPv4 address <%s> entered must be a legal address. ", addr.c_str());
    }

	//----------------------
	// Connect to server.
	if ( connect( m_Socket, (sockaddr*) &clientService, sizeof(clientService) ) == SOCKET_ERROR)
		throw CHaException(CHaException::ErrConnectError, "Error at connect to %s: %ld", ConnectString.c_str(), WSAGetLastError());

	if (m_Timeout )
	{
		struct timeval tv;
		tv.tv_sec = m_Timeout;
		tv.tv_usec = 0;
		setsockopt (m_Socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof (tv) );
	}

	int param = 1;
	setsockopt (m_Socket, IPPROTO_TCP, TCP_NODELAY, (char*)&param, sizeof (param) );
	setsockopt (m_Socket, SOL_SOCKET, SO_KEEPALIVE, (char*)&param, sizeof (param) );
	m_Connected = true;
}

void CIPConnection::Disconnect()
{
	CLog::Default()->Printf(5, "Disconnect %s connection %p/%d", (m_Socket == INVALID_SOCKET ? "closed":"active"), this, m_Socket);

	shutdown(m_Socket, SHUT_RDWR);
#ifdef WIN32
	closesocket(m_Socket);
#else
	close(m_Socket);
#endif
	m_Socket=INVALID_SOCKET;
	m_Connected = false;
}

void CIPConnection::Send(const char *Buffer, size_t Size)
{
	int l = send(m_Socket, Buffer, Size, 0);

	if (l!=Size)
		throw CHaException(CHaException::ErrSendError, "Error at send(): %ld", WSAGetLastError());
}

void CIPConnection::Recv(char *Buffer, size_t &Size, bool bWaitAll)
{
	if (false && m_Timeout>0)
	{
		fd_set fd_recv;
		FD_ZERO(&fd_recv);
		FD_SET(m_Socket, &fd_recv);
		timeval t;
		t.tv_sec=m_Timeout;
		t.tv_usec=0;

		int sel = select(m_Socket+1, &fd_recv, NULL, NULL, &t);
		if (sel==SOCKET_ERROR)
			throw CHaException(CHaException::ErrRecvError, "Error at select(): %ld", WSAGetLastError());
		else if (sel==0)
		{
			Size=0;
			return;
		}
	}

	int l = recv(m_Socket, Buffer, Size, bWaitAll?MSG_WAITALL:0);

	if (l==SOCKET_ERROR)
	{
#ifdef WIN32
		if (WSAGetLastError()==WSAETIMEDOUT)
#else
		if (WSAGetLastError()==EAGAIN || WSAGetLastError()==0)
#endif
		{
			if (m_Timeout==0)
				Disconnect();

			Size = 0;
			return;
		}

		throw CHaException(CHaException::ErrRecvError, "Error at recv(%s): %ld (%s)", m_ConnectString.c_str(), WSAGetLastError(), strerror(WSAGetLastError()));
	}

	if (l==0)
	{
		int err = WSAGetLastError();
#ifdef WIN32
		if (err==WSAETIMEDOUT)
#else
		if (err==EAGAIN || err==0)
#endif
		{
			Disconnect();
			Size = 0;
			return;
		}

		throw CHaException(CHaException::ErrRecvError, "Error at recv(%s) l==0 : %ld (%s)", m_ConnectString.c_str(), WSAGetLastError(), strerror(WSAGetLastError()));
	}

	Size = l;
}

void CIPConnection::OnSelect(CSupervisor *superviser)
{
	superviser->OnRecieveEx(this);
}

void CIPConnection::SetTimeout(int Timeout)
{
	CConnection::SetTimeout(Timeout);

	if (m_Socket!=SOCKET_ERROR )
	{
		struct timeval tv;
		tv.tv_sec = m_Timeout;
		tv.tv_usec = 0;
		setsockopt (m_Socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof tv );
	}
}

string CIPConnection::GetPeerName()
{
	sockaddr_in addr;
	socklen_t size= sizeof(addr);
	if (getpeername(getSocket(), (sockaddr*)&addr, &size) == 0)
	{
		char Buffer[500];
		snprintf(Buffer, sizeof(Buffer), "%s:%d", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
		return Buffer;
	}
	else if (m_ConnectString.length())
		return m_ConnectString;
	else
		return "<FAIL>";

}


text:
namespace google {
namespace cloud {
namespace pubsub {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace {

TEST(Schema, Basics) {
  Schema in("p1", "s1");
  EXPECT_EQ("p1", in.project_id());
  EXPECT_EQ("s1", in.schema_id());
  EXPECT_EQ("projects/p1/schemas/s1", in.FullName());

  auto copy = in;
  EXPECT_EQ(copy, in);
  EXPECT_EQ("p1", copy.project_id());
  EXPECT_EQ("s1", copy.schema_id());
  EXPECT_EQ("projects/p1/schemas/s1", copy.FullName());

  auto moved = std::move(copy);
  EXPECT_EQ(moved, in);
  EXPECT_EQ("p1", moved.project_id());
  EXPECT_EQ("s1", moved.schema_id());
  EXPECT_EQ("projects/p1/schemas/s1", moved.FullName());

  Schema in2("p2", "s2");
  EXPECT_NE(in2, in);
  EXPECT_EQ("p2", in2.project_id());
  EXPECT_EQ("s2", in2.schema_id());
  EXPECT_EQ("projects/p2/schemas/s2", in2.FullName());
}

TEST(Schema, OutputStream) {
  Schema in("p1", "s1");
  std::ostringstream os;
  os << in;
  EXPECT_EQ("projects/p1/schemas/s1", os.str());
}

}  // namespace
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace pubsub
}  // namespace cloud
}  // namespace google


text:
@interface UITableViewCell (AdditionalViews)

@property (strong, nonatomic) UIView        *leftView;
@property (assign, nonatomic) CGRect        leftViewFrame;
@property (strong, nonatomic) UIView        *rightView;
@property (assign, nonatomic) CGRect        rightViewFrame;

@end


text:
#include "sys_sys_types.h"
#include "LOG_bridge.h"
#include "POP_bridge.h"
#include "T_bridge.h"
#include "ooaofooa_classes.h"

/*
 * Instance Loader (from string data).
 */
Escher_iHandle_t
ooaofooa_CL_POR_instanceloader( Escher_iHandle_t instance, const c_t * avlstring[] )
{
  Escher_iHandle_t return_identifier = 0;
  ooaofooa_CL_POR * self = (ooaofooa_CL_POR *) instance;
  /* Initialize application analysis class attributes.  */
  self->CL_IC_Id = (Escher_iHandle_t) Escher_atoi( avlstring[ 1 ] );
  self->C_PO_Id = (Escher_iHandle_t) Escher_atoi( avlstring[ 2 ] );
  self->Name = Escher_strcpy( self->Name, avlstring[ 3 ] );
  self->Id = (Escher_iHandle_t) Escher_atoi( avlstring[ 4 ] );
  return_identifier = self->Id;
  return return_identifier;
}

/*
 * Select any where using referential/identifying attribute set.
 * If not_empty, relate this instance to the selected instance.
 */
void ooaofooa_CL_POR_batch_relate( Escher_iHandle_t instance )
{
  ooaofooa_CL_POR * ooaofooa_CL_POR_instance = (ooaofooa_CL_POR *) instance;
  ooaofooa_C_PO * ooaofooa_C_POrelated_instance1 = (ooaofooa_C_PO *) Escher_instance_cache[ (intptr_t) ooaofooa_CL_POR_instance->C_PO_Id ];
  if ( ooaofooa_C_POrelated_instance1 ) {
    ooaofooa_CL_POR_R4709_Link_is_referenced_by( ooaofooa_C_POrelated_instance1, ooaofooa_CL_POR_instance );
  }
  {
  ooaofooa_CL_IC * ooaofooa_CL_ICrelated_instance1 = ooaofooa_CL_IC_AnyWhere1( ooaofooa_CL_POR_instance->CL_IC_Id );
  if ( ooaofooa_CL_ICrelated_instance1 ) {
    ooaofooa_CL_POR_R4707_Link_communicates_through( ooaofooa_CL_ICrelated_instance1, ooaofooa_CL_POR_instance );
  }
  }
}

/*
 * Scan the extent for a matching instance.
 */
ooaofooa_CL_POR *
ooaofooa_CL_POR_AnyWhere1( Escher_UniqueID_t w_Id )
{
  ooaofooa_CL_POR * w;
  Escher_Iterator_s iter_CL_POR;
  Escher_IteratorReset( &iter_CL_POR, &pG_ooaofooa_CL_POR_extent.active );
  while ( (w = (ooaofooa_CL_POR *) Escher_IteratorNext( &iter_CL_POR )) != 0 ) {
    if ( w->Id == w_Id ) {
      return w;
    }
  }
  return 0;
}

/*
 * RELATE CL_IC TO CL_POR ACROSS R4707
 */
void
ooaofooa_CL_POR_R4707_Link_communicates_through( ooaofooa_CL_IC * part, ooaofooa_CL_POR * form )
{
  /* Use TagEmptyHandleDetectionOn() to detect empty handle references.  */
  form->CL_IC_Id = part->Id;
  form->CL_IC_R4707_orginates_from = part;
  Escher_SetInsertElement( &part->CL_POR_R4707_communicates_through, (Escher_ObjectSet_s *) form );
}

/*
 * UNRELATE CL_IC FROM CL_POR ACROSS R4707
 */
void
ooaofooa_CL_POR_R4707_Unlink_communicates_through( ooaofooa_CL_IC * part, ooaofooa_CL_POR * form )
{
  /* Use TagEmptyHandleDetectionOn() to detect empty handle references.  */
  form->CL_IC_Id = 0;
  form->CL_IC_R4707_orginates_from = 0;
  Escher_SetRemoveElement( &part->CL_POR_R4707_communicates_through, (Escher_ObjectSet_s *) form );
}

/*
 * RELATE C_PO TO CL_POR ACROSS R4709
 */
void
ooaofooa_CL_POR_R4709_Link_is_referenced_by( ooaofooa_C_PO * part, ooaofooa_CL_POR * form )
{
  /* Use TagEmptyHandleDetectionOn() to detect empty handle references.  */
  form->C_PO_Id = part->Id;
  form->C_PO_R4709_references = part;
  Escher_SetInsertElement( &part->CL_POR_R4709_is_referenced_by, (Escher_ObjectSet_s *) form );
}

/*
 * UNRELATE C_PO FROM CL_POR ACROSS R4709
 */
void
ooaofooa_CL_POR_R4709_Unlink_is_referenced_by( ooaofooa_C_PO * part, ooaofooa_CL_POR * form )
{
  /* Use TagEmptyHandleDetectionOn() to detect empty handle references.  */
  form->C_PO_Id = 0;
  form->C_PO_R4709_references = 0;
  Escher_SetRemoveElement( &part->CL_POR_R4709_is_referenced_by, (Escher_ObjectSet_s *) form );
}

/*
 * Dump instances in SQL format.
 */
void
ooaofooa_CL_POR_instancedumper( Escher_iHandle_t instance )
{
  ooaofooa_CL_POR * self = (ooaofooa_CL_POR *) instance;
  printf( "INSERT INTO CL_POR VALUES ( %ld,%ld,'%s',%ld );\n",
    ((long)self->CL_IC_Id & ESCHER_IDDUMP_MASK),
    ((long)self->C_PO_Id & ESCHER_IDDUMP_MASK),
    ( 0 != self->Name ) ? self->Name : "",
    ((long)self->Id & ESCHER_IDDUMP_MASK) );
}
/*
 * Statically allocate space for the instance population for this class.
 * Allocate space for the class instance and its attribute values.
 * Depending upon the collection scheme, allocate containoids (collection
 * nodes) for gathering instances into free and active extents.
 */
static Escher_SetElement_s ooaofooa_CL_POR_container[ ooaofooa_CL_POR_MAX_EXTENT_SIZE ];
static ooaofooa_CL_POR ooaofooa_CL_POR_instances[ ooaofooa_CL_POR_MAX_EXTENT_SIZE ];
Escher_Extent_t pG_ooaofooa_CL_POR_extent = {
  {0,0}, {0,0}, &ooaofooa_CL_POR_container[ 0 ],
  (Escher_iHandle_t) &ooaofooa_CL_POR_instances,
  sizeof( ooaofooa_CL_POR ), 0, ooaofooa_CL_POR_MAX_EXTENT_SIZE
  };


text:
<?php
/**
 * Created by PhpStorm.
 * User: ikneb
 * Date: 22.10.2016
 * Time: 15:10
 */

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

class ContactRepository extends EntityRepository
{

}


text:
import fetch from 'isomorphic-fetch';

export const REQUEST_METHODS = {
    GET: 'GET',
    POST: 'POST',
    PUT: 'PUT',
    DELETE: 'DELETE',
};

const CREDENTIALS = {
    OMIT: 'omit',
    SAME_ORIGIN: 'same-origin',
    INCLUDE: 'include',
};

const credentialsEnumToString = (credentialsEnum) => {
    switch (credentialsEnum) {
        case CREDENTIALS.INCLUDE:
            return 'include';
        case CREDENTIALS.OMIT:
            return 'omit';
        case CREDENTIALS.SAME_ORIGIN:
            return 'same-origin';
        default:
            return 'same-origin';
    }
};

const getApiParams = (requestMethod, payload, reqHeaders, config) => {
    const params = {
        method: requestMethod,
        headers: {},
        /**
         * credentials (String) - Authentication credentials mode. Default: "omit"
         * "omit" - don't include authentication credentials (e.g. cookies) in the request
         * "same-origin" - include credentials in requests to the same site
         * "include" - include credentials in requests to all sites
         */
        credentials: credentialsEnumToString(config.credentials),
    };

    if (requestMethod !== REQUEST_METHODS.GET && payload) {
        params.body = JSON.stringify(payload);
    }

    if (reqHeaders && reqHeaders.cookie) {
        params.headers.cookie = reqHeaders.cookie;
    }

    return params;
};

/**
 *This class is responsible for invoking API endpoints using fetch of isomorphic-fetch library.
 */

export default class RequestAPI {

    static CREDENTIALS = CREDENTIALS;

  /**
   * This function makes the call to back end API using below parameters and returns the promise back to the invoking client.
   *
   * @url - API end point URL.
   * @requestMethod - Request Method to call API  Ex: GET, POST, PUT, PATCH, DELETE.
   * @payload - Request payload to be send to API, this is an optional parameter and can be used for any POST,PUT and PATCH calls if required.
   */

    static invoke(url, requestMethod, payload, reqHeaders, config, middleware) {
        if (process.env.NODE_ENV === 'development') {
            url = url.indexOf('?') !== -1 ? `${url}&dpAkamaiOverride=1` : `${url}?dpAkamaiOverride=1`;
        }
        return fetch(url,
            getApiParams(requestMethod, payload, reqHeaders, config),
        ).then((response) => {
            const status = response.status;
            const statusText = response.statusText;
            if (__SERVER__) {
                try {
                    // TODO:PR: Clone header
                    middleware(url, response.headers);
                } catch (e) {
                    console.error('Middleware execution errored :: ', e);
                }
            }

            if (status === 201) {
                return response.text()
                  .then(text => ({ status, statusText, data: text }));
            }

            return response.json()
                .then(json => ({ status, statusText, data: json }));
        }).catch((error) => {
            console.log('Error in fetching data from Url: ', url, error);
            return error;
        });
    }
}


text:
package dns

import (
	"encoding/json"
	"github.com/oracle/oci-go-sdk/common"
)

// CreateZoneDetails The body for defining a new zone.
// **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.
type CreateZoneDetails struct {

	// The name of the zone.
	Name *string `mandatory:"true" json:"name"`

	// The OCID of the compartment containing the zone.
	CompartmentId *string `mandatory:"true" json:"compartmentId"`

	// Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace.
	// For more information, see Resource Tags (https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm).
	//
	// **Example:** `{"Department": "Finance"}`
	FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`

	// Defined tags for this resource. Each key is predefined and scoped to a namespace.
	// For more information, see Resource Tags (https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm).
	//
	// **Example:** `{"Operations": {"CostCenter": "42"}}`
	DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`

	// External master servers for the zone. `externalMasters` becomes a
	// required parameter when the `zoneType` value is `SECONDARY`.
	ExternalMasters []ExternalMaster `mandatory:"false" json:"externalMasters"`

	// The type of the zone. Must be either `PRIMARY` or `SECONDARY`.
	ZoneType CreateZoneDetailsZoneTypeEnum `mandatory:"false" json:"zoneType,omitempty"`
}

//GetName returns Name
func (m CreateZoneDetails) GetName() *string {
	return m.Name
}

//GetCompartmentId returns CompartmentId
func (m CreateZoneDetails) GetCompartmentId() *string {
	return m.CompartmentId
}

//GetFreeformTags returns FreeformTags
func (m CreateZoneDetails) GetFreeformTags() map[string]string {
	return m.FreeformTags
}

//GetDefinedTags returns DefinedTags
func (m CreateZoneDetails) GetDefinedTags() map[string]map[string]interface{} {
	return m.DefinedTags
}

func (m CreateZoneDetails) String() string {
	return common.PointerString(m)
}

// MarshalJSON marshals to json representation
func (m CreateZoneDetails) MarshalJSON() (buff []byte, e error) {
	type MarshalTypeCreateZoneDetails CreateZoneDetails
	s := struct {
		DiscriminatorParam string `json:"migrationSource"`
		MarshalTypeCreateZoneDetails
	}{
		"NONE",
		(MarshalTypeCreateZoneDetails)(m),
	}

	return json.Marshal(&s)
}

// CreateZoneDetailsZoneTypeEnum Enum with underlying type: string
type CreateZoneDetailsZoneTypeEnum string

// Set of constants representing the allowable values for CreateZoneDetailsZoneTypeEnum
const (
	CreateZoneDetailsZoneTypePrimary   CreateZoneDetailsZoneTypeEnum = "PRIMARY"
	CreateZoneDetailsZoneTypeSecondary CreateZoneDetailsZoneTypeEnum = "SECONDARY"
)

var mappingCreateZoneDetailsZoneType = map[string]CreateZoneDetailsZoneTypeEnum{
	"PRIMARY":   CreateZoneDetailsZoneTypePrimary,
	"SECONDARY": CreateZoneDetailsZoneTypeSecondary,
}

// GetCreateZoneDetailsZoneTypeEnumValues Enumerates the set of values for CreateZoneDetailsZoneTypeEnum
func GetCreateZoneDetailsZoneTypeEnumValues() []CreateZoneDetailsZoneTypeEnum {
	values := make([]CreateZoneDetailsZoneTypeEnum, 0)
	for _, v := range mappingCreateZoneDetailsZoneType {
		values = append(values, v)
	}
	return values
}


text:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >

    <FrameLayout
        android:id="@+id/appkefu_pulltorefreshheader_framelayout_inner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/appkefu_header_footer_top_bottom_padding"
        android:paddingLeft="@dimen/appkefu_header_footer_left_right_padding"
        android:paddingRight="@dimen/appkefu_header_footer_left_right_padding"
        android:paddingTop="@dimen/appkefu_header_footer_top_bottom_padding" >

        <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="left|center_vertical" >

            <ImageView
                android:id="@+id/appkefu_pulltorefresh_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center" />

            <ProgressBar
                android:id="@+id/appkefu_pulltorefresh_progress"
                style="?android:attr/progressBarStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:indeterminate="true"
                android:visibility="gone" />
        </FrameLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center_horizontal"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/appkefu_pulltorefresh_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:textAppearance="?android:attr/textAppearance"
                android:textColor="#000"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/appkefu_pulltorefresh_subtext"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="#000"
                android:visibility="gone" />
        </LinearLayout>
    </FrameLayout>

</merge>


text:
define(function (require, exports, module) {
    "use strict";

    var dom = require("../lib/dom");
    var event = require("../lib/event");
    var useragent = require("../lib/useragent");

    var AUTOSCROLL_DELAY = 200;
    var SCROLL_CURSOR_DELAY = 200;
    var SCROLL_CURSOR_HYSTERESIS = 5;

    function DragdropHandler(mouseHandler) {

        var editor = mouseHandler.editor;

        var blankImage = dom.createElement("img");
        // Safari crashes without image data
        blankImage.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
        if (useragent.isOpera)
            blankImage.style.cssText = "width:1px;height:1px;position:fixed;top:0;left:0;z-index:2147483647;opacity:0;";

        var exports = ["dragWait", "dragWaitEnd", "startDrag", "dragReadyEnd", "onMouseDrag"];

        exports.forEach(function (x) {
            mouseHandler[x] = this[x];
        }, this);
        editor.addEventListener("mousedown", this.onMouseDown.bind(mouseHandler));

        var mouseTarget = editor.container;
        var dragSelectionMarker, x, y;
        var timerId, range;
        var dragCursor, counter = 0;
        var dragOperation;
        var isInternal;
        var autoScrollStartTime;
        var cursorMovedTime;
        var cursorPointOnCaretMoved;

        this.onDragStart = function (e) {
            // webkit workaround, see this.onMouseDown
            if (this.cancelDrag || !mouseTarget.draggable) {
                var self = this;
                setTimeout(function () {
                    self.startSelect();
                    self.captureMouse(e);
                }, 0);
                return e.preventDefault();
            }
            range = editor.getSelectionRange();

            var dataTransfer = e.dataTransfer;
            dataTransfer.effectAllowed = editor.getReadOnly() ? "copy" : "copyMove";
            if (useragent.isOpera) {
                editor.container.appendChild(blankImage);
                // force layout
                blankImage.scrollTop = 0;
            }
            dataTransfer.setDragImage && dataTransfer.setDragImage(blankImage, 0, 0);
            if (useragent.isOpera) {
                editor.container.removeChild(blankImage);
            }
            // clear Opera garbage
            dataTransfer.clearData();
            dataTransfer.setData("Text", editor.session.getTextRange());

            isInternal = true;
            this.setState("drag");
        };

        this.onDragEnd = function (e) {
            mouseTarget.draggable = false;
            isInternal = false;
            this.setState(null);
            if (!editor.getReadOnly()) {
                var dropEffect = e.dataTransfer.dropEffect;
                if (!dragOperation && dropEffect == "move")
                // text was dragged outside the editor
                    editor.session.remove(editor.getSelectionRange());
                editor.renderer.$cursorLayer.setBlinking(true);
            }
            this.editor.unsetStyle("ace_dragging");
            this.editor.renderer.setCursorStyle("");
        };

        this.onDragEnter = function (e) {
            if (editor.getReadOnly() || !canAccept(e.dataTransfer))
                return;
            x = e.clientX;
            y = e.clientY;
            if (!dragSelectionMarker)
                addDragMarker();
            counter++;
            // dataTransfer object does not save dropEffect across events on IE, so we store it in dragOperation
            e.dataTransfer.dropEffect = dragOperation = getDropEffect(e);
            return event.preventDefault(e);
        };

        this.onDragOver = function (e) {
            if (editor.getReadOnly() || !canAccept(e.dataTransfer))
                return;
            x = e.clientX;
            y = e.clientY;
            // Opera doesn't trigger dragenter event on drag start
            if (!dragSelectionMarker) {
                addDragMarker();
                counter++;
            }
            if (onMouseMoveTimer !== null)
                onMouseMoveTimer = null;

            e.dataTransfer.dropEffect = dragOperation = getDropEffect(e);
            return event.preventDefault(e);
        };

        this.onDragLeave = function (e) {
            counter--;
            if (counter <= 0 && dragSelectionMarker) {
                clearDragMarker();
                dragOperation = null;
                return event.preventDefault(e);
            }
        };

        this.onDrop = function (e) {
            if (!dragCursor)
                return;
            var dataTransfer = e.dataTransfer;
            if (isInternal) {
                switch (dragOperation) {
                    case "move":
                        if (range.contains(dragCursor.row, dragCursor.column)) {
                            // clear selection
                            range = {
                                start: dragCursor,
                                end: dragCursor
                            };
                        } else {
                            // move text
                            range = editor.moveText(range, dragCursor);
                        }
                        break;
                    case "copy":
                        // copy text
                        range = editor.moveText(range, dragCursor, true);
                        break;
                }
            } else {
                var dropData = dataTransfer.getData('Text');
                range = {
                    start: dragCursor,
                    end: editor.session.insert(dragCursor, dropData)
                };
                editor.focus();
                dragOperation = null;
            }
            clearDragMarker();
            return event.preventDefault(e);
        };

        event.addListener(mouseTarget, "dragstart", this.onDragStart.bind(mouseHandler));
        event.addListener(mouseTarget, "dragend", this.onDragEnd.bind(mouseHandler));
        event.addListener(mouseTarget, "dragenter", this.onDragEnter.bind(mouseHandler));
        event.addListener(mouseTarget, "dragover", this.onDragOver.bind(mouseHandler));
        event.addListener(mouseTarget, "dragleave", this.onDragLeave.bind(mouseHandler));
        event.addListener(mouseTarget, "drop", this.onDrop.bind(mouseHandler));

        function scrollCursorIntoView(cursor, prevCursor) {
            var now = Date.now();
            var vMovement = !prevCursor || cursor.row != prevCursor.row;
            var hMovement = !prevCursor || cursor.column != prevCursor.column;
            if (!cursorMovedTime || vMovement || hMovement) {
                editor.$blockScrolling += 1;
                editor.moveCursorToPosition(cursor);
                editor.$blockScrolling -= 1;
                cursorMovedTime = now;
                cursorPointOnCaretMoved = {x: x, y: y};
            } else {
                var distance = calcDistance(cursorPointOnCaretMoved.x, cursorPointOnCaretMoved.y, x, y);
                if (distance > SCROLL_CURSOR_HYSTERESIS) {
                    cursorMovedTime = null;
                } else if (now - cursorMovedTime >= SCROLL_CURSOR_DELAY) {
                    editor.renderer.scrollCursorIntoView();
                    cursorMovedTime = null;
                }
            }
        }

        function autoScroll(cursor, prevCursor) {
            var now = Date.now();
            var lineHeight = editor.renderer.layerConfig.lineHeight;
            var characterWidth = editor.renderer.layerConfig.characterWidth;
            var editorRect = editor.renderer.scroller.getBoundingClientRect();
            var offsets = {
                x: {
                    left: x - editorRect.left,
                    right: editorRect.right - x
                },
                y: {
                    top: y - editorRect.top,
                    bottom: editorRect.bottom - y
                }
            };
            var nearestXOffset = Math.min(offsets.x.left, offsets.x.right);
            var nearestYOffset = Math.min(offsets.y.top, offsets.y.bottom);
            var scrollCursor = {row: cursor.row, column: cursor.column};
            if (nearestXOffset / characterWidth <= 2) {
                scrollCursor.column += (offsets.x.left < offsets.x.right ? -3 : +2);
            }
            if (nearestYOffset / lineHeight <= 1) {
                scrollCursor.row += (offsets.y.top < offsets.y.bottom ? -1 : +1);
            }
            var vScroll = cursor.row != scrollCursor.row;
            var hScroll = cursor.column != scrollCursor.column;
            var vMovement = !prevCursor || cursor.row != prevCursor.row;
            if (vScroll || (hScroll && !vMovement)) {
                if (!autoScrollStartTime)
                    autoScrollStartTime = now;
                else if (now - autoScrollStartTime >= AUTOSCROLL_DELAY)
                    editor.renderer.scrollCursorIntoView(scrollCursor);
            } else {
                autoScrollStartTime = null;
            }
        }

        function onDragInterval() {
            var prevCursor = dragCursor;
            dragCursor = editor.renderer.screenToTextCoordinates(x, y);
            scrollCursorIntoView(dragCursor, prevCursor);
            autoScroll(dragCursor, prevCursor);
        }

        function addDragMarker() {
            range = editor.selection.toOrientedRange();
            dragSelectionMarker = editor.session.addMarker(range, "ace_selection", editor.getSelectionStyle());
            editor.clearSelection();
            if (editor.isFocused())
                editor.renderer.$cursorLayer.setBlinking(false);
            clearInterval(timerId);
            onDragInterval();
            timerId = setInterval(onDragInterval, 20);
            counter = 0;
            event.addListener(document, "mousemove", onMouseMove);
        }

        function clearDragMarker() {
            clearInterval(timerId);
            editor.session.removeMarker(dragSelectionMarker);
            dragSelectionMarker = null;
            editor.$blockScrolling += 1;
            editor.selection.fromOrientedRange(range);
            editor.$blockScrolling -= 1;
            if (editor.isFocused() && !isInternal)
                editor.renderer.$cursorLayer.setBlinking(!editor.getReadOnly());
            range = null;
            dragCursor = null;
            counter = 0;
            autoScrollStartTime = null;
            cursorMovedTime = null;
            event.removeListener(document, "mousemove", onMouseMove);
        }

        // sometimes other code on the page can stop dragleave event leaving editor stuck in the drag state
        var onMouseMoveTimer = null;

        function onMouseMove() {
            if (onMouseMoveTimer == null) {
                onMouseMoveTimer = setTimeout(function () {
                    if (onMouseMoveTimer != null && dragSelectionMarker)
                        clearDragMarker();
                }, 20);
            }
        }

        function canAccept(dataTransfer) {
            var types = dataTransfer.types;
            return !types || Array.prototype.some.call(types, function (type) {
                    return type == 'text/plain' || type == 'Text';
                });
        }

        function getDropEffect(e) {
            var copyAllowed = ['copy', 'copymove', 'all', 'uninitialized'];
            var moveAllowed = ['move', 'copymove', 'linkmove', 'all', 'uninitialized'];

            var copyModifierState = useragent.isMac ? e.altKey : e.ctrlKey;

            // IE throws error while dragging from another app
            var effectAllowed = "uninitialized";
            try {
                effectAllowed = e.dataTransfer.effectAllowed.toLowerCase();
            } catch (e) {
            }
            var dropEffect = "none";

            if (copyModifierState && copyAllowed.indexOf(effectAllowed) >= 0)
                dropEffect = "copy";
            else if (moveAllowed.indexOf(effectAllowed) >= 0)
                dropEffect = "move";
            else if (copyAllowed.indexOf(effectAllowed) >= 0)
                dropEffect = "copy";

            return dropEffect;
        }
    }

    (function () {

        this.dragWait = function () {
            var interval = Date.now() - this.mousedownEvent.time;
            if (interval > this.editor.getDragDelay())
                this.startDrag();
        };

        this.dragWaitEnd = function () {
            var target = this.editor.container;
            target.draggable = false;
            this.startSelect(this.mousedownEvent.getDocumentPosition());
            this.selectEnd();
        };

        this.dragReadyEnd = function (e) {
            this.editor.renderer.$cursorLayer.setBlinking(!this.editor.getReadOnly());
            this.editor.unsetStyle("ace_dragging");
            this.editor.renderer.setCursorStyle("");
            this.dragWaitEnd();
        };

        this.startDrag = function () {
            this.cancelDrag = false;
            var editor = this.editor;
            var target = editor.container;
            target.draggable = true;
            editor.renderer.$cursorLayer.setBlinking(false);
            editor.setStyle("ace_dragging");
            var cursorStyle = useragent.isWin ? "default" : "move";
            editor.renderer.setCursorStyle(cursorStyle);
            this.setState("dragReady");
        };

        this.onMouseDrag = function (e) {
            var target = this.editor.container;
            if (useragent.isIE && this.state == "dragReady") {
                // IE does not handle [draggable] attribute set after mousedown
                var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y);
                if (distance > 3)
                    target.dragDrop();
            }
            if (this.state === "dragWait") {
                var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y);
                if (distance > 0) {
                    target.draggable = false;
                    this.startSelect(this.mousedownEvent.getDocumentPosition());
                }
            }
        };

        this.onMouseDown = function (e) {
            if (!this.$dragEnabled)
                return;
            this.mousedownEvent = e;
            var editor = this.editor;

            var inSelection = e.inSelection();
            var button = e.getButton();
            var clickCount = e.domEvent.detail || 1;
            if (clickCount === 1 && button === 0 && inSelection) {
                if (e.editor.inMultiSelectMode && (e.getAccelKey() || e.getShiftKey()))
                    return;
                this.mousedownEvent.time = Date.now();
                var eventTarget = e.domEvent.target || e.domEvent.srcElement;
                if ("unselectable" in eventTarget)
                    eventTarget.unselectable = "on";
                if (editor.getDragDelay()) {
                    // https://code.google.com/p/chromium/issues/detail?id=286700
                    if (useragent.isWebKit) {
                        this.cancelDrag = true;
                        var mouseTarget = editor.container;
                        mouseTarget.draggable = true;
                    }
                    this.setState("dragWait");
                } else {
                    this.startDrag();
                }
                this.captureMouse(e, this.onMouseDrag.bind(this));
                // TODO: a better way to prevent default handler without preventing browser default action
                e.defaultPrevented = true;
            }
        };

    }).call(DragdropHandler.prototype);

    function calcDistance(ax, ay, bx, by) {
        return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2));
    }

    exports.DragdropHandler = DragdropHandler;

});


text:
import collections
import math
from functools import reduce
from itertools import chain, count, islice, takewhile
from multiprocessing import Pool, cpu_count

import dill as serializer

PROTOCOL = serializer.HIGHEST_PROTOCOL
CPU_COUNT = cpu_count()

def is_primitive(val):
    """
    Checks if the passed value is a primitive type.

    >>> is_primitive(1)
    True

    >>> is_primitive("abc")
    True

    >>> is_primitive(True)
    True

    >>> is_primitive({})
    False

    >>> is_primitive([])
    False

    >>> is_primitive(set([]))

    :param val: value to check
    :return: True if value is a primitive, else False
    """
    return isinstance(val, (str, bool, float, complex, bytes, int))

def is_namedtuple(val):
    """
    Use Duck Typing to check if val is a named tuple. Checks that val is of type tuple and contains
    the attribute _fields which is defined for named tuples.
    :param val: value to check type of
    :return: True if val is a namedtuple
    """
    val_type = type(val)
    bases = val_type.__bases__
    if len(bases) != 1 or bases[0] != tuple:
        return False
    fields = getattr(val_type, "_fields", None)
    return all(isinstance(n, str) for n in fields)

def identity(arg):
    """
    Function which returns the argument. Used as a default lambda function.

    >>> obj = object()
    >>> obj is identity(obj)
    True

    :param arg: object to take identity of
    :return: return arg
    """
    return arg

def is_iterable(val):
    """
    Check if val is not a list, but is a collections.Iterable type. This is used to determine
    when list() should be called on val

    >>> l = [1, 2]
    >>> is_iterable(l)
    False
    >>> is_iterable(iter(l))
    True

    :param val: value to check
    :return: True if it is not a list, but is a collections.Iterable
    """
    if isinstance(val, list):
        return False
    return isinstance(val, collections.abc.Iterable)

def is_tabulatable(val):
    if is_primitive(val):
        return False
    if is_iterable(val) or is_namedtuple(val) or isinstance(val, list):
        return True
    return False

def split_every(parts, iterable):
    """
    Split an iterable into parts of length parts

    >>> l = iter([1, 2, 3, 4])
    >>> split_every(2, l)
    [[1, 2], [3, 4]]

    :param iterable: iterable to split
    :param parts: number of chunks
    :return: return the iterable split in parts
    """
    return takewhile(bool, (list(islice(iterable, parts)) for _ in count()))

def unpack(packed):
    """
    Unpack the function and args then apply the function to the arguments and return result
    :param packed: input packed tuple of (func, args)
    :return: result of applying packed function on packed args
    """
    func, args = serializer.loads(packed)
    result = func(*args)
    if isinstance(result, collections.abc.Iterable):
        return list(result)
    return None

def pack(func, args):
    """
    Pack a function and the args it should be applied to
    :param func: Function to apply
    :param args: Args to evaluate with
    :return: Packed (func, args) tuple
    """
    return serializer.dumps((func, args), PROTOCOL)

def parallelize(func, result, processes=None, partition_size=None):
    """
    Creates an iterable which is lazily computed in parallel from applying func on result
    :param func: Function to apply
    :param result: Data to apply to
    :param processes: Number of processes to use in parallel
    :param partition_size: Size of partitions for each parallel process
    :return: Iterable of applying func on result
    """
    parallel_iter = lazy_parallelize(
        func, result, processes=processes, partition_size=partition_size
    )
    return chain.from_iterable(parallel_iter)

def lazy_parallelize(func, result, processes=None, partition_size=None):
    """
    Lazily computes an iterable in parallel, and returns them in pool chunks
    :param func: Function to apply
    :param result: Data to apply to
    :param processes: Number of processes to use in parallel
    :param partition_size: Size of partitions for each parallel process
    :return: Iterable of chunks where each chunk as func applied to it
    """
    if processes is None or processes < 1:
        processes = CPU_COUNT
    else:
        processes = min(processes, CPU_COUNT)
    partition_size = partition_size or compute_partition_size(result, processes)
    pool = Pool(processes=processes)
    partitions = split_every(partition_size, iter(result))
    packed_partitions = (pack(func, (partition,)) for partition in partitions)
    for pool_result in pool.imap(unpack, packed_partitions):
        yield pool_result
    pool.terminate()

def compute_partition_size(result, processes):
    """
    Attempts to compute the partition size to evenly distribute work across processes. Defaults to
    1 if the length of result cannot be determined.

    :param result: Result to compute on
    :param processes: Number of processes to use
    :return: Best partition size
    """
    try:
        return max(math.ceil(len(result) / processes), 1)
    except TypeError:
        return 1

def compose(*functions):
    """
    Compose all the function arguments together
    :param functions: Functions to compose
    :return: Single composed function
    """
    # pylint: disable=undefined-variable
    return reduce(lambda f, g: lambda x: f(g(x)), functions, lambda x: x)


text:
package com.hearthsim.util;

/**
 * Created by oyachai on 6/22/15.
 */
public class UniqueCardIdCreator {
}


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

-->
<DatePickerDialog xmlns:dialog="http://schemas.android.com/apk/res-auto"
                  dialog:dialogNegativeButton="@string/dialog_button_cancel"
                  dialog:dialogPositiveButton="@string/dialog_button_ok"
                  dialog:dialogMinDate="current-(0050-00-00)"
                  dialog:dialogMaxDate="current"/>