text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <title>Macros - Elixir</title>
  <link href="http://feeds.feedburner.com/ElixirLang" rel="alternate" title="Elixir's Blog" type="application/atom+xml" />
  <link rel="stylesheet" type="text/css" href="/css/style.css" />
  <link rel="stylesheet" type="text/css" href="/css/syntax.css" />
  <link rel="stylesheet" href="/js/icons/style.css">

  <link rel="stylesheet" href="/js/icons/ie7/ie7.css">

  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <link rel="stylesheet" id="font-bitter-css" href="http://fonts.googleapis.com/css?family=Bitter&ver=1" type="text/css" media="screen" />
  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />

Home

Install

Getting Started

Learning

Docs

Blog

Packages

    News: Elixir v1.0 released

  <form method="get" class="search-form" action="http://www.google.com/search">

			<input class="search-text" type="text" name="q" placeholder="Search..." id="searchfield">
			<input type="hidden" name="sitesearch" value="elixir-lang.org">
			<input class="search-submit button" name="submit" type="submit" value="Search">

	</form>

Getting Started

Introduction

Basic types

Basic operators

Pattern matching

case, cond and if

Binaries, strings and char lists

Keywords, maps and dicts

Modules

Recursion

Enumerables and streams

Processes

IO and the file system

alias, require and import

Module attributes

Structs

Protocols

Comprehensions

Sigils

try, catch and rescue

Typespecs and behaviours

Where to go next

Mix and OTP

Introduction to Mix

Agent

GenServer

GenEvent

Supervisor and Application

ETS

Dependencies and umbrella apps

Task and gen-tcp

Docs, tests and pipelines

Distributed tasks and configuration

Meta-programming in Elixir

Quote and unquote

Macros

Domain Specific Languages

Sponsors

Macros

Foreword

Even though Elixir attempts its best to provide a safe environment for macros, the major responsibility of writing clean code with macros falls on developers. Macros are harder to write than ordinary Elixir functions and it's considered to be bad style to use them when they're not necessary. So write macros responsibly.

Elixir already provides mechanisms to write your every day code in a simple and readable fashion. Macros should only be used as a last resort. Remember that explicit is better than implicit. Clear code is better than concise code.

Our first macro

Macros in Elixir are defined via defmacro/2.

For this chapter, we will be using files instead of running code samples in IEx. That's because the code samples will span multiple lines of code and typing them all in IEx can be counter-productive. You should be able to run the code samples by saving them into a macros.exs file and running it with elixir macros.exs or iex macros.exs.

In order to better understand how macros work, let's create a new module where we are going to implement unless, which does the opposite of if, as a macro and as a function:

defmodule Unless do
  def fun_unless(clause, expression) do
    if(!clause, do: expression)
  end

  defmacro macro_unless(clause, expression) do
    quote do
      if(!unquote(clause), do: unquote(expression))
    end
  end
end

The function receives the arguments and passes them to if. However, as we learned in the previous chapter, the macro will receive quoted expressions, inject them into the quote, and finally return another quoted expression.

Let's start iex with the module above:

$ iex macros.exs

And play with those definitions:

iex> require Unless
iex> Unless.macro_unless true, IO.puts "this should never be printed"
nil
iex> Unless.fun_unless true, IO.puts "this should never be printed"
"this should never be printed"
nil

Note that in our macro implementation, the sentence was not printed, although it was printed in our function implementation. That's because the arguments to a function call are evaluated before calling the function. However, macros do not evaluate their arguments. Instead, they receive the arguments as quoted expressions which are then transformed into other quoted expressions. In this case, we have rewritten our unless macro to become an if behind the scenes.

In other words, when invoked as:

Unless.macro_unless true, IO.puts "this should never be printed"

Our macro_unless macro received the following:

macro_unless(true, {{:., [], [{:aliases, [], [:IO]}, :puts]}, [], ["this should never be printed"]})

And it then returned a quoted expression as follows:

{:if, [], [
  {:!, [], [true]},
  {{:., [], [IO, :puts], [], ["this should never be printed"]}}]}

We can actually verify that this is the case by using Macro.expand_once/2:

iex> expr = quote do: Unless.macro_unless(true, IO.puts "this should never be printed")
iex> res  = Macro.expand_once(expr, __ENV__)
iex> IO.puts Macro.to_string(res)
if(!true) do
  IO.puts("this should never be printed")
end
:ok

Macro.expand_once/2 receives a quoted expression and expands it according to the current environment. In this case, it expanded/invoked the Unless.macro_unless/2 macro and returned its result. We then proceeded to convert the returned quoted expression to a string and print it (we will talk about __ENV__ later in this chapter).

That's what macros are all about. They are about receiving quoted expressions and transforming them into something else. In fact, unless/2 in Elixir is implemented as a macro:

defmacro unless(clause, options) do
  quote do
    if(!unquote(clause), do: unquote(options))
  end
end

Constructs such as unless/2, defmacro/2, def/2, defprotocol/2, and many others used throughout this getting started guide are implemented in pure Elixir, often as a macros. This means that the constructs being used to build the language can be used by developers to extend the language to the domains they are working on.

We can define any function and macro we want, including ones that override the built-in definitions provided by Elixir. The only exceptions are Elixir special forms which are not implemented in Elixir and therefore cannot be overridden, the full list of special forms is available in Kernel.SpecialForms.

Macros hygiene

Elixir macros have late resolution. This guarantees that a variable defined inside a quote won't conflict with a variable defined in the context where that macro is expanded. For example:

defmodule Hygiene do
  defmacro no_interference do
    quote do: a = 1
  end
end

defmodule HygieneTest do
  def go do
    require Hygiene
    a = 13
    Hygiene.no_interference
    a
  end
end

HygieneTest.go
# => 13

In the example above, even though the macro injects a = 1, it does not affect the variable a defined by the go function. If a macro wants to explicitly affect the context, it can use var!:

defmodule Hygiene do
  defmacro interference do
    quote do: var!(a) = 1
  end
end

defmodule HygieneTest do
  def go do
    require Hygiene
    a = 13
    Hygiene.interference
    a
  end
end

HygieneTest.go
# => 1

Variable hygiene only works because Elixir annotates variables with their context. For example, a variable x defined on line 3 of a module would be represented as:

{:x, [line: 3], nil}

However, a quoted variable is represented as:

defmodule Sample do
  def quoted do
    quote do: x
  end
end

Sample.quoted #=> {:x, [line: 3], Sample}

Notice that the third element in the quoted variable is the atom Sample, instead of nil, which marks the variable as coming from the Sample module. Therefore, Elixir considers these two variables as coming from different contexts and handles them accordingly.

Elixir provides similar mechanisms for imports and aliases too. This guarantees that a macro will behave as specified by its source module rather than conflicting with the target module where the macro is expanded. Hygiene can be bypassed under specific situations by using macros like var!/2 and alias!/2, although one must be careful when using those as they directly change the user environment.

Sometimes variable names might be dynamically created. In such cases, Macro.var/2 can be used to define new variables:

defmodule Sample do
  defmacro initialize_to_char_count(variables) do
    Enum.map variables, fn(name) ->
      var = Macro.var(name, nil)
      length = name |> Atom.to_string |> String.length
      quote do
        unquote(var) = unquote(length)
      end
    end
  end

  def run do
    initialize_to_char_count [:red, :green, :yellow]
    [red, green, yellow]
  end
end

> Sample.run #=> [3, 5, 6]

Take note of the second argument to Macro.var/2. This is the context being used and will determine hygiene as described in the next section.

The environment

When calling Macro.expand_once/2 earlier in this chapter, we used the special form __ENV__.

__ENV__ returns an instance of the Macro.Env struct which contains useful information about the compilation environment, including the current module, file and line, all variables defined in the current scope, as well as imports, requires and so on:

iex> __ENV__.module
nil
iex> __ENV__.file
"iex"
iex> __ENV__.requires
[IEx.Helpers, Kernel, Kernel.Typespec]
iex> require Integer
nil
iex> __ENV__.requires
[IEx.Helpers, Integer, Kernel, Kernel.Typespec]

Many of the functions in the Macro module expect an environment. You can read more about these functions in the docs for the Macro module and learn more about the compilation environment in the docs for Macro.Env.

Private macros

Elixir also supports private macros via defmacrop. As private functions, these macros are only available inside the module that defines them, and only at compilation time.

It is important that a macro is defined before its usage. Failing to define a macro before its invocation will raise an error at runtime, since the macro won't be expanded and will be translated to a function call:

iex> defmodule Sample do
...>  def four, do: two + two
...>  defmacrop two, do: 2
...> end
** (CompileError) iex:2: function two/0 undefined

Write macros responsibly

Macros are a powerful construct and Elixir provides many mechanisms to ensure they are used responsibly.

Macros are hygienic: by default, variables defined inside a macro are not going to affect the user code. Furthermore, function calls and aliases available in the macro context are not going to leak into the user context.

Macros are lexical: it is impossible to inject code or macros globally. In order to use a macro, you need to explicitly require or import the module that defines the macro.

Macros are explicit: it is impossible to run a macro without explicitly invoking it. For example, some languages allow developers to completely rewrite functions behind the scenes, often via parse transforms or via some reflection mechanisms. In Elixir, a macro must be explicitly invoked in the caller during compilation time.

Macros' language is clear: many languages provide syntax shortcuts for quote and unquote. In Elixir, we preferred to have them explicitly spelled out, in order to clearly delimit the boundaries of a macro definition and its quoted expressions.

Even with such guarantees, the developer plays a big role when writing macros responsibly. If you are confident you need to resort to macros, remember that macros are not your API. Keep your macro definitions short, including their quoted contents. For example, instead of writing a macro like this:

defmodule MyModule do
  defmacro my_macro(a, b, c) do
    quote do
      do_this(unquote(a))
      ...
      do_that(unquote(b))
      ...
      and_that(unquote(c))
    end
  end
end

write:

defmodule MyModule do
  defmacro my_macro(a, b, c) do
    quote do
      # Keep what you need to do here to a minimum
      # and move everything else to a function
      do_this_that_and_that(unquote(a), unquote(b), unquote(c))
    end
  end

  def do_this_that_and_that(a, b, c) do
    do_this(a)
    ...
    do_that(b)
    ...
    and_that(c)
  end
end

This makes your code clearer and easier to test and maintain, as you can invoke and test do_this_that_and_that/3 directly. It also helps you design an actual API for developers that do not want to rely on macros.

With those lessons, we finish our introduction to macros. The next chapter is a brief discussion on DSLs that shows how we can mix macros and module attributes to annotate and extend modules and functions.

              ← Previous

              Top

              Next →

        © 2012-2015 Plataformatec. All rights reserved.


text:
package com.android.internal.telephony;

public abstract class SmsAddress
{
  // Fields

  public static final int TON_UNKNOWN = 0;

  public static final int TON_INTERNATIONAL = 1;

  public static final int TON_NATIONAL = 2;

  public static final int TON_NETWORK = 3;

  public static final int TON_SUBSCRIBER = 4;

  public static final int TON_ALPHANUMERIC = 5;

  public static final int TON_ABBREVIATED = 6;

  public int ton;

  public java.lang.String address;

  public byte [] origBytes;

  // Constructors

  public SmsAddress(){
  }
  // Methods

  public java.lang.String getAddressString(){
    return (java.lang.String) null;
  }
  public boolean isAlphanumeric(){
    return false;
  }
  public boolean isNetworkSpecific(){
    return false;
  }
  public boolean couldBeEmailGateway(){
    return false;
  }
}

redpajama_set_name: RedPajamaGithub


text:
import copy

import six
from six.moves.urllib import parse
import jsonschema
from oslo_log import log as logging

from designate import exceptions
from designate.schema import validators
from designate.schema import format
from designate.i18n import _

LOG = logging.getLogger(__name__)

class NotSpecifiedSentinel:
    pass

def get_attrname(name):
    """Return the mangled name of the attribute's underlying storage."""
    return '_obj_field_%s' % name

def make_class_properties(cls):
    """Build getter and setter methods for all the objects attributes"""
    # Prepare an empty dict to gather the merged/final set of fields
    fields = {}

    # Add each supercls's fields
    for supercls in cls.mro()[1:-1]:
        if not hasattr(supercls, 'FIELDS'):
            continue
        fields.update(supercls.FIELDS)

    # Add our fields
    fields.update(cls.FIELDS)

    # Store the results
    cls.FIELDS = fields

    for field in six.iterkeys(cls.FIELDS):
        def getter(self, name=field):
            self._obj_check_relation(name)
            return getattr(self, get_attrname(name), None)

        def setter(self, value, name=field):
            if (self.obj_attr_is_set(name) and value != getattr(self, name)
                    or not self.obj_attr_is_set(name)):
                self._obj_changes.add(name)

            if (self.obj_attr_is_set(name) and value != getattr(self, name)
                    and name not in list(six.iterkeys(
                        self._obj_original_values))):
                self._obj_original_values[name] = getattr(self, name)

            return setattr(self, get_attrname(name), value)

        setattr(cls, field, property(getter, setter))

def _schema_ref_resolver(uri):
    """
    Fetches an DesignateObject's schema from a JSON Schema Reference URI

    Sample URI: obj://ObjectName#/subpathA/subpathB
    """
    obj_name = parse.urlsplit(uri).netloc
    obj = DesignateObject.obj_cls_from_name(obj_name)

    return obj.obj_get_schema()

def make_class_validator(obj):

    schema = {
        '$schema': 'http://json-schema.org/draft-04/hyper-schema',
        'title': obj.obj_name(),
        'description': 'Designate %s Object' % obj.obj_name(),
    }

    if isinstance(obj, ListObjectMixin):

        schema['type'] = 'array',
        schema['items'] = make_class_validator(obj.LIST_ITEM_TYPE)

    else:
        schema['type'] = 'object'
        schema['additionalProperties'] = False
        schema['required'] = []
        schema['properties'] = {}

        for name, properties in obj.FIELDS.items():
            if properties.get('relation', False):
                if obj.obj_attr_is_set(name):
                    schema['properties'][name] = \
                        make_class_validator(getattr(obj, name))
            else:
                schema['properties'][name] = properties.get('schema', {})

            if properties.get('required', False):
                schema['required'].append(name)

    resolver = jsonschema.RefResolver.from_schema(
        schema, handlers={'obj': _schema_ref_resolver})

    obj._obj_validator = validators.Draft4Validator(
        schema, resolver=resolver, format_checker=format.draft4_format_checker)

    return schema

class DesignateObjectMetaclass(type):
    def __init__(cls, names, bases, dict_):
        if not hasattr(cls, '_obj_classes'):
            # This means we're working on the base DesignateObject class,
            # and can skip the remaining Metaclass functionality
            cls._obj_classes = {}
            return

        make_class_properties(cls)

        # Add a reference to the finished class into the _obj_classes
        # dictionary, allowing us to lookup classes by their name later - this
        # is useful for e.g. referencing another DesignateObject in a
        # validation schema.
        if cls.obj_name() not in cls._obj_classes:
            cls._obj_classes[cls.obj_name()] = cls
        else:
            raise Exception("Duplicate DesignateObject with name '%(name)s'" %
                            {'name': cls.obj_name()})

@six.add_metaclass(DesignateObjectMetaclass)
class DesignateObject(object):
    FIELDS = {}

    STRING_KEYS = []

    def _obj_check_relation(self, name):
        if name in self.FIELDS and self.FIELDS[name].get('relation', False):
            if not self.obj_attr_is_set(name):
                raise exceptions.RelationNotLoaded(object=self, relation=name)

    @classmethod
    def obj_cls_from_name(cls, name):
        """Retrieves a object cls from the registry by name and returns it."""
        return cls._obj_classes[name]

    @classmethod
    def from_primitive(cls, primitive):
        """
        Construct an object from primitive types

        This is used while deserializing the object.
        """
        objcls = cls.obj_cls_from_name(primitive['designate_object.name'])
        return objcls._obj_from_primitive(primitive)

    @classmethod
    def _obj_from_primitive(cls, primitive):
        instance = cls()

        for field, value in primitive['designate_object.data'].items():
            if isinstance(value, dict) and 'designate_object.name' in value:
                setattr(instance, field, DesignateObject.from_primitive(value))
            else:
                setattr(instance, field, value)

        instance._obj_changes = set(primitive['designate_object.changes'])
        instance._obj_original_values = \
            primitive['designate_object.original_values']

        return instance

    @classmethod
    def from_dict(cls, _dict):
        instance = cls()

        for field, value in _dict.items():
            if (field in instance.FIELDS and
                    instance.FIELDS[field].get('relation', False)):
                relation_cls_name = instance.FIELDS[field]['relation_cls']
                # We're dealing with a relation, we'll want to create the
                # correct object type and recurse
                relation_cls = cls.obj_cls_from_name(relation_cls_name)

                if isinstance(value, list):
                    setattr(instance, field, relation_cls.from_list(value))
                else:
                    setattr(instance, field, relation_cls.from_dict(value))

            else:
                setattr(instance, field, value)

        return instance

    @classmethod
    def from_list(cls, _list):
        raise NotImplementedError()

    @classmethod
    def obj_name(cls):
        """Return a canonical name for this object which will be used over
        the wire and in validation schemas.
        """
        return cls.__name__

    @classmethod
    def obj_get_schema(cls):
        """Returns the JSON Schema for this Object."""
        return cls._obj_validator.schema

    def __init__(self, **kwargs):
        self._obj_changes = set()
        self._obj_original_values = dict()

        for name, value in kwargs.items():
            if name in list(six.iterkeys(self.FIELDS)):
                setattr(self, name, value)
            else:
                raise TypeError("__init__() got an unexpected keyword "
                                "argument '%(name)s'" % {'name': name})

    def __str__(self):
        return (self._make_obj_str(self.STRING_KEYS)
                % self)

    @classmethod
    def _make_obj_str(cls, keys):
        msg = "<%(name)s" % {'name': cls.obj_name()}
        for key in keys:
            msg += " {0}:'%({0})s'".format(key)
        msg += ">"
        return msg

    def to_primitive(self):
        """
        Convert the object to primitive types so that the object can be
        serialized.
        NOTE: Currently all the designate objects contain primitive types that
        do not need special handling.  If this changes we need to modify this
        function.
        """
        data = {}

        for field in six.iterkeys(self.FIELDS):
            if self.obj_attr_is_set(field):
                if isinstance(getattr(self, field), DesignateObject):
                    data[field] = getattr(self, field).to_primitive()
                else:
                    data[field] = getattr(self, field)

        return {
            'designate_object.name': self.obj_name(),
            'designate_object.data': data,
            'designate_object.changes': sorted(self._obj_changes),
            'designate_object.original_values': dict(self._obj_original_values)
        }

    def to_dict(self):
        """Convert the object to a simple dictionary."""
        data = {}

        for field in six.iterkeys(self.FIELDS):
            if self.obj_attr_is_set(field):
                val = getattr(self, field)
                if isinstance(val, ListObjectMixin):
                    data[field] = val.to_list()
                elif isinstance(val, DesignateObject):
                    data[field] = val.to_dict()
                else:
                    data[field] = val

        return data

    def update(self, values):
        """Update a object's fields with the supplied key/value pairs"""
        for k, v in values.items():
            setattr(self, k, v)

    @property
    def is_valid(self):
        """Returns True if the Object is valid."""

        make_class_validator(self)

        return self._obj_validator.is_valid(self.to_dict())

    def validate(self):

        make_class_validator(self)

        # NOTE(kiall): We make use of the Object registry here in order to
        #              avoid an impossible circular import.
        ValidationErrorList = self.obj_cls_from_name('ValidationErrorList')
        ValidationError = self.obj_cls_from_name('ValidationError')

        errors = ValidationErrorList()

        try:
            values = self.to_dict()
        except exceptions.RelationNotLoaded as e:
            e = ValidationError()
            e.path = ['type']
            e.validator = 'required'
            e.validator_value = [e.relation]
            e.message = "'%s' is a required property" % e.relation
            errors.append(e)
            raise exceptions.InvalidObject(
                "Provided object does not match "
                "schema", errors=errors, object=self)

        LOG.debug("Validating '%(name)s' object with values: %(values)r", {
            'name': self.obj_name(),
            'values': values,
        })

        for error in self._obj_validator.iter_errors(values):
            errors.append(ValidationError.from_js_error(error))

        if len(errors) > 0:
            LOG.debug(
                "Error Validating '%(name)s' object with values: "
                "%(values)r", {
                    'name': self.obj_name(),
                    'values': values,
                }
            )
            raise exceptions.InvalidObject(
                "Provided object does not match "
                "schema", errors=errors, object=self)

    def obj_attr_is_set(self, name):
        """
        Return True or False depending of if a particular attribute has had
        an attribute's value explicitly set.
        """
        return hasattr(self, get_attrname(name))

    def obj_what_changed(self):
        """Returns a set of fields that have been modified."""
        return set(self._obj_changes)

    def obj_get_changes(self):
        """Returns a dict of changed fields and their new values."""
        changes = {}

        for key in self.obj_what_changed():
            changes[key] = getattr(self, key)

        return changes

    def obj_reset_changes(self, fields=None):
        """Reset the list of fields that have been changed."""
        if fields:
            self._obj_changes -= set(fields)
            for field in fields:
                self._obj_original_values.pop(field, None)

        else:
            self._obj_changes.clear()
            self._obj_original_values = dict()

    def obj_get_original_value(self, field):
        """Returns the original value of a field."""
        if field in list(six.iterkeys(self._obj_original_values)):
            return self._obj_original_values[field]
        elif self.obj_attr_is_set(field):
            return getattr(self, field)
        else:
            raise KeyError(field)

    def __setattr__(self, name, value):
        """Enforces all object attributes are private or well defined"""
        if name[0:5] == '_obj_' or name in list(six.iterkeys(self.FIELDS)) \
                or name == 'FIELDS':
            super(DesignateObject, self).__setattr__(name, value)

        else:
            raise AttributeError(
                "Designate object '%(type)s' has no attribute '%(name)s'" % {
                    'type': self.obj_name(),
                    'name': name,
                })

    def __deepcopy__(self, memodict=None):
        """
        Efficiently make a deep copy of this object.

        "Efficiently" is used here a relative term, this will be faster
        than allowing python to naively deepcopy the object.
        """

        memodict = memodict or {}

        c_obj = self.__class__()

        for field in six.iterkeys(self.FIELDS):
            if self.obj_attr_is_set(field):
                c_field = copy.deepcopy(getattr(self, field), memodict)
                setattr(c_obj, field, c_field)

        c_obj._obj_changes = set(self._obj_changes)

        return c_obj

    def __eq__(self, other):
        if self.__class__ != other.__class__:
            return False

        return self.to_primitive() == other.to_primitive()

    def __ne__(self, other):
        return not(self.__eq__(other))

class DictObjectMixin(object):
    """
    Mixin to allow DesignateObjects to behave like dictionaries

    Eventually, this should be removed as other code is updated to use object
    rather than dictionary accessors.
    """
    def __getitem__(self, key):
        return getattr(self, key)

    def __setitem__(self, key, value):
        setattr(self, key, value)

    def __contains__(self, item):
        return item in list(six.iterkeys(self.FIELDS))

    def get(self, key, default=NotSpecifiedSentinel):
        if key not in list(six.iterkeys(self.FIELDS)):
            raise AttributeError("'%s' object has no attribute '%s'" % (
                                 self.__class__, key))

        if default != NotSpecifiedSentinel and not self.obj_attr_is_set(key):
            return default
        else:
            return getattr(self, key)

    def items(self):
        for field in six.iterkeys(self.FIELDS):
            if self.obj_attr_is_set(field):
                yield field, getattr(self, field)

    # Compatibility with jsonutils to_primitive(). See bug
    # https://bugs.launchpad.net/designate/+bug/1481377
    iteritems = items

    def __iter__(self):
        for field in six.iterkeys(self.FIELDS):
            if self.obj_attr_is_set(field):
                yield field, getattr(self, field)

class ListObjectMixin(object):
    """Mixin to allow DesignateObjects to behave like python lists."""
    FIELDS = {
        'objects': {
            'relation': True
        }
    }
    LIST_ITEM_TYPE = DesignateObject

    @classmethod
    def _obj_from_primitive(cls, primitive):
        instance = cls()

        for field, value in primitive['designate_object.data'].items():
            if field == 'objects':
                instance.objects = [DesignateObject.from_primitive(v) for v in
                                    value]
            elif isinstance(value, dict) and 'designate_object.name' in value:
                setattr(instance, field, DesignateObject.from_primitive(value))
            else:
                setattr(instance, field, value)

        instance._obj_changes = set(primitive['designate_object.changes'])
        instance._obj_original_values = \
            primitive['designate_object.original_values']

        return instance

    @classmethod
    def from_list(cls, _list):
        instance = cls()

        for item in _list:
            instance.append(cls.LIST_ITEM_TYPE.from_dict(item))

        return instance

    def to_list(self):

        list_ = []

        for item in self.objects:
            if isinstance(item, ListObjectMixin):
                list_.append(item.to_list())
            elif isinstance(item, DesignateObject):
                list_.append(item.to_dict())
            else:
                list_.append(item)

        return list_

    def __init__(self, *args, **kwargs):
        super(ListObjectMixin, self).__init__(*args, **kwargs)
        if 'objects' not in kwargs:
            self.objects = []
            self.obj_reset_changes(['objects'])

    def to_primitive(self):
        data = {}

        for field in six.iterkeys(self.FIELDS):
            if self.obj_attr_is_set(field):
                if field == 'objects':
                    data[field] = [o.to_primitive() for o in self.objects]
                elif isinstance(getattr(self, field), DesignateObject):
                    data[field] = getattr(self, field).to_primitive()
                else:
                    data[field] = getattr(self, field)

        return {
            'designate_object.name': self.obj_name(),
            'designate_object.data': data,
            'designate_object.changes': list(self._obj_changes),
            'designate_object.original_values': dict(self._obj_original_values)
        }

    def __str__(self):
        return (_("<%(type)s count:'%(count)s' object:'%(list_type)s'>")
                % {'count': len(self),
                   'type': self.LIST_ITEM_TYPE.obj_name(),
                   'list_type': self.obj_name()})

    def __iter__(self):
        """List iterator interface"""
        return iter(self.objects)

    def __len__(self):
        """List length"""
        return len(self.objects)

    def __getitem__(self, index):
        """List index access"""
        if isinstance(index, slice):
            new_obj = self.__class__()
            new_obj.objects = self.objects[index]
            new_obj.obj_reset_changes()
            return new_obj
        return self.objects[index]

    def __setitem__(self, index, value):
        """Set list index value"""
        self.objects[index] = value

    def __contains__(self, value):
        """List membership test"""
        return value in self.objects

    def append(self, value):
        """Append a value to the list"""
        return self.objects.append(value)

    def extend(self, values):
        """Extend the list by appending all the items in the given list"""
        return self.objects.extend(values)

    def pop(self, index):
        """Pop a value from the list"""
        return self.objects.pop(index)

    def insert(self, index, value):
        """Insert a value into the list at the given index"""
        return self.objects.insert(index, value)

    def remove(self, value):
        """Remove a value from the list"""
        return self.objects.remove(value)

    def index(self, value):
        """List index of value"""
        return self.objects.index(value)

    def count(self, value):
        """List count of value occurrences"""
        return self.objects.count(value)

    def sort(self, key=None, reverse=False):
        self.objects.sort(key=key, reverse=reverse)

    def obj_what_changed(self):
        changes = set(self._obj_changes)
        for item in self.objects:
            if item.obj_what_changed():
                changes.add('objects')
        return changes

class PersistentObjectMixin(object):
    """
    Mixin class for Persistent objects.

    This adds the fields that we use in common for all persistent objects.
    """
    FIELDS = {
        'id': {
            'schema': {
                'type': 'string',
                'format': 'uuid',
            },
            'read_only': True
        },
        'created_at': {
            'schema': {
                'type': 'string',
                'format': 'date-time',
            },
            'read_only': True
        },
        'updated_at': {
            'schema': {
                'type': ['string', 'null'],
                'format': 'date-time',
            },
            'read_only': True
        },
        'version': {
            'schema': {
                'type': 'integer',
            },
            'read_only': True
        }
    }

    STRING_KEYS = ['id']

class SoftDeleteObjectMixin(object):
    """
    Mixin class for Soft-Deleted objects.

    This adds the fields that we use in common for all soft-deleted objects.
    """
    FIELDS = {
        'deleted': {
            'schema': {
                'type': ['string', 'integer'],
            },
            'read_only': True
        },
        'deleted_at': {
            'schema': {
                'type': ['string', 'null'],
                'format': 'date-time',
            },
            'read_only': True
        }
    }

class PagedListObjectMixin(object):
    """
    Mixin class for List objects.

    This adds fields that would populate API metadata for collections.
    """
    FIELDS = {
        'total_count': {
            'schema': {
                'type': ['integer'],
            }
        }
    }


text:
  {{#if img}}

  {{/if}}

{{title}}

{{excerpt}}

    Open Link


text:
<?PHP
// load application header
require('../includes/application_top.php');
// load application front header
require(INCLUDES_DIR.'front_top.php');

// load account login page class
if (!class_exists('advertiser_login_pg')) {
	require(CLASSES_DIR.'pages/advertiser_login.php');
	$advertiser_login_pg = new advertiser_login_pg;
}

$page_output = '
';
if ($_SESSION['advertiser_logged_in'] == 1) {
	$page_output .= 'You appear to already be logged in.';
} else {
	if ($_POST['submit'] === 'Advertiser Sign In') {

		// check if customer is logged in
		if (!empty($_POST['username']) && !empty($_POST['password'])) {

			$adv_info_tbl->user_login_check();
			if ($_SESSION['advertiser_logged_in'] != 1) {
				$page_output .= create_warning_box('Either the username or password provided was invalid.');
				$page_output .= $advertiser_login_pg->draw_login_form();
			} else {
				if($adv_info_tbl->email_authorized == 1) {
					if($adv_info_tbl->customer_level > 0) {
						$_SESSION['just_logged_in'] = 1;
						header("Location: ".SITE_SSL_URL."advertiser_admin/");
					} else {
						header("Location: ".SITE_SSL_URL."advertiser_admin/create_account_user_level_select.deal");
					}
				} else {
					$page_output .= create_warning_box('You have not yet authorized your account. Please authorize your account before logging in.');
					unset($_SESSION['advertiser_logged_in']);
					unset($_SESSION['advertiser_id']);
					unset($_SESSION['approved']);
					unset($_SESSION['customer_level']);
					unset($_SESSION['allow_multiple_logins']);
					$page_output .= $advertiser_login_pg->draw_login_form();
				}
			}

		} else {
			$page_output .= create_warning_box('You did not provide either a username or a password.');
			$page_output .= $advertiser_login_pg->draw_login_form();
		}

	} else {
		$page_output .= $advertiser_login_pg->draw_login_form();
	}
}
$page_output .= '
';

// set page header -- only assign for static header data
$page_header_title = 'CheapLocalDeals.com - Advertiser Account Login';
$page_meta_description = 'Advertiser Account Login';
$page_meta_keywords = 'Advertiser Account Login';

// assign header constant
$prnt_header = new prnt_header();
$prnt_header->page_header_title = $page_header_title;
$prnt_header->page_meta_description = $page_meta_description;
$prnt_header->page_meta_keywords = $page_meta_keywords;
define('PAGE_HEADER',$prnt_header->print_page_header());

// start output buffer
ob_start();

	// load template
	require(TEMPLATE_DIR.'blank.php');

	$html = ob_get_contents();

ob_end_clean();

print_page($html);
?>


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.xander.number</groupId>
    <artifactId>TDD-Katas</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>TDD-Katas</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <junit.version>4.11</junit.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.github.stefanbirkner</groupId>
            <artifactId>system-rules</artifactId>
            <version>1.5.0</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>TDD-Katas</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <compilerArguments>
                        <Xlint/>
                    </compilerArguments>
                    <verbose>true</verbose>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <showWarnings>true</showWarnings>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.owasp</groupId>
                <version>1.4.3</version>
                <artifactId>dependency-check-maven</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>check</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-pmd-plugin</artifactId>
                <version>3.8</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
                <version>2.17</version>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>findbugs-maven-plugin</artifactId>
                <version>3.0.4</version>
                <configuration>
                    <xmlOutput>true</xmlOutput>
                    <xmlOutputDirectory>target/site</xmlOutputDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
var Notes   = require('./')
  , inspect = require('util').inspect
  ;

var notes = new Notes(
{
  user: process.argv[2] || process.env['user'],
  password: process.argv[3] || process.env['pass'],
  host: 'imap.gmail.com',
  port: 993,
  tls: true,
  tlsOptions: { rejectUnauthorized: false }
});

notes.connect(function(err)
{
  if (err) throw err;

  console.log(['Connected']);

  notes.search({subject: 'test'}, function(err, list)
  {
    if (err) throw err;

    console.log('Done', inspect(list, false, 4, true));

    notes.end();
  });
});


text:
var questions = [
  {
    question: 'At least 15% of all our users require some accessibility assistance.',
    correct: 0,
    choices: [
      'True',
      'False',
    ]
  },
  {
    question: 'WAI-ARIA stands for:',
    correct: 1,
    choices: [
      'Web Accessibility Initiative, Accessibility Rights Internet Awareness',
      'Web Accessibility Initiative, Accessible Rich Internet Applications',
      'Why Acronyms Indeed, Another Real Idiotic Acronym',
    ]
  },
  {
    question: 'The `alt` attribute is helpful for users with what kind of impairments?',
    correct: 0,
    choices: [
      'Visual impairments',
      'Auditory impairments',
      'Mobility & dexterity impairments',
      'Cognitive impairments',
    ]
  },
  {
    question: 'Keyboard access is helpful for users with what kind of impairments?',
    correct: 2,
    choices: [
      'Visual impairments',
      'Auditory impairments',
      'Mobility & dexterity impairments',
      'Cognitive impairments',
    ]
  },
  {
    question: 'When using video, what is helpful for users with auditory impairments?',
    correct: 3,
    choices: [
      'Not auto-playing the video',
      'Captions & transcripts',
      'Volume controls',
      'All of the above',
    ]
  },
  {
    question: 'Why is it important to underline links when designing websites?',
    correct: 3,
    choices: [
      'To easily distinguish links from the surrounding text',
      'Because colour by itself isn't a good enough indicator',
      'To help the text be more scannable',
      'All of the above',
    ]
  },
  {
    question: 'The ARIA role of `banner` is used to denote:',
    correct: 1,
    choices: [
      'The location of the hero banner graphic of the website',
      'The location of the site-oriented content like the logo, identity & navigation',
      'The location on the page where the primary navigation is located',
    ]
  },
  {
    question: 'The ARIA role of `contentinfo` is used to denote:',
    correct: 0,
    choices: [
      'The region that contains copyright statements, privacy policies, etc.',
      'The region that contains information about the source of the content',
      'The region that contains extra information that's not necessary for understanding',
    ]
  },
  {
    question: 'Why are headings important considerations when designing websites?',
    correct: 3,
    choices: [
      'To help navigating around pages',
      'To help understand the flow of pages',
      'To help make pages more scannable',
      'All of the above',
    ]
  },
  {
    question: 'Why are em-based media queries helpful from an accessibility perspective?',
    correct: 1,
    choices: [
      'Many browsers only support em-based media queries',
      'They allow the website to adjust its layout when the font-size changes',
      'They allow the user to redefine when the media queries are activated',
    ]
  },
];

MultipleChoice(ActivityRunner(), questions);


text:
/* @flow */

import type Watcher from './watcher'
import config from '../config'
import { callHook, activateChildComponent } from '../instance/lifecycle'

import {
  warn,
  nextTick,
  devtools
} from '../util/index'

export const MAX_UPDATE_COUNT = 100

const queue: Array<Watcher> = []
const activatedChildren: Array<Component> = []
let has: { [key: number]: ?true } = {}
let circular: { [key: number]: number } = {}
let waiting = false
let flushing = false
let index = 0

/**
 * Reset the scheduler's state.
 */
function resetSchedulerState () {
  index = queue.length = activatedChildren.length = 0
  has = {}
  if (process.env.NODE_ENV !== 'production') {
    circular = {}
  }
  waiting = flushing = false
}

/**
 * Flush both queues and run the watchers.
 */
function flushSchedulerQueue () {
  flushing = true
  let watcher, id

  // Sort queue before flush.
  // This ensures that:
  // 1. Components are updated from parent to child. (because parent is always
  //    created before the child)
  // 2. A component's user watchers are run before its render watcher (because
  //    user watchers are created before the render watcher)
  // 3. If a component is destroyed during a parent component's watcher run,
  //    its watchers can be skipped.
  // ----------------------------------------------------------------------------------------------
  // 从小到大进行排序,可以保证:
  // 1. 组件是从父组件开始更新的,其次才是子组件(因为父组件先于子组件创建)
  // 2. 一个组件的 user watcher 先于它的 render watcher 执行(因为 user watcher 先于 render watcher 创建)
  // 3. 如果某一组件的父组件在执行 watcher.run 时被销毁了,该组件就无需执行更新函数了
  queue.sort((a, b) => a.id - b.id)

  // do not cache length because more watchers might be pushed
  // as we run existing watchers
  // 循环时动态获取队列的长度
  for (index = 0; index < queue.length; index++) {
    watcher = queue[index]
    id = watcher.id
    has[id] = null
    watcher.run()
    // in dev build, check and stop circular updates.
    if (process.env.NODE_ENV !== 'production' && has[id] != null) {
      circular[id] = (circular[id] || 0) + 1
      if (circular[id] > MAX_UPDATE_COUNT) {
        warn(
          'You may have an infinite update loop ' + (
            watcher.user
              ? `in watcher with expression "${watcher.expression}"`
              : `in a component render function.`
          ),
          watcher.vm
        )
        break
      }
    }
  }

  // keep copies of post queues before resetting state
  const activatedQueue = activatedChildren.slice()
  const updatedQueue = queue.slice()

  resetSchedulerState()

  // call component updated and activated hooks
  callActivatedHooks(activatedQueue)
  callUpdatedHooks(updatedQueue)

  // devtool hook
  /* istanbul ignore if */
  if (devtools && config.devtools) {
    devtools.emit('flush')
  }
}

function callUpdatedHooks (queue) {
  let i = queue.length
  while (i--) {
    const watcher = queue[i]
    const vm = watcher.vm
    // vm._watcher 保存的是渲染模板时创建的 watcher,所以如果队列中有该 watcher,则说明模板有变化,随之调用 updated 钩子函数。
    if (vm._watcher === watcher && vm._isMounted) {
      // 由于数据更改导致的虚拟 DOM 重新渲染和打补丁,在这之后会调用该钩子
      // 当这个钩子被调用时,组件 DOM 已经更新,所以你现在可以执行依赖于 DOM 的操作
      // 然而在大多数情况下,你应该避免在此期间更改状态,因为这可能会导致更新无限循环
      callHook(vm, 'updated')
    }
  }
}

/**
 * Queue a kept-alive component that was activated during patch.
 * The queue will be processed after the entire tree has been patched.
 */
export function queueActivatedComponent (vm: Component) {
  // setting _inactive to false here so that a render function can
  // rely on checking whether it's in an inactive tree (e.g. router-view)
  vm._inactive = false
  activatedChildren.push(vm)
}

function callActivatedHooks (queue) {
  for (let i = 0; i < queue.length; i++) {
    queue[i]._inactive = true
    activateChildComponent(queue[i], true /* true */)
  }
}

/**
 * Push a watcher into the watcher queue.
 * Jobs with duplicate IDs will be skipped unless it's
 * pushed when the queue is being flushed.
 * 对于同步多次更改被监听的数据的值的情况,因为会检查 watcher.id 所以 watcher 只被推入一次
 * 故只会调用一次 watcher.run 方法,从而只触发一次 DOM 操作
 */
export function queueWatcher (watcher: Watcher) {
  const id = watcher.id
  // 只有没有推入队列中的 watcher 才会被放入,是为了防止多次触发 DOM 更新
  if (has[id] == null) {
    has[id] = true
    if (!flushing) {
      queue.push(watcher)
    } else {
      // if already flushing, splice the watcher based on its id
      // if already past its id, it will be run next immediately.
      let i = queue.length - 1
      while (i > index && queue[i].id > watcher.id) {
        i--
      }
      queue.splice(i + 1, 0, watcher)
    }
    // queue the flush
    if (!waiting) {
      waiting = true
      nextTick(flushSchedulerQueue)
    }
  }
}


text:
it is our passion, but most of all it is our way of life.
We will take care of the highest quality of your training,
as well as safety and fun! Trust us – we know how to make you
fall in love with kite and board.

All our courses will not have more than 3 participants per instructor.
Students will rotate for better learning results. Depending on your
talent or pre-existing experience with sports as windsurfing, power kiting,
wake boarding each student learns differently fast. We always give our best
efforts for your maximum success.

You`re looking for individual courses or package deals? Just click our
packages or send us a request.

The kiteschool provides you with the latest gear of
F-One.

Our instructors speak English, German, Dutch (Netherlands), Russian,
Polish, Ukrainian, Serbian.


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
backtype.storm.serialization (Storm Core 0.9.1-incubating-SNAPSHOT API)
</TITLE>

<META NAME="date" CONTENT="2014-02-04">

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

backtype.storm.serialization

Interfaces

IKryoDecorator

IKryoFactory

ITupleDeserializer

ITupleSerializer

Classes

DefaultKryoFactory

DefaultKryoFactory.KryoSerializableDefault

KryoTupleDeserializer

KryoTupleSerializer

KryoValuesDeserializer

KryoValuesSerializer

SerializableSerializer

SerializationFactory

SerializationFactory.IdDictionary


text:
<?php

namespace WT\SemestralkaBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class WTSemestralkaBundle extends Bundle
{
}


text:
<?php
# src/Acme/DemoBundle/Command/CreateClientCommand.php
namespace AppBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use AppBundle\Entity\College;
use AppBundle\Entity\User;

class CreateUserCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('adrestia:new-user')
            ->setDescription('Creates a new user with the required parameters')
            ->addArgument(
                'email',
                InputArgument::REQUIRED,
                'Please put in an email address for the user.'
            )
            ->addArgument(
                'password',
                InputArgument::REQUIRED,
                'Please put in the password for the user.'
            )
            ->addArgument(
                'college_id',
                InputArgument::REQUIRED,
                'Add in the id of the college. Get from database.'
            );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $email = $input->getArgument('email');
        $plain_password = $input->getArgument('password');
        $college_id = $input->getArgument('college_id');

        $em = $this->getContainer()->get('doctrine')->getManager();
        $college = $em->getRepository("AppBundle:College")->find($college_id);

        $user = new User();

        $user->setEmail($email);
        $user->setEmailConfirmed(true);
        $user->setCollege($college);

        $password = $this->getContainer()
            ->get('security.password_encoder')
            ->encodePassword($user, $plain_password);
         $user->setPassword($password);

         do {
             $apikey = self::guidv4();
             $entity = $em->getRepository('AppBundle\Entity\User')->findOneBy(array('api_key' => $apikey));
         } while($entity !== null);

         // Set their API key
         $user->setApiKey($apikey);

         // Save the user
         $em->persist($user);
         $em->flush();

        $output->writeln("Successfully created a new user.");
    }

    protected function guidv4()
    {
        $data = openssl_random_pseudo_bytes(16);
        assert(strlen($data) == 16);

        $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10

        return vsprintf('%s%s%s%s%s%s%s%s', str_split(bin2hex($data), 4));
    }
}


text:
class QJSEngine;
class TJSInstance;

class T_CORE_EXPORT TJSModule : public QObject
{
public:
    TJSModule(QObject *parent = nullptr);
    virtual ~TJSModule();

    QJSValue evaluate(const QString &program, const QString &fileName = QString(), int lineNumber = 1);
    QJSValue call(const QString &func, const QJSValue &arg);
    QJSValue call(const QString &func, const QJSValueList &args = QJSValueList());
    TJSInstance callAsConstructor(const QString &constructorName, const QJSValue &arg);
    TJSInstance callAsConstructor(const QString &constructorName, const QJSValueList &args = QJSValueList());
    QString modulePath() const { return moduleFilePath; }

    QJSValue import(const QString &moduleName);
    QJSValue import(const QString &defaultMember, const QString &moduleName);

private:
    QJSEngine *jsEngine;
    QMap<QString, QString> loadedFiles;
    QJSValue *funcObj;
    QString lastFunc;
    QString moduleFilePath;
    QMutex mutex;

    Q_DISABLE_COPY(TJSModule);

    friend class TJSLoader;
    friend class TReactComponent;
};

#endif // TJSMODULE_H


text:
require 'spec_helper'

describe Groups::AutoDevopsService, '#execute' do
  set(:group) { create(:group) }
  set(:user) { create(:user) }
  let(:group_params) { { auto_devops_enabled: '0' } }
  let(:service) { described_class.new(group, user, group_params) }

  context 'when user does not have enough privileges' do
    it 'raises exception' do
      group.add_developer(user)

      expect do
        service.execute
      end.to raise_exception(Gitlab::Access::AccessDeniedError)
    end
  end

  context 'when user has enough privileges' do
    before do
      group.add_owner(user)
    end

    it 'updates group auto devops enabled accordingly' do
      service.execute

      expect(group.auto_devops_enabled).to eq(false)
    end

    context 'when group has projects' do
      it 'reflects changes on projects' do
        project_1 = create(:project, namespace: group)

        service.execute

        expect(project_1).not_to have_auto_devops_implicitly_enabled
      end
    end

    context 'when group has subgroups' do
      it 'reflects changes on subgroups' do
        subgroup_1 = create(:group, parent: group)

        service.execute

        expect(subgroup_1.auto_devops_enabled?).to eq(false)
      end

      context 'when subgroups have projects' do
        it 'reflects changes on projects' do
          subgroup_1 = create(:group, parent: group)
          project_1 = create(:project, namespace: subgroup_1)

          service.execute

          expect(project_1).not_to have_auto_devops_implicitly_enabled
        end
      end
    end
  end
end


text:
"use strict"; // run code in ES5 strict mode

var pathUtil = require("path");

/**
 * Unifies a path to alleviate working with paths on different platforms. It
 *
 * - makes all paths absolute (adds a preceding "/" or "c:/" if necessary)
 * - normalizes the path
 * - applies linux-style path separators "/"
 * - removes a trailing slash
 *
 * @param {!String} path
 * @throws {TypeError}
 * @return {String}
 */
function unify(path) {
    var isWindows = process.platform.search(/^win/) !== -1;

    if (typeof path !== "string") {
        throw new TypeError("(fshelpers) The path must be a string. Instead saw '" + typeof path + "'");
    }

    // Make path absolute depending on platform
    if (isWindows) {
        path = path.replace(/^[\/\\]/, ""); // trim leading slash if present
        if (/^[a-z]\:/i.test(path) === false) {
            path = "c:/" + path;    // fallback: we"re assuming that we"re on drive C:
        } else {
            path = path.charAt(0).toLowerCase() + path.substr(1);
        }
    } else {
        path = "/" + path;
    }

    path = pathUtil.normalize(path);

    // Turn all path separators to linux-style
    if (pathUtil.sep !== "/") {
        path = path.replace(new RegExp("\\" + pathUtil.sep, "g"), "/");
    }

    // Remove trailing slash
    if ((isWindows === false && path.length > 1) || (isWindows && path.length > 3)) {
        if (path.charAt(path.length - 1) === "/") {
            path = path.substr(0, path.length - 1);
        }
    }

    return path;
}

module.exports = unify;


text:
/**
 * A service locator implementation.
 *
 * Can be used with or without a CDI (JSR330) container.
 *
 * @see ml.alternet.discover.DiscoveryService
 */
@ml.alternet.misc.InfoClass
package ml.alternet.discover;


text:
namespace chatterino {

struct Emote;
using EmotePtr = std::shared_ptr<const Emote>;

class Channel;
class TwitchChannel;

struct TwitchEmoteOccurence {
    int start;
    int end;
    EmotePtr ptr;
    EmoteName name;
};

class TwitchMessageBuilder : public SharedMessageBuilder
{
public:
    enum UsernameDisplayMode : int {
        Username = 1,                  // Username
        LocalizedName = 2,             // Localized name
        UsernameAndLocalizedName = 3,  // Username (Localized name)
    };

    TwitchMessageBuilder() = delete;

    explicit TwitchMessageBuilder(Channel *_channel,
                                  const Communi::IrcPrivateMessage *_ircMessage,
                                  const MessageParseArgs &_args);
    explicit TwitchMessageBuilder(Channel *_channel,
                                  const Communi::IrcMessage *_ircMessage,
                                  const MessageParseArgs &_args,
                                  QString content, bool isAction);

    TwitchChannel *twitchChannel;

    [[nodiscard]] bool isIgnored() const override;
    void triggerHighlights() override;
    MessagePtr build() override;

    static void appendChannelPointRewardMessage(
        const ChannelPointReward &reward, MessageBuilder *builder);

    // Message in the /live chat for channel going live
    static void liveMessage(const QString &channelName,
                            MessageBuilder *builder);

    // Messages in normal chat for channel stuff
    static void liveSystemMessage(const QString &channelName,
                                  MessageBuilder *builder);
    static void offlineSystemMessage(const QString &channelName,
                                     MessageBuilder *builder);
    static void hostingSystemMessage(const QString &channelName,
                                     MessageBuilder *builder);

private:
    void parseUsernameColor() override;
    void parseUsername() override;
    void parseMessageID();
    void parseRoomID();
    void appendUsername();

    void runIgnoreReplaces(std::vector<TwitchEmoteOccurence> &twitchEmotes);

    boost::optional<EmotePtr> getTwitchBadge(const Badge &badge);
    void appendTwitchEmote(const QString &emote,
                           std::vector<TwitchEmoteOccurence> &vec,
                           std::vector<int> &correctPositions);
    Outcome tryAppendEmote(const EmoteName &name) override;

    void addWords(const QStringList &words,
                  const std::vector<TwitchEmoteOccurence> &twitchEmotes);
    void addTextOrEmoji(EmotePtr emote) override;
    void addTextOrEmoji(const QString &value) override;

    void appendTwitchBadges();
    void appendChatterinoBadges();
    void appendFfzBadges();
    Outcome tryParseCheermote(const QString &string);

    QString roomID_;
    bool hasBits_ = false;
    QString bits;
    int bitsLeft;
    bool bitsStacked = false;
    bool historicalMessage_ = false;

    QString userId_;
    bool senderIsBroadcaster{};
};

}  // namespace chatterino


text:
<?php
	/**
	 * Action to reset a password and send success email.
	 *
	 * @package Elgg
	 * @subpackage Core
	 * @author Curverider Ltd
	 * @link http://elgg.org/
	 */

	require_once(dirname(dirname(dirname(__FILE__))) . "/engine/start.php");
	global $CONFIG;

	$user_guid = get_input('u');
	$code = get_input('c');

	if (execute_new_password_request($user_guid, $code))
		system_message(elgg_echo('user:password:success'));
	else
		register_error(elgg_echo('user:password:fail'));

	forward();
	exit;

?>


text:
class Siege < Formula
  desc "HTTP regression testing and benchmarking utility"
  homepage "https://www.joedog.org/siege-home/"
  url "http://download.joedog.org/siege/siege-4.0.2.tar.gz"
  sha256 "7efb81f9547bef0e693bdd51348a205ad691e1d72c36041f4608099ba0326c47"

  bottle do
    sha256 "727ee17ca64eb752916cf8318d0cda9a56b094d358b46b04b33d66872373f843" => :sierra
    sha256 "787e7394cc038b1a06d164faebbb0b02a37f32757abbf80da223d46b0f0091e5" => :el_capitan
    sha256 "932fce124172f3b1e25bfcbe673feffccf1a86ea97f00564ecaeb01f4950d3bb" => :yosemite
    sha256 "6575d3bc644e7acecbeab9b7c8fed77c7c523a709e9b2184501b2d40c7eb8d5f" => :mavericks
  end

  depends_on "openssl"

  def install
    # To avoid unnecessary warning due to hardcoded path, create the folder first
    (prefix/"etc").mkdir
    system "./configure", "--disable-dependency-tracking",
                          "--prefix=#{prefix}",
                          "--mandir=#{man}",
                          "--localstatedir=#{var}",
                          "--with-ssl=#{Formula["openssl"].opt_prefix}"
    system "make", "install"
  end

  def caveats; <<-EOS.undent
    Mac OS X has only 16K ports available that won't be released until socket
    TIME_WAIT is passed. The default timeout for TIME_WAIT is 15 seconds.
    Consider reducing in case of available port bottleneck.

    You can check whether this is a problem with netstat:

        # sysctl net.inet.tcp.msl
        net.inet.tcp.msl: 15000

        # sudo sysctl -w net.inet.tcp.msl=1000
        net.inet.tcp.msl: 15000 -> 1000

    Run siege.config to create the ~/.siegerc config file.
    EOS
  end

  test do
    system "#{bin}/siege", "--concurrent=1", "--reps=1", "https://www.google.com/"
  end
end


text:
package io.grpc.netty;

import static com.google.common.base.Preconditions.checkNotNull;

import io.grpc.Status;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.util.ReferenceCountUtil;
import java.net.SocketAddress;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Buffers all writes until either {@link #writeBufferedAndRemove(ChannelHandlerContext)} or
 * {@link #failWrites(Throwable)} is called. This handler allows us to
 * write to a {@link io.netty.channel.Channel} before we are allowed to write to it officially
 * i.e.  before it's active or the TLS Handshake is complete.
 */
final class WriteBufferingAndExceptionHandler extends ChannelDuplexHandler {
  private static final Logger logger =
      Logger.getLogger(WriteBufferingAndExceptionHandler.class.getName());

  private final Queue<ChannelWrite> bufferedWrites = new ArrayDeque<>();
  private final ChannelHandler next;
  private boolean writing;
  private boolean flushRequested;
  private Throwable failCause;

  WriteBufferingAndExceptionHandler(ChannelHandler next) {
    this.next = checkNotNull(next, "next");
  }

  @Override
  public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    ctx.pipeline().addBefore(ctx.name(), null, next);
    super.handlerAdded(ctx);
    // kick off protocol negotiation.
    ctx.pipeline().fireUserEventTriggered(ProtocolNegotiationEvent.DEFAULT);
  }

  @Override
  public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    if (!bufferedWrites.isEmpty()) {
      Status status = Status.INTERNAL.withDescription("Buffer removed before draining writes");
      failWrites(status.asRuntimeException());
    }
    super.handlerRemoved(ctx);
  }

  /**
   * If this channel becomes inactive, then notify all buffered writes that we failed.
   */
  @Override
  public void channelInactive(ChannelHandlerContext ctx) {
    Status status = Status.UNAVAILABLE.withDescription(
        "Connection closed while performing protocol negotiation for " + ctx.pipeline().names());
    failWrites(status.asRuntimeException());
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    assert cause != null;
    Throwable previousFailure = failCause;
    Status status = Utils.statusFromThrowable(cause)
        .augmentDescription("Channel Pipeline: " + ctx.pipeline().names());
    failWrites(status.asRuntimeException());
    // Check to see if the channel is active and this is the first failure.  If a downstream
    // handler triggers an exception in close(), avoid being reentrant.  This is not obviously
    // correct, so here are the cases and how they are correctly handled:
    // 1. !active, prev==null: the channel is inactive, no-op
    // 2. !active, prev!=null: the channel is inactive, no-op
    // 3.  active, prev==null: this is the first error, close
    // 4a. active, prev!=null[channelInactive]: impossible, no-op
    // 4b. active, prev!=null[close]: close() cannot succeed, no point in calling ctx.close().
    // 4c. active, prev!=null[handlerRemoved]: channel will be closed out-of-band by buffered write.
    // 4d. active, prev!=null[connect]: impossible, channel can't be active after a failed connect.
    if (ctx.channel().isActive() && previousFailure == null) {
      final class LogOnFailure implements ChannelFutureListener {
        @Override
        public void operationComplete(ChannelFuture future) {
          if (!future.isSuccess()) {
            logger.log(Level.FINE, "Failed closing channel", future.cause());
          }
        }
      }

      ctx.close().addListener(new LogOnFailure());
    }
  }

  /**
   * Buffers the write until either {@link #writeBufferedAndRemove(ChannelHandlerContext)} is
   * called, or we have somehow failed. If we have already failed in the past, then the write
   * will fail immediately.
   */
  @Override
  @SuppressWarnings("FutureReturnValueIgnored")
  public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
    if (failCause != null) {
      promise.setFailure(failCause);
      ReferenceCountUtil.release(msg);
    } else {
      // Do not special case GracefulServerCloseCommand, as we don't want to cause handshake
      // failures.
      if (msg instanceof GracefulCloseCommand || msg instanceof ForcefulCloseCommand) {
        // No point in continuing negotiation
        ctx.close();
        // Still enqueue the command in case the HTTP/2 handler is already on the pipeline
      }
      bufferedWrites.add(new ChannelWrite(msg, promise));
    }
  }

  /**
   * Connect failures do not show up as {@link #channelInactive} or {@link #exceptionCaught}, so
   * it needs to be watched.
   */
  @Override
  public void connect(
      ChannelHandlerContext ctx,
      SocketAddress remoteAddress,
      SocketAddress localAddress,
      ChannelPromise promise) throws Exception {
    final class ConnectListener implements ChannelFutureListener {
      @Override
      public void operationComplete(ChannelFuture future) {
        if (!future.isSuccess()) {
          failWrites(future.cause());
        }
      }
    }

    super.connect(ctx, remoteAddress, localAddress, promise);
    promise.addListener(new ConnectListener());
  }

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) {
    try {
      if (logger.isLoggable(Level.FINE)) {
        Object loggedMsg = msg instanceof ByteBuf ? ByteBufUtil.hexDump((ByteBuf) msg) : msg;
        logger.log(
            Level.FINE,
            "Unexpected channelRead()->{0} reached end of pipeline {1}",
            new Object[] {loggedMsg, ctx.pipeline().names()});
      }
      exceptionCaught(
          ctx,
          Status.INTERNAL.withDescription(
              "channelRead() missed by ProtocolNegotiator handler: " + msg)
              .asRuntimeException());
    } finally {
      ReferenceCountUtil.safeRelease(msg);
    }
  }

  /**
   * Calls to this method will not trigger an immediate flush. The flush will be deferred until
   * {@link #writeBufferedAndRemove(ChannelHandlerContext)}.
   */
  @Override
  public void flush(ChannelHandlerContext ctx) {
    /**
     * Swallowing any flushes is not only an optimization but also required
     * for the SslHandler to work correctly. If the SslHandler receives multiple
     * flushes while the handshake is still ongoing, then the handshake "randomly"
     * times out. Not sure at this point why this is happening. Doing a single flush
     * seems to work but multiple flushes don't ...
     */
    flushRequested = true;
  }

  /**
   * If we are still performing protocol negotiation, then this will propagate failures to all
   * buffered writes.
   */
  @Override
  public void close(ChannelHandlerContext ctx, ChannelPromise future) throws Exception {
    Status status = Status.UNAVAILABLE.withDescription(
        "Connection closing while performing protocol negotiation for " + ctx.pipeline().names());
    failWrites(status.asRuntimeException());
    super.close(ctx, future);
  }

  @SuppressWarnings("FutureReturnValueIgnored")
  final void writeBufferedAndRemove(ChannelHandlerContext ctx) {
    // TODO(carl-mastrangelo): remove the isActive check and just fail if not yet ready.
    if (!ctx.channel().isActive() || writing) {
      return;
    }
    // Make sure that method can't be reentered, so that the ordering
    // in the queue can't be messed up.
    writing = true;
    while (!bufferedWrites.isEmpty()) {
      ChannelWrite write = bufferedWrites.poll();
      ctx.write(write.msg, write.promise);
    }
    if (flushRequested) {
      ctx.flush();
    }
    // Removal has to happen last as the above writes will likely trigger
    // new writes that have to be added to the end of queue in order to not
    // mess up the ordering.
    ctx.pipeline().remove(this);
  }

  /**
   * Propagate failures to all buffered writes.
   */
  @SuppressWarnings("FutureReturnValueIgnored")
  private void failWrites(Throwable cause) {
    if (failCause == null) {
      failCause = cause;
    } else {
      logger.log(Level.FINE, "Ignoring duplicate failure", cause);
    }
    while (!bufferedWrites.isEmpty()) {
      ChannelWrite write = bufferedWrites.poll();
      write.promise.setFailure(cause);
      ReferenceCountUtil.release(write.msg);
    }
  }

  private static final class ChannelWrite {
    final Object msg;
    final ChannelPromise promise;

    ChannelWrite(Object msg, ChannelPromise promise) {
      this.msg = msg;
      this.promise = promise;
    }
  }
}


text:
function run(argv) {
  // Obtain the terminal application
  var terminal = Application('Terminal');

  // Grab the Pro profile
  proSettings = terminal.settingsSets.Pro;

  // Set the font
  proSettings.fontName = 'Source Code Pro for Powerline';
  proSettings.fontSize = 16;
  proSettings.fontAntialiasing = true;

  // Set the window size
  proSettings.numberOfRows = 26;
  proSettings.numberOfColumns = 130;

  // Set the default profile to Pro
  terminal.defaultSettings = proSettings;

  // Set the profile to Pro for all open windows and tabs
  for (var window of terminal.windows()) {
    for (var tab of window.tabs()) {
      tab.currentSettings = proSettings;
    }
  }
  terminal.quit
}


text:
package org.springframework.boot.configurationsample.specific;

import org.springframework.boot.configurationsample.ConfigurationProperties;
import org.springframework.boot.configurationsample.ConstructorBinding;
import org.springframework.boot.configurationsample.DefaultValue;

/**
 * Demonstrates that an invalid default character value leads to a compilation failure.
 *
 * @author Stephane Nicoll
 */
@ConfigurationProperties("test")
public class InvalidDefaultValueCharacterProperties {

	private final char letter;

	@ConstructorBinding
	public InvalidDefaultValueCharacterProperties(@DefaultValue("bad") char letter) {
		this.letter = letter;
	}

	public char getLetter() {
		return this.letter;
	}

}


text:
gem 'minitest'
require 'minitest/autorun'
require 'minitest/pride'
require './beer_song'

class BeerSongTest < Minitest::Test

  def beer_song
    @beer_song = Beer::Song.new
  end

  def teardown
    @beer_song = nil
  end

  def test_a_typical_verse
    expected =
      "8 bottles of beer on the wall, 8 bottles of beer.\n" +
      "Take one down and pass it around, 7 bottles of beer on the wall.\n"
    assert_equal expected, beer_song.verse(8)
  end

  def test_another_typical_verse
    expected =
      "3 bottles of beer on the wall, 3 bottles of beer.\n" +
      "Take one down and pass it around, 2 bottles of beer on the wall.\n"
    assert_equal expected, beer_song.verse(3)
  end
  def test_verse_1
    expected =
      "1 bottle of beer on the wall, 1 bottle of beer.\n" +
      "Take it down and pass it around, no more bottles of beer on the wall.\n"
    assert_equal expected, beer_song.verse(1)
  end

  def test_verse_2
    expected =
      "2 bottles of beer on the wall, 2 bottles of beer.\n" +
      "Take one down and pass it around, 1 bottle of beer on the wall.\n"
    assert_equal expected, beer_song.verse(2)
  end

  def test_verse_0
    expected =
      "No more bottles of beer on the wall, no more bottles of beer.\n" +
      "Go to the store and buy some more, 99 bottles of beer on the wall.\n"
    assert_equal expected, beer_song.verse(0)
  end

  def test_several_verses
    expected =
      "8 bottles of beer on the wall, 8 bottles of beer.\n" +
      "Take one down and pass it around, 7 bottles of beer on the wall.\n\n" +
      "7 bottles of beer on the wall, 7 bottles of beer.\n" +
      "Take one down and pass it around, 6 bottles of beer on the wall.\n\n" +
      "6 bottles of beer on the wall, 6 bottles of beer.\n" +
      "Take one down and pass it around, 5 bottles of beer on the wall.\n\n"
    assert_equal expected, beer_song.verses(8, 6)
  end

  def test_all_the_rest_of_the_verses
    expected =
      "3 bottles of beer on the wall, 3 bottles of beer.\n" +
      "Take one down and pass it around, 2 bottles of beer on the wall.\n" +
      "\n" +
      "2 bottles of beer on the wall, 2 bottles of beer.\n" +
      "Take one down and pass it around, 1 bottle of beer on the wall.\n" +
      "\n" +
      "1 bottle of beer on the wall, 1 bottle of beer.\n" +
      "Take it down and pass it around, no more bottles of beer on the wall.\n" +
      "\n" +
      "No more bottles of beer on the wall, no more bottles of beer.\n" +
      "Go to the store and buy some more, 99 bottles of beer on the wall.\n" +
      "\n"
    assert_equal expected, beer_song.verses(3)
  end
end


text:
<?php namespace Pixiu\Commerce\Models;

use Model;
use October\Rain\Database\Traits\Validation;
use Pixiu\Commerce\Traits\LocalizedValidation;

/**
 * Tax Model
 */
class Tax extends Model
{
    use Validation;
    use LocalizedValidation;

    public $rules = [];

    public function __construct()
    {
        parent::__construct();

        $this->localizeValidation();
        $this->rules = [
            'name' => 'required',
            'rate' => 'required|numeric|min:0'
        ];
    }

    /**
     * @var string The database table used by the model.
     */
    public $table = 'pixiu_com_taxes';

    /**
     * @var array Guarded fields
     */
    protected $guarded = ['*'];

    /**
     * @var array Fillable fields
     */
    protected $fillable = [];

    /**
     * @var array Relations
     */
    public $hasOne = [];
    public $hasMany = [];
    public $belongsTo = [];
    public $belongsToMany = [];
    public $morphTo = [];
    public $morphOne = [];
    public $morphMany = [];
    public $attachOne = [];
    public $attachMany = [];

    public function getQualifiedNameAttribute()
    {
        return $this->name . ' (' . $this->rate . '%)';
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
A Revision of the Species Described in Phyllosticta (Utrecht) 35 (2002)

#### Original name
Phyllostictina kamatii Golatkar

### Remarks
null


text:
package net.metanotion.util;

/** This interface is to be used with the EventCalculator class. It represents a
function which knows how to "calculate"(or instantiate) the next state for a finite
state machine when given the event type and the current state. Implementations
need not handle all possible event classes, as the purporse of event calculator is
to select the proper handler from the event.getClass()/interfaces.
	@param <S> Type type states this event handler operates on and generates.
*/
public interface EventHandler<S extends State> {
	/** Calculate the next state of the machine given the current state and an event.
		@param event The event that just occurred.
		@param currentState The current state of the finite state machine.
		@return The object representing the next state of the machine.
	*/
	public S nextState(Object event, S currentState);
}


text: Rails.application.config.session_store :cookie_store, key: '_ajax-crud_session'


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable

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

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

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

    See the License for the specific language governing permissions and
    limitations under the License.
-->
<!DOCTYPE Test SYSTEM "test.dtd">
<!--
Author:  Alexander D. Shipilov
Version: $Revision: 1.3 $
-->
<Test
  ID="ddiv1301"
  date-of-creation="2005-02-04"
  timeout="1"
  >
  <Author value="Alexander D. Shipilov"/>
  <Description>
      Tests ddiv instruction.
      ddiv of positive value and -0.0. Result must be negative infinity.

      Covered assertions assert_instr23a117 assert_concept070 assert_over066
  </Description>

  <Source name="ddiv1301p.j"/>

  <Runner ID="Runtime">
    <Param name="toRun" value="org.apache.harmony.vts.test.vm.jvms.instructions.arithm.ddiv.ddiv13.ddiv1301.ddiv1301p"/>
  </Runner>
</Test>


text:
package org.aakretech.istgame.gui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;

/**
 * Listener that registers clicking on the Guess buttons
 *
 * @author Erlend Aakre
 */
public class GuessButtonListener extends MouseAdapter {

    private GameWindow gameWindow;

    /**
     * Creates a new listener
     *
     * @param gameWindow the main game window
     */
    public GuessButtonListener(GameWindow gameWindow) {
        this.gameWindow = gameWindow;
    }

    /**
     * called to handle mouse presses on a guess button
     *
     * @param e the mouse event
     */
    @Override
    public void mousePressed(MouseEvent e) {
        int guess = (Integer) ((JLabel) e.getSource()).getClientProperty("guess");
        System.out.println("PLAYER " + gameWindow.getGame().getCurrentPlayer().getName() + " GUESSED " + guess);
        gameWindow.getGame().guess(guess);
        gameWindow.getBoardPanel().playerGuessed();
        gameWindow.getControlPanel().resetGameForNewRound();
        gameWindow.checkForWinner();
    }
}


text:
.class public final Lcom/sec/android/glview/HoverPopupWindow$Gravity;
.super Ljava/lang/Object;
.source "HoverPopupWindow.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/sec/android/glview/HoverPopupWindow;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "Gravity"
.end annotation

# static fields
.field public static final BOTTOM_UNDER:I = 0x5050

.field public static final CENTER_HORIZONTAL:I = 0x1

.field public static final HORIZONTAL_GRAVITY_MASK:I = 0xf0f

.field public static final LEFT:I = 0x3

.field public static final NO_GRAVITY:I = 0x0

.field public static final RIGHT:I = 0x5

.field public static final SCREEN_BOUNDARY:I = 0x301

.field public static final TOP_ABOVE:I = 0x3030

.field public static final VERTICAL_GRAVITY_MASK:I = 0xf0f0

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 1427
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method


text:
test2!
pulling in changes


text:
namespace MosesTraining
{
namespace Syntax
{
namespace PostprocessEgretForests
{

class Forest
{
public:
  struct Vertex;

  struct Hyperedge {
    double weight;
    Vertex *head;
    std::vector<Vertex *> tail;
  };

  struct Vertex {
    Symbol symbol;
    int start;
    int end;
    std::vector<boost::shared_ptr<Hyperedge> > incoming;
  };

  Forest() {}

  std::vector<boost::shared_ptr<Vertex> > vertices;

private:
  // Copying is not allowed.
  Forest(const Forest &);
  Forest &operator=(const Forest &);
};

}  // namespace PostprocessEgretForests
}  // namespace Syntax
}  // namespace MosesTraining


text:
package org.kie.workbench.common.screens.datamodeller.client.widgets.advanceddomain.valuepaireditor;

import javax.annotation.PostConstruct;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;

import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import org.kie.workbench.common.services.datamodeller.core.AnnotationValuePairDefinition;

@Dependent
public class ValuePairEditorPopup
    implements IsWidget,
        ValuePairEditorPopupView.Presenter {

    @Inject
    private ValuePairEditorPopupView view;

    private ValuePairEditorPopupView.ValuePairEditorPopupHandler popupHandler;

    private AnnotationValuePairDefinition valuePairDefinition;

    private String annotationClassName;

    public ValuePairEditorPopup() {
    }

    @PostConstruct
    private void init( ) {
        view.setPresenter( this );
    }

    public void init( String annotationClassName, AnnotationValuePairDefinition valuePairDefinition ) {
        this.annotationClassName = annotationClassName;
        this.valuePairDefinition = valuePairDefinition;
        view.init( valuePairDefinition );
    }

    @Override
    public Widget asWidget() {
        return view.asWidget();
    }

    public void clear() {
        view.clear();
    }

    public void addPopupHandler( ValuePairEditorPopupView.ValuePairEditorPopupHandler popupHandler ) {
        this.popupHandler = popupHandler;
    }

    public boolean isGenericEditor() {
        return view.isGenericEditor();
    }

    public boolean isValid() {
        return view.isValid();
    }

    @Override
    public void onOk() {
        if ( popupHandler != null ) {
            popupHandler.onOk();
        }
    }

    @Override
    public void onCancel() {
        if ( popupHandler != null ) {
            popupHandler.onCancel();
        }
    }

    @Override
    public void onClose() {
        if ( popupHandler != null ) {
            popupHandler.onClose();
        }
    }

    @Override
    public void onValidate() {

    }

    @Override
    public void onValueChange() {

    }

    public AnnotationValuePairDefinition getValuePairDefinition() {
        return valuePairDefinition;
    }

    public void setErrorMessage( String errorMessage ) {
        view.setErrorMessage( errorMessage );
    }

    public void cleanErrorMessage() {
        view.clearErrorMessage();
    }

    public String getAnnotationClassName() {
        return annotationClassName;
    }

    public void setValue( Object value ) {
        view.setValue( value );
    }

    public Object getValue() {
        return view.getValue();
    }

    public void show() {
        view.show();
    }

    public void hide() {
        view.hide();
    }
}


text:
var mockProcess = new (require('events').EventEmitter)()
mockProcess.nextTick = process.nextTick
mockProcess.hrtime = function (last) {
  var now = typeof performance !== 'undefined' && performance.now ?
    performance.now() : +new Date
  return [now / 1e3 - (last && last[0] || 0), 0]
}
var origSetTimeout = setTimeout
var test = require('tape-catch-onerror')
test('test-timers-linked-list.js', function (tape) {
  var process = mockProcess
  var timers = require('../timers')
  var setTimeout = timers.setTimeout
  var clearTimeout = timers.clearTimeout
  var setInterval = timers.setInterval
  var clearInterval = timers.clearInterval
  var setImmediate = timers.setImmediate
  var clearImmediate = timers.clearImmediate

// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// var common = require('../common');
var assert = require('assert');
var L = require('../_linklist');

var list = { name: 'list' };
var A = { name: 'A' };
var B = { name: 'B' };
var C = { name: 'C' };
var D = { name: 'D' };

L.init(list);
L.init(A);
L.init(B);
L.init(C);
L.init(D);

assert.ok(L.isEmpty(list));
assert.equal(null, L.peek(list));

L.append(list, A);
// list -> A
assert.equal(A, L.peek(list));

L.append(list, B);
// list -> A -> B
assert.equal(A, L.peek(list));

L.append(list, C);
// list -> A -> B -> C
assert.equal(A, L.peek(list));

L.append(list, D);
// list -> A -> B -> C -> D
assert.equal(A, L.peek(list));

var x = L.shift(list);
assert.equal(A, x);
// list -> B -> C -> D
assert.equal(B, L.peek(list));

x = L.shift(list);
assert.equal(B, x);
// list -> C -> D
assert.equal(C, L.peek(list));

// B is already removed, so removing it again shouldn't hurt.
L.remove(B);
// list -> C -> D
assert.equal(C, L.peek(list));

// Put B back on the list
L.append(list, B);
// list -> C -> D -> B
assert.equal(C, L.peek(list));

L.remove(C);
// list -> D -> B
assert.equal(D, L.peek(list));

L.remove(B);
// list -> D
assert.equal(D, L.peek(list));

L.remove(D);
// list
assert.equal(null, L.peek(list));

assert.ok(L.isEmpty(list));

L.append(list, D);
// list -> D
assert.equal(D, L.peek(list));

L.append(list, C);
L.append(list, B);
L.append(list, A);
// list -> D -> C -> B -> A

// Append should REMOVE C from the list and append it to the end.
L.append(list, C);

// list -> D -> B -> A -> C
assert.equal(D, L.shift(list));
// list -> B -> A -> C
assert.equal(B, L.peek(list));
assert.equal(B, L.shift(list));
// list -> A -> C
assert.equal(A, L.peek(list));
assert.equal(A, L.shift(list));
// list -> C
assert.equal(C, L.peek(list));
assert.equal(C, L.shift(list));
// list
assert.ok(L.isEmpty(list));

  origSetTimeout(function () {
    process.emit('exit')
    tape.pass()
    tape.end()
  }, 0)
})


text:
package tictactoe.network.rpcprotocol;

import java.io.Serializable;

public class Response implements Serializable
{
    private ResponseType type;
    private Object       data;

    private Response()
    {
    }

    public ResponseType getType()
    {
        return type;
    }

    private void setType(ResponseType type)
    {
        this.type = type;
    }

    public Object getData()
    {
        return data;
    }

    private void setData(Object data)
    {
        this.data = data;
    }

    @Override
    public String toString()
    {
        return "Response{" +
            "setType='" + type + '\'' +
            ", getData='" + data + '\'' +
            '}';
    }

    public static class Builder
    {
        private Response response = new Response();

        public Builder type(ResponseType type)
        {
            response.setType(type);
            return this;
        }

        public Builder data(Object data)
        {
            response.setData(data);
            return this;
        }

        public Response build()
        {
            return response;
        }
    }
}


text:
Predictor generates the predicted trajectory for each obstacle. Here assume we want to add a new predictor for vehicle, for other types of obstacles, the procedure is very similar.

## Steps to add a new predictor
Please follow the steps to add a new predictor named `NewPredictor`.

### Step 1: Define a class that inherits `Predictor`
Create a new file named `new_predictor.h` in the folder  `modules/prediction/predictor/vehicle`. And define it like this:
```cpp

#include "modules/prediction/predictor/predictor.h"

namespace apollo {
namespace prediction {

class NewPredictor : public Predictor {
 public:
  void Predict(Obstacle* obstacle) override;
  // Other useful functions and fields.
};

}  // namespace prediction
}  // namespace apollo
```

### Step 2 Implement the class `NewPredictor`
Create a new file named `new_predictor.cc` in the same folder of `new_predictor.h`. Implement it like this:
```cpp
#include "modules/prediction/predictor/vehicle/new_predictor.h"

namespace apollo {
namespace prediction {

NewPredictor::Predict(Obstacle* obstacle)() {
  // Get the results from evaluator
  // Generate the predicted trajectory
}

// Other functions

}  // namespace prediction
}  // namespace apollo

```
### Step 3: Update prediction conf
In the file `modules/prediction/conf/prediction_conf.pb.txt`, update the field `predictor_type` like this:
```
obstacle_conf {
  obstacle_type: VEHICLE
  obstacle_status: ON_LANE
  evaluator_type: NEW_EVALUATOR
  predictor_type: NEW_PREDICTOR
}
```

### Step 4: Upate predictor manager
Update `vehicle_on_lane_predictor_` in `modlues/prediction/predictor/predictor_manager.h` like this:
```cpp
ObstacleConf::PredictorType vehicle_on_lane_predictor_ =
    ObstacleConf::NEW_PREDICTOR;
```

After this procedure, the new predictor will be created.


text:
using Microsoft.Extensions.DependencyInjection;
using TIKSN.Data;
using TIKSN.Finance.ForeignExchange.Data;
using TIKSN.Finance.ForeignExchange.Data.LiteDB;

namespace TIKSN.Finance.ForeignExchange.LiteDB
{
    public class DataEntityMapperProfile : MapperProfile
    {
        public DataEntityMapperProfile(IServiceCollection services) : base(services)
        {
            AddMapper<ExchangeRateEntity, ExchangeRateDataEntity>();
            AddMapper<ExchangeRateDataEntity, ExchangeRateEntity>();

            AddMapper<ForeignExchangeEntity, ForeignExchangeDataEntity>();
            AddMapper<ForeignExchangeDataEntity, ForeignExchangeEntity>();
        }
    }
}


text:
from glanceclient import client as gc
from glanceclient import exc
from oslo_log import log as logging
from oslo_utils import uuidutils

from heat.common import exception
from heat.common.i18n import _
from heat.common.i18n import _LI
from heat.engine.clients import client_plugin
from heat.engine import constraints

LOG = logging.getLogger(__name__)

class GlanceClientPlugin(client_plugin.ClientPlugin):

    exceptions_module = exc

    service_types = [IMAGE] = ['image']

    def _create(self):

        con = self.context
        endpoint_type = self._get_client_option('glance', 'endpoint_type')
        endpoint = self.url_for(service_type=self.IMAGE,
                                endpoint_type=endpoint_type)
        args = {
            'auth_url': con.auth_url,
            'service_type': self.IMAGE,
            'project_id': con.tenant_id,
            'token': self.auth_token,
            'endpoint_type': endpoint_type,
            'cacert': self._get_client_option('glance', 'ca_file'),
            'cert_file': self._get_client_option('glance', 'cert_file'),
            'key_file': self._get_client_option('glance', 'key_file'),
            'insecure': self._get_client_option('glance', 'insecure')
        }

        return gc.Client('1', endpoint, **args)

    def is_not_found(self, ex):
        return isinstance(ex, exc.HTTPNotFound)

    def is_over_limit(self, ex):
        return isinstance(ex, exc.HTTPOverLimit)

    def is_conflict(self, ex):
        return isinstance(ex, exc.HTTPConflict)

    def get_image_id(self, image_identifier):
        """Return the ID for the specified image name or identifier.

        :param image_identifier: image name or a UUID-like identifier
        :returns: the id of the requested :image_identifier:
        :raises: exception.EntityNotFound,
                 exception.PhysicalResourceNameAmbiguity
        """
        if uuidutils.is_uuid_like(image_identifier):
            try:
                image_id = self.client().images.get(image_identifier).id
            except exc.HTTPNotFound:
                image_id = self.get_image_id_by_name(image_identifier)
        else:
            image_id = self.get_image_id_by_name(image_identifier)
        return image_id

    def get_image_id_by_name(self, image_identifier):
        """Return the ID for the specified image name.

        :param image_identifier: image name
        :returns: the id of the requested :image_identifier:
        :raises: exception.EntityNotFound,
                 exception.PhysicalResourceNameAmbiguity
        """
        try:
            filters = {'name': image_identifier}
            image_list = list(self.client().images.list(filters=filters))
        except exc.ClientException as ex:
            raise exception.Error(
                _("Error retrieving image list from glance: %s") % ex)
        num_matches = len(image_list)
        if num_matches == 0:
            LOG.info(_LI("Image %s was not found in glance"),
                     image_identifier)
            raise exception.EntityNotFound(entity='Image',
                                           name=image_identifier)
        elif num_matches > 1:
            LOG.info(_LI("Multiple images %s were found in glance with name"),
                     image_identifier)
            raise exception.PhysicalResourceNameAmbiguity(
                name=image_identifier)
        else:
            return image_list[0].id

class ImageConstraint(constraints.BaseCustomConstraint):

    expected_exceptions = (exception.EntityNotFound,)

    def validate_with_client(self, client, value):
        client.client_plugin('glance').get_image_id(value)


text:
namespace gfx {

// This should return the thickness, in pixels, of a scrollbar in web content.
// This needs to match the values in WebCore's
// ScrollbarThemeChromiumXXX.cpp::scrollbarThickness().
UI_EXPORT int scrollbar_size();

}  // namespace gfx

#endif  // UI_GFX_SCROLLBAR_SIZE_H_